mPi*_*rce 6 java while-loop java.util.scanner
我在使用 java 的 Scanner 类时遇到了麻烦。我可以让它很好地读取我的输入,但问题是当我想输出一些东西时。给定多行输入,我想在完全读取所有输入后仅打印一行。这是我用来读取输入的代码:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in); //scanner reads block of input
while(scanner.hasNextLine()){
//body of loop goes here
String s = scanner.nextLine();
Scanner ls = new Scanner(s); //scanner to parse a line of input
while(ls.hasNext()){
//body of nested loop goes here
ls.next();
}
}
System.out.println("Fin");
}
Run Code Online (Sandbox Code Playgroud)
即使已读取所有输入行,程序也不会到达 System.out.println 消息。(请注意,该消息不能发送到其他任何地方,否则它将按照循环运行的次数输出)。我该如何解决?任何帮助将不胜感激。
在这种情况下,您正在从无限流中读取数据。hasNextLine()如果此扫描仪的输入中有另一行,将继续返回 true。作为 a System.in,它将继续从键盘读取,除非您终止它或告诉流停止。
最后按“ctrl+Z”,你会看到它起作用了。
编辑:你可以做这样的事情......
Scanner scanner = new Scanner(System.in); //scanner reads block of input
int BLOCK_SIZE =3,count=1;
while(scanner.hasNextLine()){
//body of loop goes here
String s = scanner.nextLine();
Scanner ls = new Scanner(s); //scanner to parse a line of input
while(ls.hasNext()){
//body of nested loop goes here
ls.next();
}
if(count++==BLOCK_SIZE)
{
break;
}
}
System.out.println("Fin");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21046 次 |
| 最近记录: |