I'm trying to check if a name has already been used in the array, but it's only working for the spot [0]. I'm assuming its from the for loop in boolean only going through once and not incrementing up to check the other spots?
Tried changing different if's and while loops
if (depotCount < 4){ // Runs if the depots are less than 4
System.out.println("Enter your depots name");
name = console.next().toLowerCase();
if (check(depots, name) == true){
System.out.println("Depot name already exists");
break;
}
else {
addDepot(depots, name);
}
} else {
System.out.println("Only 4 depots are allowed");
break;
}
public boolean check(Depot [] depots, String name){
boolean check = false;
for (int i = 0; i < depots.length; i++){
if(depots[i].getDepotName().equals(name))
return true;
else {
return false;
}
}
return check;
}
So it is working if a first name as "Warehouse" and I try to put "Warehouse" a second time. but if I try to put the same name as the 2nd slots it doesn't come back as true.
You need remove return false; in for loop, if you put there, for loop run only one time with index 0.
public boolean check(Depot[] depots, String name) {
boolean check = false;
for (int i = 0; i < depots.length; i++) {
if (depots[i].getDepotName().equals(name))
return true;
}
return check;
}
You can only short like this without check variable.
public boolean check(Depot[] depots, String name) {
for (int i = 0; i < depots.length; i++) {
if (depots[i].getDepotName().equals(name))
return true;
}
return false;
}
Inside your for loop you have an "else return false". what this does is, if you find something that is not equal you immidiatly return false. However, if you return on any occasion in your method, the method is over thus it doesnt loop through all depots
public boolean check(Depot [] depots, String name){
for (int i = 0; i < depots.length; i++){
if(depots[i].getDepotName().equals(name))
return true;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With