Reputation: 242
My program prompts the user to input an item's code. Duplicate codes are not allowed so when he enters the code, the for
loop will checks if it exists. The for
loop should break
for my condition because I do get the output "Item's code exists" but it still does not add the item to the array. What am I missing?
tems[] items = new Items[200];
AddItem add = new AddItem();
Scanner s = new Scanner(System.in);
int z,x;
double c,v;
String n,m,b;
public void addItem(){
int r;
z = add.getCode();
x = add.getQuantity();
c = add.getCostPrice();
n = add.getDescription();
m = add.getDiscount();
v = add.getSellingPrice();
b = add.getStatus();
for(r = 0; r < items.length; r++){
for(int q=0; q<r; q++){
if(z==items[q].getCode()){
System.out.println("Item's code exists");
break;
}
}
if(items[r]==null){
items[r] = new Items(z, n, x, c, v, b, m);
break;
}else if (items[r]!=null){
continue;
}
}
}
Upvotes: 0
Views: 135
Reputation: 393801
An alternative to using break is using a boolean variable :
boolean codeExists = false;
for(r = 0; r < items.length && !codeExists; r++){
for(int q=0; q<r && !codeExists; q++){
if(z==items[q].getCode()) {
System.out.println("Item's code exists");
codeExists = true;
}
}
}
Both loops would be exited once codeExists
becomes true.
Upvotes: 0
Reputation: 201439
If you want to break
the outer loop, use a labeled break. Something like,
out: for(r = 0; r < items.length; r++){
for(int q=0; q<r; q++){
if(z==items[q].getCode()){
System.out.println("Item's code exists");
break out;
}
}
Upvotes: 5
Reputation: 378
Your code is a little difficult to understand. Try improving variable names and creating comments so others can understand code better. I Believe the problem lies in your loops. The break statement breaks out of the first for loop, but it will not break out of both. If i am understanding your code, then it would be better to place a flag to properly break out of both loops.
Upvotes: 0