gpt4 book ai didi

java - 根据 ArrayList 验证用户输入

转载 作者:行者123 更新时间:2023-12-01 15:33:31 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com