2017-04-04 5 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入り、彼がn個入った場合に閉じた場合。

私はwhileループを使うべきだと知っていますが、どこでループを始めるべきか分かりません。

+3

ループあり。サイトを検索するといくつかの例が見つかりますhttp://stackoverflow.com/questions/34474882/read-input-until-a-certain-number-is-typed例えば –

答えて

2

あなたは、例えばループを使用することができます

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

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

良い試みです。ただ、ループしながら、シンプルを追加し、彼らは継続したいかどうかを尋ねた後、ユーザーの入力を容易:

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

実際に働いてくれたおかげで、私はロット。 –

関連する問題