for循环中的scan.nextLine()问题

时间:2019-03-25 11:30:48

标签: 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()
}
  

我希望输出:

名称:David Obama

年龄:14

名称:Ava Omidi

年龄:53

  

但这是我的输出,仅使用一次nextLine():

名称:David Obama

年龄:14

姓名:年龄:

1 个答案:

答案 0 :(得分: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();
}