0

Index of an Element in String Java

Hello SoloLearn friends! I am trying to return the position/index for a word in a sentence. In my code below, I get the positon/index one less than the correct number. For example, for sentence "I like listening to music!", correct position for "music" is 5 but my program returns 4. Any suggestions? Thanks! public class Challenge { public static String findWord(String sentence) { String[] strArray = sentence.split(" "); for (int i = 1; i < strArray.length; i++){ if (strArray[i].equals("music")) return "I found music at " + i + "!"; }return "I can't find music"; } }

10th Jul 2020, 4:46 PM
GG128
4 Antworten
+ 3
GE12 if you write i = 1 in for loop it doesn't mean that position will change. i = 1 means 2nd position in Java i = 0 means 1st position See the Example: https://code.sololearn.com/cfr0AV7mOUIL/?ref=app
10th Jul 2020, 4:54 PM
A͢J
A͢J - avatar
+ 2
GE12 Index start from 0 in Java. So music is on 4th position. To get 5 just print i + 1 instead of i
10th Jul 2020, 4:49 PM
A͢J
A͢J - avatar
+ 1
Thanks for the code example AJ Anant. Adding +1 to i in the return statement worked!
10th Jul 2020, 5:19 PM
GG128
0
@AJ Anant Unfortunately I get the same results (in test cases) with index from 0 :(
10th Jul 2020, 4:52 PM
GG128