while ( input.hasNext() ) {
i = input.nextInt();
//System.out.println();
System.out.print("Bla: ");
}
这只是一个测试应用程序/代码。当我按下 ctrl+z 时,我只听到 ding Windows 声音(也就是你做错了声音 <.<),但没有任何反应,程序继续正常运行。我在另一个应用程序中对其进行了测试,input.hasNext() 确实返回了正确的 True boolean 值,只是无法识别 Ctrl+Z。使用 Netbeans 6.9.1 和 Windows 7。
最佳答案
在 Windows 7 平台上,CTRL-Z 确实会在 System.in 的控制台输入流中结束输入。
它有助于理解其工作方式。大量的 Scanner 方法,特别是 hasNext... 和 next... 方法,会阻止执行,直到某些内容出现在 System.in 字节流中,这些内容正在被实例化的 Scanner 对象处理。一旦有某种输入,这些方法将解除阻塞并按照它们所宣传的那样继续进行。
如果输入是输入流的结尾(即 Windows 中的 CTRL-Z,UNIX/Linux 中的 CTRL-D),hasNext... 方法将返回 boolean 值 false。如果 hasNext... 特定于原语或其他类型,则仅当输入解析为 hasNext... 测试的有效原语或对象类型时,它才会返回 boolean 值 true,否则它将返回 false。
在 hasNext() 的情况下,它不是原始的或特定于对象的,因此除了输入流结束之外的任何输入都将返回 true。这使得它对于这个问题所暗示的那种确定非常有用。
以下代码适用于 Windows 7 Ultimate 平台,它使用更通用的 nextLine() 方法而不是 nextInt() 方法来演示其工作原理。 nextInt() 方法将用户限制为整数,如果输入的不是输入末尾或对于 int 基元来说不是太大的整数,则会抛出异常。此代码将回显用户输入的任何内容,直到输入字符结束。
// ControlZEndInputTestApp.java
// Demonstrate how end of input
// works with Scanner.hasNext() method
import java.util.Scanner;
public class ControlZEndInputTestApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// hasNext() blocks until something appears in the System.in
// byte stream being processed by Scanner or an end of stream
// occurs which is CTRL-Z in Windows and CTRL-D in UNIX/Linux
// When hasNext() unblocks, it returns boolean false
// if the stream ended or boolean true if the input was anything else
// other than an end of input stream
// repeat as long as we don't receive an end of input
// i.e. CTRL-Z on Windows or CTRL-D on UNIX/Linux...
while ( input.hasNext() ) {
System.out.println(input.nextLine());
}
}
}
关于java - Netbeans - input.hasNext() 在按下 ctrl+z 时什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4742445/