Error in Program | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Error in Program

https://code.sololearn.com/ceN5q84VCiJv/?ref=app Pls help me, I couldn't get it why this error is coming if anyone has any solution to the error then pls tell me :(

4th Feb 2023, 2:11 PM
五条悟 ♡
五条悟 ♡ - avatar
7 Answers
+ 3
https://code.sololearn.com/cJIt2knE0HQi/?ref=app I got my solution everyone When I tried to do it by using io package, it ran perfectly Stefanoo SoloProg José Ricardo Jiménez Aguilera just check it out
9th Feb 2023, 1:13 PM
五条悟 ♡
五条悟 ♡ - avatar
+ 1
Use int n= Integer.parseInt(in.nextLine()); instead of int n=in.nextInt();
4th Feb 2023, 2:28 PM
SoloProg
SoloProg - avatar
+ 1
If your input is like this it works. Input: 2 Name1 Name2 Ouput: N It's because your a still on the first line after nextInt and nextLine finds a Space as first char.
4th Feb 2023, 2:36 PM
Stefanoo
Stefanoo - avatar
+ 1
That's because a String itself can throw this exception. It's not the array who is throwing it. And your first string at Index 0 is empty.
4th Feb 2023, 3:00 PM
Stefanoo
Stefanoo - avatar
+ 1
You should give a try to your code in a real IDE. If you can't and want to continue here, you should add in.nextLine() before the for loop where you start adding the elements to the array, otherwise it will remain in the same line where the integer was written and the first element of the array will be left empty. That error was generated because the first element in your array was left empty because when you call in.nextLine() in the first iteration, the "cursor" is still right after the integer and not at the following line as you (and also me) would expect. As the first element of the array was left empty, requesting its first char is impossible and causes an exception. As a future advice, avoid that kind of error by using the method .isEmpty() before calling any method to handle the value of any String variable
6th Feb 2023, 6:31 AM
José Ricardo
José Ricardo - avatar
0
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index out of range: 0 at java.base/ java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:711) at Program.main(Program.java:18) I think the main problem is in line 18 Char ch=a[i].charAt(0); It is saying the index of the string is not 0 or the compiler can't find any character in that position. But as a learner, I know every string starts with a position 0, but why this error is coming everytime I don't know.
4th Feb 2023, 2:45 PM
五条悟 ♡
五条悟 ♡ - avatar
0
Stefanoo sir, I couldn't get it! 😥
4th Feb 2023, 2:46 PM
五条悟 ♡
五条悟 ♡ - avatar