Relatively new to java. I'm trying to sequentially search in a string array but I'm pretty sure there's something wrong with my if statement because the boolean flag stays false. The code worked with the int array, so I don't understand what's wrong with this one.
public static void sequentialNameSearch(String[] array) {
// sequential name search
Scanner input = new Scanner(System.in);
String value;
int index = 0;
boolean flag = false;
System.out.println("\nPlease enter a name to search for");
value = input.next();
while (flag == false && index < array.length - 1) {
if (array[index] == value) {
flag = true;
System.out.println(array[index] + " is number "
+ (index + 1) + " in the array.");
}
else if (index == array.length - 1)
System.out.println("That name is not in the array");
index++;
}
input.close();
}
What's wrong is that you can't compare the contents of two Strings with ==. For that, you should use equals() or equalsIgnoreCase() methods of one of the strings. Example:
if (array[index].equals(value)) {