Note: If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String empty = scan.nextLine();
//this is the change to get the "enther key"
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
本文介绍了一个常见的Java编程陷阱:当使用Scanner类读取输入时,nextInt()方法之后紧接着使用nextLine()方法的问题。nextInt()读取整数并留下换行符在缓冲区中,导致nextLine()实际上读取的是空行。文章通过示例代码展示了如何解决这个问题。
153

被折叠的 条评论
为什么被折叠?



