2015-11-25 123 views
0

每当我运行程序,一切正常,但由于某种原因确认打印发生两次,我不明白为什么。任何帮助,将不胜感激。为什么确认语句两次打印到控制台?

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 
+0

哪条消息会打电话“确认消息”? “你的Z号码是...”或“你选择了%s,你确定吗?” – AlexR

+1

使用nextInt()后,您需要调用nextLine()来使用该输入行的其余部分。否则'nextLine()'会立即返回它的缓冲输入,你的'do'循环会进行第二次迭代。 – khelwood

回答

0

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

在do-while循环中,您确实不需要nextLine

+0

正确答案。非常感谢您的宝贵时间。 –

+0

@WillCrayger没问题的朋友,欢迎来到SO。 – hagrawal

0

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

number = input.nextInt(); 

不读的最后'\n'

我认为你需要在该循环中添加一个nextLine()

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"));