0
I'm working on a program which would locate the word 'Nemo' in a string. I'm new to java, please help me fix this.
import java.util.Scanner; class solution { public static void main ( String[] args ) { // taking inputs Scanner input = new Scanner( System.in ); int numberWords = input.nextInt(); input.nextLine(); String string = input.nextLine(); input.close(); // creating list of words String[] words = string.split( " ", numberWords ); // finding and printing Nemo for ( int i = 0; i < numberWords; i++ ) { if ( words[i] == "Nemo" ) System.out.println( i + 1 ); break; } } }
7 Réponses
+ 3
I did not try your code, but my guess would be to compare the strings by the string method .equals() instead of the == operator as you want to compare the string "contents" not their instances.
Once you found Nemo, search for Dory, too. :-)
+ 1
Heres the code that i did for it: https://code.sololearn.com/c32FSQPgU1Yt/#java
try to compare to spot out the differences.
+ 1
Actually I had to find only the word 'Nemo'... If there were a word like 'notNemo', indexOf would have scanned it and printed the output... And also I had to tell which number word it was, that's why the first thing that hit my mind was the way I would have done it in python
+ 1
Martin Taylor, I will definitely try the regex method... Seems interesting
0
Lisa and pNK... The equals method is working thanks