+ 1

Split

https://code.sololearn.com/cOqpwl7BUE8J/?ref=app Input: str1 Number str2 str3 str4 str5 What is problem in my code? IndexOutOfrange I think the problem is in split function. But i dont know why? Can anyone help me?

28th Dec 2020, 7:49 AM
Mohammad Reza Moravejolahkami
Mohammad Reza Moravejolahkami - avatar
6 odpowiedzi
+ 1
The problem seems to be how the input is handled. Maybe clear the scanner before accessing it with the nextLine() statement. This is a nasty fix which works, but should be rewritten to properly handle the input. https://code.sololearn.com/c81lmP0Nl2t5/?ref=app
28th Dec 2020, 9:15 AM
Maru
Maru - avatar
+ 5
Mohammad Reza Morawej You can also check if (input.nextLine() != null) https://code.sololearn.com/cP48YZrJwMKw/?ref=app
28th Dec 2020, 9:27 AM
A͢J
A͢J - avatar
+ 2
As you can see, the problem is caused due to the nextInt() statement not catching the given "\n" on the line in input. This is caught by your nextLine() statement therefore causing an empty array. Source: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo
28th Dec 2020, 9:18 AM
Maru
Maru - avatar
+ 1
You're accessing index 1 of an array of length 1. Array indexing starts from zero in Java. You should access index 0 instead.
28th Dec 2020, 9:05 AM
Maru
Maru - avatar
+ 1
But. As you see, i splitted the string "str2 str3 str4 str5" by " "(space) delimiter (using split function). So this array must be a 4-index array and should support index 0 1 2 3.
28th Dec 2020, 9:12 AM
Mohammad Reza Moravejolahkami
Mohammad Reza Moravejolahkami - avatar
+ 1
Thanks a lot McMaartenz. The best for you.
28th Dec 2020, 9:22 AM
Mohammad Reza Moravejolahkami
Mohammad Reza Moravejolahkami - avatar