2016-10-17 5 views
0

3から24までの3の倍数でユーザを入力させています。出力は0に達するまで3より少ない数字を出力します。ユーザーが15を選択します。出力が15,12,9,6,3,0を出力します。問題は、ユーザーが番号17を選択して15に丸めて残りのコードを実行する場合です。 3の倍数で入力しないと入力を無限に繰り返すにはどうすればよいですか?私のコードは以下の通りです。ステートメントを入れ子にしてdo-while文を無限にループする方法

do{ 
     System.out.print("Enter a multiple of 3: "); 
     //We use the variable n to hold the multiple of 3, like the heading says to do. 

     n = input.nextInt(); 
     if (n % 3 !=0 || n >= 25) { 
      System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive."); 
      n = input.nextInt();     
     } 
     /** 
     * X = n /3, this gives us the base number of the multiple of 3 to use and figure out the 
     * values of n->0 by 3's. 
     */ 
     for(x = n/3; x <= 8 && x >=0; x--){ 
      int three = 3 * x; 
      System.out.printf(three + "\t"); 

     } 

    }while(x >= 0); 

あなたは、私はちょうどif文の中に別の入力部を入れて見ることができるように、しかし、私はこれを行うにはしたくありません。私はループを維持するifステートメントのための方法を把握しようとしています。 if文で設定したパラメータですか?または、ステートメントの基準が満たされていない場合にifステートメントを繰り返す特定のコマンドがありますか?また、私はJavaを使用しています。

+0

'(入力良くない)しばらく{}プロンプトん;' – Li357

+0

あなたはもう少し詳しく説明してもらえますか?私はかなり新しいコーディングです。 –

+0

'if'を' while'に変更しようとしましたか? – sstan

答えて

1

別のループを使用してnを初期化することができます。 (Iあなたの外側のループが何のためにあるのかわからないので、私はそれを削除した。)

int n; 

while (true) { 
    System.out.print("Enter a multiple of 3: "); 

    n = input.nextInt(); 
    // Validate input. 
    if (n % 3 == 0 && n < 25 && n > 0) { 
    // Input is good. 
    break; 
    } 
    // Input is bad. Continue looping. 
    System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive."); 
} 

for (x = n/3; x <= 8; x--) { 
    int three = 3 * x; 
    System.out.printf(three + "\t"); 
} 

if - あなたではなく、ループの途中でループ状態をチェックする必要があるためbreakパターンが必要です始まりまたは終わりよりも。

0

while(true) { ... break; ... }が気に入らない場合は、代わりにdo { ... } while (flag);ループを使用できます。 do/whileループは何かを何度もやりたいとき、特に少なくとも一回は何度もやりたいときによく使われます。

例えば

boolean keepGoing = true; 
do { 
    System.out.println("Enter a multiple of 3 between 3 and 24: "); 
    n = input.nextInt(); 
    keepGoing = (n < 3 || 24 < n || n % 3 != 0); 
} while (keepGoing); 
System.out.println("You entered: " + n); 

それともこの変化

boolean done = true; 
do { 
    System.out.println("Enter a multiple of 3 between 3 and 24: "); 
    n = input.nextInt(); 
    done = (3 <= n && n <= 24 && n % 3 == 0); 
} while (!done); 
System.out.println("You entered: " + n); 
関連する問題