Search code examples
javaarraysfor-looplinear-search

Why is my condition never met?


Take a loot at the bottom in my for loop. It's probably a simple logical error but for some reason 'if' condition is never met. Sorry for asking basic stuff but I've searched and searched and can't seem to find the answer. Thanks for helping a noob.

Scanner scan = new Scanner(System.in);

    System.out.println("How large would you like the array to be? (number)");
    int arraySize = scan.nextInt();
    scan.nextLine();
    String [] myArray = new String [arraySize];
    int i = 0;

    if (arraySize <= 0 ) {
        System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
    } else {
        while (i < myArray.length) {
            System.out.println("Please type a string to be entered in the array");
            myArray[i] = scan.nextLine();
            i++;
        }
    System.out.println("Array contents: " + Arrays.toString(myArray));
    }
    System.out.println("What element would you like would you like to find in the array by performing a linear search?");
    String search = scan.nextLine();

    for (int j = 0; j < myArray.length; j++) {
        if (myArray[j] == search){
            int location = j + 1;
            System.out.println("The element, " + search + " was found in the array, in which the linear search looped " + location + " times to find it." );
            j = myArray.length;
        }
    }

Solution

  • You should always use .equals() and not == operator for String comparison. == operator will evaluate to true only when both the references are pointing to same String instance. To check whether String contents are equal you can use .equals() or equalsIgnoreCase().

    So change your search condition from

    if (myArray[j] == search)
    

    to

    if (myArray[j].equals(search))