[英]How to read last line with Scanner.nextLine()?
I'm working on homework and i have to read input with nextLine() method. 我正在做作业,我必须使用nextLine()方法读取输入。 When i copied all input lines and pasted on console, the program don't read final line. 当我复制所有输入行并将其粘贴到控制台时,该程序不会读取最后一行。 How can i solve this problem. 我怎么解决这个问题。
What i need : 我需要的 :
line1
line2
line3
What i get: 我得到什么:
line1
line2
Here is my code 这是我的代码
public class Name{
public static void main(String [] args){
Scanner scn = new Scanner(System.in);
str = scn.nextLine();
while(scn.hasNextLine()){
.
.
.
str = scn.nextLine();
}
scn.close();
}
}
I don't see any reason to check for null
- you should be using scn.hasNextLine()
instead, which will stop iteration when there are no more lines in the file for the Scanner
to read. 我看不出有任何理由要检查null
-你应该使用scn.hasNextLine()
代替,当有文件为中没有更多的线,将停止迭代Scanner
来读取。
Here's a code sample - we move the reading of System.in
into the loop, and add a stopping condition so you don't get an infinite loop. 这是一个代码示例-我们将System.in
的读数移入循环,并添加一个停止条件,这样您就不会陷入无限循环。
Scanner scn = new Scanner(System.in);
String str;
while(scn.hasNextLine()){
str = scn.nextLine();
System.out.println(str);
if(str.equalsIgnoreCase("stop")) {
break;
}
}
How about 怎么样
public void main(String [] args){
Scanner scn = new Scanner(System.in);
while (scn.hasNextLine()) {
String str = scn.nextLine();
System.out.println(str);
}
// don't close System.in as we didn't create it.
}
When I run 当我跑步
$ cat > text
line1
line2
line3
^D
$ java -cp . Example < text
line1
line2
line3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.