Scanner in = new Scanner(System.in);
for (int i = 1; i <= 6; i++) {
System.out.print("Name: ");
in.nextLine();
System.out.print("Age: ");
in.nextInt()
}
I expect the output of:
姓名:大卫·奥巴马
年龄:14
姓名:艾娃·奥米迪
年龄:53
等等
but this is my output and only once nextLine() is used:
姓名:大卫·奥巴马
年龄:14
姓名: 年龄:
最佳答案
如果你调用了nextInt或nextDouble,你需要调用scan.nextLine();之后立即命令,正确读取任何字符串。
Scanner in = new Scanner(System.in);
for (int i = 1; i <= 6; i++) {
System.out.print("Name: ");
in.nextLine();
System.out.print("Age: ");
in.nextInt()
//you need to make another call to nextLine() because of the Scanner object
//will read the rest of the line where its previous read left off.
in.nextLine();
}
关于java - for循环中scanner.nextLine()的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55336828/