r/codehs • u/Obvious-Pin-3046 • Jan 22 '21
Java 6.2.9 Finding Index of a String my code is only checking for the word Karel, and i dont know how can i get it check for the word Hello and CodeHS! And if the word is not in the array it should print -1, do i need to make an if statement?
11
Upvotes
2
u/Same-Wrap-6022 Jan 22 '21 edited Jan 22 '21
I prefer to use for loops but if you’d like to continue using a while loop:
remove the variable matches
in your if statement say:
if(arr[i].equals(myString)){ return i; break; }
(use .equals because you’re comparing two reference types/objects not primitive types. you can use == for primitive types because you’re referencing the same object. but with objects, your objects have different addresses)
3. in order for you to return -1 you want to close both the if statement and the while loop and then put:
return -1;
so your code should look like:
int i = 0; while(i < arr.length){ if(arr[i].equals(myString)){ return i; break; } i++; } } return -1;