2017-04-04 56 views
-2

這裏是我的代碼:如果用戶輸入Y,如何保持程序運行?

import java.util.*; 

class Main { 

    public static void main(String[] args) { 
     Scanner Keyboard = new Scanner(System.in); 
     { 
      System.out.println("What is the answer to the following problem?"); 

      Generator randomNum = new Generator(); 
      int first = randomNum.num1(); 
      int second = randomNum.num2(); 
      int result = first + second; 
      System.out.println(first + " + " + second + " ="); 

      int total = Keyboard.nextInt(); 

      if (result != total) { 
       System.out.println("Sorry, wrong answer. The correct answer is " + result); 
       System.out.print("DO you to continue y/n: "); 
      } else { 
       System.out.println("That is correct!"); 

       System.out.print("DO you to continue y/n: "); 

      } 

     } 
    } 

} 

我試圖讓程序繼續運行,但如果用戶輸入y和如果他進入ñ關閉。

我知道我應該使用while循環,但不知道應該在哪裏開始循環。

+3

帶循環。如果你搜索網站,你會發現一些例子http://stackoverflow.com/questions/34474882/read-input-until-a-certain-number-is-typed例如 – 2017-04-04 17:44:10

回答

2

您可以使用一個循環,例如:

Scanner scan = new Scanner(System.in); 
String condition; 
do { 
    //...Your code 
    condition = scan.nextLine(); 

} while (condition.equalsIgnoreCase("Y")); 
0

這是一個很好的嘗試。只需添加一個簡單的while循環,並促進用戶輸入您詢問後,如果他們想繼續與否:

import java.util.*; 

class Main 
{ 
    public static void main(String [] args) 
    { 
     //The boolean variable will store if program needs to continue. 
     boolean cont = true; 

     Scanner Keyboard = new Scanner(System.in); 

     // The while loop will keep the program running unless the boolean 
     // variable is changed to false. 
     while (cont) { 

      //Code 

      if (result != total) { 

       System.out.println("Sorry, wrong answer. The correct answer is " + result); 

       System.out.print("DO you to continue y/n: "); 

       // This gets the user input after the question posed above. 
       String choice = Keyboard.next(); 

       // This sets the boolean variable to false so that program 
       // ends 
       if(choice.equalsIgnoreCase("n")){ 
        cont = false; 
       } 

      } else { 

       System.out.println("That is correct!"); 

       System.out.print("DO you to continue y/n: "); 

       // This gets the user input after the question posed above. 
       String choice = Keyboard.next(); 

       // This sets the boolean variable to false so that program 
       // ends 
       if(choice.equalsIgnoreCase("n")){ 
        cont = false; 
       } 
      } 
     } 
    } 
} 

您也可以在其他類型的讀取多達循環,並嘗試以其他方式實施此代碼:Control Flow Statements

+0

謝謝你,實際上工作,我學到了許多。 –

相關問題