2016-02-21 22 views
0

我不知道爲什麼,但下面的代碼讓用戶再次運行代碼,無論他們選擇與否。我嘗試了很多東西,但它無法正常工作。無論如何,代碼都會再次運行。

謝謝!

public static void main (String [ ] args) 
{ 


    boolean a = true; 
    while (a) 
    { 
     Scanner scan = new Scanner(System.in); 

     System.out.print("Enter an integer: "); 
     int x = scan.nextInt(); 



     System.out.print("\n\nEnter a second integer: "); 
     int z = scan.nextInt(); 

     System.out.println(); 
     System.out.println(); 

     binaryConvert1(x, z); 



     System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\"."); 
     System.out.print("Enter your response here: "); 

     String RUN = scan.nextLine(); 
     String run = RUN.toLowerCase(); 
     if (run.equals("n")) 
     { 
      a = false; 
     } 

     System.out.println(); 
     System.out.println(); 
    } 
    System.out.println("Goodbye."); 
} 

回答

0

Scanner.nextInt()不消耗結束從緩衝區,這是一個字符行爲什麼當你閱讀scan.nextLine()的「是/否」問題的價值,你會收到一個空字符串,而不是價值用戶輸入。

一個簡單的辦法解決這一問題是使用Integer.parseInt()明確地解析從原材料線整數:

System.out.print("Enter an integer: "); 
int x = Integer.parseInt(scan.nextLine()); 

System.out.print("\n\nEnter a second integer: "); 
int z = Integer.parseInt(scan.nextLine()); 
相關問題