Error after compiling Java project : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

StackOverflow https://stackoverflow.com/questions/19371310

문제

I am working on a project for school. The project is a game where the user needs to guess the price of an object. The price is generated randomly. The user has 5 chances to guess it. if he doesnt, th game is over and is asked if he wants to replay or not. The name of this game could be known as The Price is Right. My problem is that when i run the project it crashes just before taking the answer of the user, to know if he wants to replay.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at pkgthepriceisrightv1.ThePriceisRightV1.main(ThePriceisRightV1.java:102)
Java Result: 1
BUILD SUCCESSFUL (total time: 7 seconds)

This is the error. I dont know what is the problem....

And here is the code lines where i am taking the information, the yes or no from the user, wich is the line 102, in the error code, i have declared all my variables. valeur_recommencer is a char, and recommencer is a string. All my code is in Java. Excuse me for the language of the code, its all in french, a requirement for school.

recommencer = lire.nextLine();   
valeur_recommencer = recommencer.charAt(0);
도움이 되었습니까?

해결책 2

Ok found my mistake. I needed to add an other Scanner. If this error code is shown for any body else, try adding an other scanner. The sacnner could not read too much of answers from the user, so is crashes. I think it could solve the problem

다른 팁

This returns empty string "".

recommencer = lire.nextLine();

so when you try to find the first char of empty string, it ends with exception.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top