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

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

Question

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);
Was it helpful?

Solution 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

OTHER TIPS

This returns empty string "".

recommencer = lire.nextLine();

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top