2011-09-09 9 views
0
public int Remove(int i, Briefcase c[], String[] m) { 

     int nChoice = 0; 
     boolean inputisok = false; 

     while (inputisok == false) { 
      System.out.print("\tPlease remove " + i + " cases: "); 
      nChoice = input.nextInt(); 
      if (c[nChoice] == null || nChoice < 0 && nChoice >= c.length) { 
       System.out.println(); 
       System.out.println("\tInvalid Input please Try again\n"); 
      } else { 
       System.out.println("\tI'm " + m[nChoice] 
         + " You just removed case # " + nChoice); 
       System.out.println("\t|" + nChoice + "| contains $" 
         + c[nChoice].getAmount() + "\n"); 
       inputisok = true; 
      } 
     } 
     return nChoice; 
    } 

ここで私の手紙には、文字と負の数、または27より高い数字を入力すると例外エラーが発生します。どうすれば修正できますか?スキャナを使用した入力に関するヘルプ

答えて

0

次の行が正しくありません:

if (nChoice < 0 || nChoice >= c.length || c[nChoice] == null) { 

二つの変更があります:

if (c[nChoice] == null || nChoice < 0 && nChoice >= c.length) { 

あなたがそうのようにそれを変更したい(1)&&||になりましたが、 (2)句が並べ替えられた。

nChoiceがあなたの元に(おかげで、@Aleks G!)

(2)c.lengthよりも同時にゼロより小さいと大きくすることはできませんので、nChoice < 0 && nChoice >= c.lengthは常に、falseに評価される(1)&&が間違っていますバージョンnChoicecの範囲内にあることを確認する前に、c[nChoice]にアクセスしようとしています。そうでない場合は、「無効入力」を表示する代わりにArrayIndexOutOfBoundsExceptionになります。

Short-circuit evaluationは、条項の発注が重要な理由です。

最後に、inputから読み取る前に、hasNextInt()を呼び出して、次のトークンが有効な整数として解釈されるようにすることができます。

public int Remove(int i, Briefcase c[], String[] m) { 

    boolean isNextIntCorrect = false; 
    int enteredInt; 

    while(!isNextIntCorrect){ 
     System.out.println("\tPlease remove " + i + " cases: "); 
     Scanner inputScanner = new Scanner(input.next()); 
     if(inputScanner.hasNextInt()){ 
      enteredInt = inputScanner.nextInt(); 
      isNextIntCorrect = enteredInt >= 0 && enteredInt < c.length 
       && enteredInt < m.length) 
     } 
     inputScanner.close(); 

     if(!isNextIntCorrect){ 
      System.out.println("\tInvalid Input please Try again\n"); 
     } 
    } 
    System.out.println("\tI'm " + m[enteredInt] 
        + " You just removed case # " + enteredInt); 
    System.out.println("\t|" + enteredInt+ "| contains $" 
        + c[enteredInt].getAmount() + "\n"); 
} 

この方法では、あなたが正しい int型を扱うのは確実だ:

+0

最初の部分が本当に評価されるとは思いません。 'c.length'は常に0以上になります。したがって、この 'if'文の最初の部分は本質的に' if(cChoice <0 && cChoice> = 0) 'を意味します - これは常に' false'です。私は彼がおそらく必要と思うのは 'if(nChoice <0 || nChoice> = c.length || c [nChoice] == null)' –

+0

@Aleks G:いいキャッチ!答えを編集します。ありがとう。 – NPE

+0

他のエラーは何ですか?または間違っている? –

関連する問題