Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a string exists in array

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.

like image 625
Humeey4 Avatar asked Mar 21 '26 06:03

Humeey4


2 Answers

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;
}
like image 113
Hien Nguyen Avatar answered Mar 23 '26 20:03

Hien Nguyen


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;
}
like image 23
Alan Avatar answered Mar 23 '26 18:03

Alan