1

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;
        }
    }
plooms
  • 93
  • 2
  • 11

2 Answers2

4

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))
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • 1
    I'd prefer your answer without the first 9 words ("Unless both reference are pointing to same String instance"). It's generally a bad idea (and unnecessary) to count on string references being the same, and it makes it look like you don't know what you're doing. – ajb Jul 21 '14 at 16:34
2

You're using == instead of .equals which doesn't check if strings are equal. .equals will check that the values are equal, not just the reference numbers like this:

if( myArray[j].equals(search)){
jhobbie
  • 1,016
  • 9
  • 18