0

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");
    }
}
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Kiotzu
  • 41
  • 8
  • 1
    To compare if two strings are equal, do `names[index].equals(search)` instead of using `==` – Riley Carney Nov 16 '15 at 00:09
  • 1
    Also, `if (searchReturn = true) {` does not check to see is `searchReturn` is `true`. It **assigns** the value `true` to the variable `searchReturn`. You want simply `if (searchReturn) { ...` – azurefrog Nov 16 '15 at 00:10

2 Answers2

2

The following code

if (searchReturn = true) 

will just assign searchReturn as true and will execute the code within it.

Instead of this code you should change it to

if (searchReturn)

which will run whenever searchReturn is true

Also to compare strrings use equals method instead of ==

Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34
1

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.

Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
  • 1
    thanks, put me on the right track, i ended up revamping it and using startsWith, endWith, and contains for my needs but this steered me in the direction i needed to go! thanks a lot. – Kiotzu Nov 16 '15 at 04:28