根据ArrayList验证用户输入

问题描述:

我遇到了以下部分代码问题。 当输入“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)); 
    } 

你想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”时,我还需要 有条件停止订单。我试过 while循环,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”时,我需要完全从循环中断开。我从if块中删除了'code = scan.next(),但是结果相同。 – xiphias 2012-02-12 23:30:07

+0

我是一个noob,我正在努力...... – xiphias 2012-02-12 23:37:27

+0

因此,当您循环使用产品时,您目前使用的产品是唯一可以接受的产品;您将输入的代码与当前产品的代码进行比较,否则将其视为无效。那是你要的吗? – 2012-02-13 01:04:38