为什么此循环的第二次迭代会跳过第一次扫描?

时间:2016-09-26 06:01:43

标签: java eclipse loops arraylist while-loop

我正在尝试编写一个代码,要求用户输入他们的名字,将其存储在List中,然后要求他们输入他们的年龄,将其存储在另一个列表中。然后它询问用户是否想再试一次[是/否]。 在测试代​​码时,我输入“Y”并期望循环让我输入另一个名字。相反,它会跳过名称输入并跳转到年龄输入。我无法弄清楚为什么。 这是代码

import java.util.ArrayList;
import java.util.Scanner;

public class PatternDemoPlus {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<Integer> ages = new ArrayList<Integer>();
        String repeat = "Y";
        while(repeat.equalsIgnoreCase("Y")){
            System.out.print("Enter the name: ");
            names.add(scan.nextLine());
            System.out.print("Enter the age: ");
            ages.add(scan.nextInt());

            System.out.print("Would you like to try again? [Y/N]");
            repeat = scan.next();
            //Notice here that if I use "repeat = scan.nextLine(); instead, the code does not allow me to input anything and it would get stuck at "Would you like to try again? [Y/N]
            System.out.println(repeat);

            //Why is it that after the first iteration, it skips names.add and jumps right to ages.add?
        }
    }
}

感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

使用next()只会返回空格之前的内容。返回当前行后,nextLine()会自动将扫描仪向下移动。

尝试更改您的代码,如下所示。

    public class PatternDemoPlus {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<Integer> ages = new ArrayList<Integer>();
        String repeat = "Y";
        while(repeat.equalsIgnoreCase("Y")){
            System.out.print("Enter the name: ");
            String s =scan.nextLine();
            names.add(s);
            System.out.print("Enter the age: ");
            ages.add(scan.nextInt());
            scan.nextLine();
            System.out.print("Would you like to try again? [Y/N]");
            repeat = scan.nextLine();

            System.out.println(repeat);


        }
    }
}