简体   繁体   English

Nextline和扫描程序是否忽略Java中的行?

[英]Nextline and scanner ignoring lines in Java?

Scanner s = new Scanner (System.in);
while(!s.nextLine().isEmpty()){

a.add(i, s.nextLine());
i++;
}

System.out.println(a.size());

I created an Arraylist because I was copy and pasting an unknown amount of strings into the ide to be scanned, which may be an issue for the end of line. 我创建了一个Arraylist,因为我正在将未知数量的字符串复制并粘贴到要扫描的ide中,这可能是行尾的问题。

I was testing out three lines by pasting them in. For example take the following example: 我通过粘贴将三行测试出来。例如,请看以下示例:

Hello
World
Again

I would copy and paste them in and the size of the Arraylist would be 2 and it would be World which would occupy at position 0. 我将其复制并粘贴到其中,Arraylist的大小将为2,并且将是World,它将占据位置0。

My own theory is that he while loop takes the first line to check whether it is empty and then the second line is put into the Arraylist with the third being checked and a blank being put into the second position. 我自己的理论是,他的while循环使用第一行来检查它是否为空,然后将第二行放入Arraylist中,并检查第三行,并在第二行中放置一个空白。

Then there is the pasting of the strings in the format of three lines and then pressing enter once which may affect the end of line. 然后以三行格式粘贴字符串,然后按一次Enter键,这可能会影响行尾。 Does anyone have any insight into what is going on? 有谁对正在发生的事情有任何见识? Thanks, 谢谢,

You need to "capture" the line to be tested rather than throwing it away. 您需要“捕获”要测试的行,而不是将其丢弃。 Each call to s.nextLine() reads a line. 每次调用s.nextLine()读取一行。

Scanner s = new Scanner (System.in);
String line;
while(!(line = s.nextLine()).isEmpty()){
    a.add(i, line);
    i++;
}

System.out.println(a.size());

Or as others have mentioned, you can use s.hasNext() as the loop condition as follows: 或者像其他人提到的那样,您可以使用s.hasNext()作为循环条件,如下所示:

Scanner s = new Scanner (System.in);
while(s.hasNext()) {
    a.add(i, s.nextLine());
    i++;
}

System.out.println(a.size());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM