Reputation: 1239
I have some trouble in getting Java to read the first character in a String. I have here included the code up to this point (the code beyond this is, I don't think, relevant at all):
import java.util.Scanner;
public class SeveralDice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many dice do you want to use? ");
int numberOfDice = input.nextInt();
SeveralDice game = new SeveralDice(numberOfDice);
System.out.print("You have 0 points. Another try(y/n)? ");
boolean turn = true;
String answerInput;
char answer;
int lastValue = 0;
while (turn) {
answerInput = input.nextLine();
answer = answerInput.charAt(0);
if (answer == 'y') {. . . . .
And then the code continues. However, when I run the program, I get the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at SeveralDice.main(SeveralDice.java:25)*
Line 25 is the line answer = answerInput.charAt(0);
. So obviously something goes wrong here. Any help would be greatly appreciated!
Upvotes: 1
Views: 735
Reputation: 76908
It's because when you do:
int numberOfDice = input.nextInt();
You read in the int
the user enters but the \n
is still in the input stream.
The first call to input.nextLine()
in your loop tokenizes on \n
so it's reading in a blank line, thus answerInput
has a zero length. nextLine()
differs from nextInt()
in that it reads in an entire line as a String
and strips the trailing \n
from the intput.
As others have posted, checking the length of answerInput
will solve the problem. You can also simply call input.nextLine()
after getting your int
from nextInt()
Upvotes: 2
Reputation: 62439
It seems that entering the integer for "How many dice..." also triggers the call to nextLine() to read a blank line (since you are pressing enter after you wrote the integer) and so you are reading a string with 0 characters. I suggest you replace:
int numberOfDice = input.nextInt();
with
int numberOfDice = Integer.parseInt(input.nextLine());
Upvotes: 1