So I have no errors in my code but for some reason my search is returning the true result no matter if the array contains it
public static void linSrch(String[] names) {
Scanner inputDevice = new Scanner(System. in );
System.out.println("Please enter search");
String search;
search = inputDevice.nextLine();
boolean searchReturn;
for (int index = 0; index < names.length - 1; index++) {
if (names[index] == search) {
searchReturn = true;
}
}
if (searchReturn = true) {
System.out.println(search + " is found in the array.");
} else {
System.out.println(search + " not found in the array");
}
}
Instead of writing:
if (names[index] == search) {
searchReturn = true;
}
You have to write:
if (names[index].equals(search)) {
searchReturn = true;
}
Because, in case of Non-primitive data types ==
checks the memory addresses are equal or not.
And also must not forget about:
if (searchReturn = true) {
System.out.println(search + " is found in the array.");
}
to change:
if (searchReturn) {
System.out.println(search + " is found in the array.");
}
Because, you are assigning instead of checking.