2016-04-06 3 views
0

をチェック:hasNextIntを合わせ、値が大きい/ X未満では、以下の方法の使用

public void localsetValue(String UserInput) 
{ 
    System.out.println("Enter New Value:"); 
    while (!console.hasNextInt()){ 
      console.next(); 
      System.out.println("Must be a number."); 
     } 
     tempInt = console.nextInt(); 
     console.nextLine(); 



    while (tempInt <0) { 
     System.out.println("Value must be positive."); 
     tempInt = console.nextInt(); 
    } 
    SetSpecificValue(UserInput.toLowerCase(), tempInt); 
} 

最初の状態で、ユーザが有効な整数に入ることループチェック。これはうまく動作します。

2番目のwhileループは、ユーザーが正の数を入力したことを確認します。これは動作しますが、この時点では手紙を入力することができ、例外がスローされます。

まだJavaには新しく、この2つのチェックを組み合わせる方法はありますか?

+0

その他の論理的な観点。あなたは整数を読んで、それが正であることを確認したい(あなたのコードは非負であると言う)、次のトークンがnextInt()と整数であることを確認するために戻って行く。 –

答えて

3

同じwhileループを使用すれば問題ありません。

ここでは、ユーザがint以外のものを入力した場合、または入力したintが否定の場合にループ処理を続けます。

int tmpInt = 0; 
boolean flag = false; 
while ((flag = !console.hasNextInt()) || (tmpInt = console.nextInt()) < 0){ 
    if (flag) { 
     console.next(); 
     flag = false; 
    } 
    System.out.println("Value must be a positive integer !"); 
} 
+0

私はまだconsole.next console.nextLine();部品? これはまだかなり正しく動作しません。文字を入力すると、エラーメッセージが出力されます。負の値を入力すると、エラーメッセージは表示されず、次の入力(有効または無効)は常に無効として返されます。 – NuMs

+0

完璧に動作します!ありがとう:) – NuMs

+0

@NuMsあなたは大歓迎です:) –

0

このようなものはありますか?

public void localsetValue(String UserInput) 
{ 
    tempInt = -1; 
    System.out.println("Enter New Value:"); 
    while (!console.hasNextInt() || (tempInt = console.nextInt()) <0){ 
      console.next(); 
      System.out.println("Must be a positive number."); 
     }  
     console.nextLine(); 
    SetSpecificValue(UserInput.toLowerCase(), tempInt); 
} 
1

ループは1つだけ必要ですが、2つの中止条件(数値は正である)を組み合わせる必要があります。

int value = -1 
do { 
    if(console.hasNextInt()){ 
     value = console.nextInt(); 
    } else { 
     console.next(); 
    } 
} while(value < 0) 
関連する問題