【问题标题】:the problem with scanner.nextLine() in the for loop [duplicate]for循环中scanner.nextLine()的问题[重复]
【发布时间】:2019-03-25 11:30:48
【问题描述】:
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()
}
我希望输出:
姓名:大卫·奥巴马
年龄:14
姓名:艾娃·奥米迪
年龄:53
等等
但这是我的输出,并且只使用一次 nextLine():
姓名:大卫·奥巴马
年龄:14
姓名:年龄:
【问题讨论】:
标签:
java
loops
for-loop
java.util.scanner
【解决方案1】:
如果你调用了 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();
}