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. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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; } } }

6th Dec 2020, 12:17 PM
duskygloom
duskygloom - avatar
5 Answers
+ 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. :-)
6th Dec 2020, 12:33 PM
Lisa
Lisa - avatar
+ 1
Heres the code that i did for it: https://code.sololearn.com/c32FSQPgU1Yt/#java try to compare to spot out the differences.
6th Dec 2020, 12:37 PM
pNK
pNK - avatar
+ 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
6th Dec 2020, 2:38 PM
duskygloom
duskygloom - avatar
+ 1
Martin Taylor, I will definitely try the regex method... Seems interesting
6th Dec 2020, 3:24 PM
duskygloom
duskygloom - avatar
0
Lisa and pNK... The equals method is working thanks
6th Dec 2020, 12:42 PM
duskygloom
duskygloom - avatar