简体   繁体   English

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

[英]the timing of using the Scanner.nextLine() method

From P.40 of the textbook 'Data Structures and Algorithms in Java, 6/e' (the code is slightly revised): 从教科书“Java中的数据结构和算法,6 / e”(代码略有修改)的P.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);

If I type a non-integer value(that's to say: 1.0) by System.in, it would enter the while loop body since the boolean of !scanner.hasNextInt() is true. 如果我通过System.in键入一个非整数值(也就是说:1.0),它将进入while循环体,因为!scanner.hasNextInt()的布尔值为true。

However I don't understand the syntax the author puts in another line of scanner.nextLine(); 但是,我不理解作者在另一行scanner.nextLine();的语法scanner.nextLine(); inside the while loop in Line 4, does it generate anything? 在第4行的while循环中,是否会生成任何内容? Why can't the program work if I delete the scanner.nextLine(); 如果删除scanner.nextLine();为什么程序无法正常工作scanner.nextLine(); line? 线? (and somehow pc memory almost get full after deleting it..) (以某种方式,删除它后,pc内存几乎已满了..)

What @Guy said is correct. @Guy说的是对的。 The hasNext function call does not do anything to advance your input pointer. hasNext函数调用不会对您的输入指针进行任何操作。 hasNextInt checks if your next input is an integer, but to advance to the next line after this input, you need to call a next function. hasNextInt检查您的下一个输入是否为整数,但是在此输入之后前进到下一行,您需要调用next函数。 Otherwise, you will forever be checking hasNextInt on your non-integer input, going into an infinite loop, which is why your memory usage is super high. 否则,您将永远在非整数输入上检查hasNextInt ,进入无限循环,这就是您的内存使用率超高的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM