我尝试读取的输入文件包含第一行条目 block 的行数以及后续行的记录。该文件可能包含许多这样的 block 。例如:
3
a b c
a b
a c b //Three in the first line tells that there are 3 subsequent lines.
2
a b
a b c
0 //the input ends here
我试图使用 while 循环一次读取一个 block ,处理它,然后读取另一个 block 。然而,该代码仅在有一个 block 时才有效。当有多个 block 时,它会卡住。有人可以帮助找出问题所在吗?谢谢你!
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
while (s.hasNextLine()){
String number = s.nextLine();
if (line.equals("0")){
break;
}else {
int n = Integer.parseInt(number);
for (int i=0; i<n; i++){
String letters= s.nextLine();
...
//do something to store the lines of letters
}
}
}
}
最佳答案
退出 while
循环的最佳方法(除了仔细使用控制条件之外)是使用 break
语句。
System.exit(0)
将关闭 Java 虚拟机并将状态代码 0 返回给操作系统。这有点激烈。状态代码 0 通常用于指示成功:因此您的返回值是特殊的。
总而言之,您当前的问题是打印问题,请从 if
中删除 !
:
if (line.equals("0")){
关于java while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26032461/