java - 根据 ArrayList 验证用户输入

标签 java arraylist

我的代码的以下部分遇到问题。 当输入“nn”时,我得到无效代码。 当输入有效代码时,我得到无效代码,但这只会发生一次。 程序似乎没有按预期工作。请帮忙。

    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));
    }

最佳答案

您想要继续而不是中断

此外,您应该只在循环内部调用 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.

更新:

I still can't get this to work. What I am trying to do is test user input to make sure that product code exists, if not prompt that the product code entered is invalid and asks for correct code. I also need to have the condition to stop order when "nn" is entered. I have tried while loops, do-while loops etc. i can't seem to get it right. Please assist. My problem is with writing code for multiple conditions. When one is working correctly the other isn't.

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()。

关于java - 根据 ArrayList 验证用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9253542/

相关文章:

java - 嵌套循环模式

java - 在收到 UDP 数据包之前不显示 Activity

java - 这两个代码片段之间有区别吗?如果有区别是什么?

java - 在值相同的多个 ArrayList 中拆分 ArrayList

java - 没有名为 EntityManager 的持久性提供程序

JavaScript 和动态表单创建

java - 如何使用 JNI 从 C 实现对 Java 的回调?

Java List列表转String[]

java - 对数组列表进行排序。按int值比较

java - ArrayList.clear() 与 ArrayList=null