除非我打印每一行,否则读取多行输入总是运行无限循环
reading multiple lines of input always runs an infinite loop unless I print each line
我正在尝试使用 Java 中的扫描仪处理来自控制台的多行输入,并且它在无限循环中运行,除非我打印出每一行。出于某种原因,下一行不是 'consumed' 除非我打印它。我不想打印它,我只想将每一行添加到一个数组中以便稍后处理,所以我不知道如何 'consume' 每行 w/o 打印它。这两个循环都是无限的:
while(sc.hasNext()) {
String line = sc.nextLine();
commands.add(line);
//System.out.println(line);
sc.nextLine();
}
while(sc.hasNext()) {
String line = sc.nextLine();
commands.add(line);
//System.out.println(line);
//sc.nextLine();
}
编辑:
我的扫描仪初始化如下,我也将条件编辑为 hasNextLine(),仍然是 运行 无限循环。打印 "done" 的打印语句永远不会执行。
Scanner sc = new Scanner(System.in);
ArrayList<String> commands = new ArrayList<String>();
while(sc.hasNextLine()) {
String line = sc.nextLine();
commands.add(line);
//System.out.println(line);
//sc.nextLine();
}
System.out.println("done");
你应该打电话给 hasNextLine()
,而不是 hasNext()
。
印刷与此无关。打印不会终止循环。
EDIT 如果你从未看到你的最终 "done"
,这根本不是一个无限循环,它是一个 block:您永远不会将流的结尾发送到 System.in
。输入 Ctrl/d 或 Ctrl/z 取决于 Windows 与 Unix/Linux/... 再一次,打印与它无关。
我正在尝试使用 Java 中的扫描仪处理来自控制台的多行输入,并且它在无限循环中运行,除非我打印出每一行。出于某种原因,下一行不是 'consumed' 除非我打印它。我不想打印它,我只想将每一行添加到一个数组中以便稍后处理,所以我不知道如何 'consume' 每行 w/o 打印它。这两个循环都是无限的:
while(sc.hasNext()) {
String line = sc.nextLine();
commands.add(line);
//System.out.println(line);
sc.nextLine();
}
while(sc.hasNext()) {
String line = sc.nextLine();
commands.add(line);
//System.out.println(line);
//sc.nextLine();
}
编辑: 我的扫描仪初始化如下,我也将条件编辑为 hasNextLine(),仍然是 运行 无限循环。打印 "done" 的打印语句永远不会执行。
Scanner sc = new Scanner(System.in);
ArrayList<String> commands = new ArrayList<String>();
while(sc.hasNextLine()) {
String line = sc.nextLine();
commands.add(line);
//System.out.println(line);
//sc.nextLine();
}
System.out.println("done");
你应该打电话给 hasNextLine()
,而不是 hasNext()
。
印刷与此无关。打印不会终止循环。
EDIT 如果你从未看到你的最终 "done"
,这根本不是一个无限循环,它是一个 block:您永远不会将流的结尾发送到 System.in
。输入 Ctrl/d 或 Ctrl/z 取决于 Windows 与 Unix/Linux/... 再一次,打印与它无关。