2012-02-12 9 views
0

私のコードの以下の部分に問題があります。 「nn」と入力すると無効なコードが表示されます。 有効なコードが入力されると、無効なコードが返されますが、これは一度だけ発生します。 プログラムが意図したとおりに動作していないようです。手伝ってください。ArrayListに対してユーザー入力を検証する

System.out.println("ENTER CODE (nn to Stop) : "); 
    ArrayList<Product> list = new ArrayList<Product>(); 
    . 
    . 
    . 
    . 


    ArrayList<Code> codeList = new ArrayList<Code>(); 


    for (Product product : list) { 
     System.out.print("CODE : "); 
     String pcode = scan.next(); 
     if (pcode.equalsIgnoreCase("nn")) { 
      break; 
     } 

     if (!(code.equalsIgnoreCase(product.getCode()))) { 
      System.out.println("Invalid code, please enter valid code."); 
      System.out.print("CODE : "); 
      pcode = scan.next(); 

     } 

     System.out.print("QUANTITY : "); 
     int quan = scan.nextInt(); 
     while (quan > 20) { 
      System.out.println("Purchase of more than 20 items are not allowed, please enter lower amount."); 
      System.out.print("QUANTITY : "); 
      quan = scan.nextInt(); 
     } 
     codeList.add(new Code(pcode, quan)); 
    } 

答えて

1

あなたはcontinueの代わりbreakたい。

また、code = scan.next()はループの内部で一度だけ呼び出す必要があります。そうでなければ、いくつかの項目をスキップします。

String code = scan.next(); 
boolean match = false; 
for (Product product : list) { 
    if (code.equalsIgnoreCase(product.getCode())) { 
     match = true; 
     break; 
    } 
} 
// now only if match is false do you have an invalid product code. 

更新:

私はまだこれを動作させることはできません。私がしようとしているのは、入力された 製品コードが無効で、正しいコードを要求するかどうかを確認するメッセージが表示されない場合は、テストユーザー の入力です。また、 "nn"を入力したときに注文を停止する条件を設定するには、 が必要です。私はループ中に を試していますが、do-whileループなどの場合、私はそれを正しく得ることはできません。 アシストしてください。私の問題は、複数の条件のコードを書くことです。 が正しく動作している場合、もう一方は正しく動作していません。

while (true) { 
    final String code = scan.next(); 
    if (isExitCode(code)) { 
     break; 
    } 
    if (!isValidCode(code)) { 
     System.out.println("Invalid code, please enter valid code."); 
     continue; 
    } 
    int quantity = -1; 
    while (true) { 
     quantity = scan.nextInt(); 
     if (!isValidQuantity(quantity)) { 
      System.out.println("bad quantity"); 
      continue; 
     } 
     break; 
    } 
    // if you've got here, you have a valid code and a valid 
    // quantity; deal with it as you see fit. 
} 

今、あなただけのisExitCode()メソッドを記述する必要が、isValidCode()、およびisValidQuantity()。

+0

私は「続行」しようとしましたが、「nn」が入力されたときにループから完全に切り離す必要があります。私は 'code = scan.next()を取り除いたが、同じ結果がブロックされている場合は中から除去した。 – xiphias

+0

私はノブです、私はベストを尽くしています... – xiphias

+0

製品をループしているとき、あなたが現在いる製品は受け入れられる唯一の製品です。入力したコードと現在の製品のコードを比較し、それ以外の場合は無効として扱います。それはあなたが欲しいものですか? –

関連する問題