使用 Scanner.nextLine() 方法的计时



摘自教科书"Java 中的数据结构和算法,6/e"的第 40 页 (代码略有修改):

Scanner scanner = new Scanner(System.in);
System.out.print("Please enter an integer: ");
while (!scanner.hasNextInt()) {
scanner.nextLine();
System.out.print("Invalid int; pls enter an int: ");
}
int i = scanner.nextInt();
System.out.print(i);

如果我按 System.in 键入一个非整数值(即:1.0),它将进入 while 循环体,因为!scanner.hasNextInt()的布尔值为真。

但是我不明白作者在第 4 行的 while 循环中放入另一行scanner.nextLine();的语法,它会生成什么吗?为什么如果我删除scanner.nextLine();行,程序无法工作?(不知何故,删除后PC内存几乎已满..)

@Guy说的是正确的。hasNext函数调用不会执行任何操作来推进输入指针。hasNextInt检查下一个输入是否为整数,但要前进到此输入后的下一行,您需要调用next函数。否则,您将永远检查非整数输入的hasNextInt,进入无限循环,这就是您的内存使用率超高的原因。

相关内容

最新更新