Reputation: 37
I am having issues with the following part of my code. when "nn" is entered i get invalid code. when valid code is entered i get invalid code however this only happens once. program doesn't seem to work as intended. Please assist.
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));
}
Upvotes: 0
Views: 2569
Reputation: 40336
You want continue
instead of break
.
Also, you should only call code = scan.next()
once inside the loop; otherwise you'll skip over some items.
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.
Update:
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.
}
Now you just need to write the methods isExitCode(), isValidCode(), and isValidQuantity().
Upvotes: 1