为什么确认声明会两次打印到控制台?

时间:2015-11-25 15:33:16

标签: java

每当我运行程序时,一切正常,但由于某种原因,确认打印发生了两次,我无法弄清楚原因。任何帮助,将不胜感激。

public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String Z = "Z";
        int number;
        String Znumber = "";
        String Confirmation = "";
        int ExamType;

        // Ask user for Z number
        do {
            System.out.println("Please enter your Z number. Example: 12345678");
            number = input.nextInt();
            Znumber = Z + number;

        } while ((Znumber.length() != 9));

        //Confirm Z number entry
        do {
            System.out.printf(
                    "Your Z number is: %s. Is this correct? Enter Y/N: \n",
                    Znumber);
            Confirmation = input.nextLine();
        } while (!Confirmation.equalsIgnoreCase("y"));

        // Ask user which exam they would like to take
        ExamType = 0;
        Confirmation = "";

        System.out.println("Which exam would you like to take? Select 1-3: ");
        System.out.println("1: English");
        System.out.println("2: Spanish");
        System.out.println("3: Math");
        ExamType = input.nextInt();

        do {
            System.out.printf("You selected %s. Are you sure? Enter Y/N: \n",
                    ExamType);
            Confirmation = input.nextLine();

        } while (!Confirmation.equalsIgnoreCase("y"));

        // Begin exam
        if (ExamType == 1) {

            System.out.println("Welcome to the English exam!");
            // Start code from JavaExam.java

        } else if (ExamType == 2) {

            System.out.println("Welcome to the Spanish exam!");
            // Start code from MathExam.java

        } else if (ExamType == 3) {

            System.out.println("Welcome to the Math exam!");
            // Start code from EnglishExam.java

3 个答案:

答案 0 :(得分:0)

你的第一个循环(// Ask user for Z number

number = input.nextInt();

不会读取最后一个'\n'

我认为您需要在该循环中添加nextLine()

答案 1 :(得分:0)

而不是Confirmation = input.nextLine();,请使用Confirmation = input.next();,你应该做得很好。经过测试和确认。

你在do-while循环中真的不需要nextLine

答案 2 :(得分:0)

在您第一次跑步的时候打印Your Z number is: %s. Is this correct? Enter Y/N:。之后,在这种情况下评估条件!Confirmation.equalsIgnoreCase("y"),为此原因提供true尝试在第二次运行循环do-while。

     do {
       System.out.printf("Your Z number is: %s. Is this correct? Enter Y/N: \n",
               ....
        } while (!Confirmation.equalsIgnoreCase("y"));