java - for循环中scanner.nextLine()的问题

标签 java loops for-loop java.util.scanner

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/

相关文章:

r - 如何自动化 dunn_test 和 ggboxplot?

json - 为什么我的 commonName 在我的循环中重复相同的内容?

java - 为什么我的程序创建空的 .lck 文件?

c++ - 我怎么能在这个简单的 C++ 游戏中转到另一个 "map"?

java - For 循环对于要考虑哪个值感到困惑

javascript - 奇怪的 if-else 行为 Javascript

python - 使用 while 循环添加和减去当前位置

java - 在 SpringFrame 工作中进行日志记录的首选方式

java - 无法通过 java 代码关闭和删除已打开的 .xls 文件

java - 我可以得到一个 "bond class"的具体例子吗(来自 anti-if-campaign 网站)?