Eric Smith Eric Smith - 1 month ago 6
Java Question

Why is my string index out of range?

Writing a nested while loop for a coin flip program and I can't find out why my code won't compile.
The user input at the end is giving me the index out of range error. Can someone tell me how to fix this?

Scanner lit = new Scanner(System.in);
int numHeads = 0;
int numTails = 0;
int counter = 0;
boolean tryAgain = false;
String replayResponse = "";
char replay = '0';

System.out.println("Enter how many times a coin should be flipped");
int numFlipped = lit.nextInt();

do {

do{


if (Math.random() > 0.5){
System.out.println("H");
numHeads++; counter++;
}

else if (Math.random() < 0.5){
System.out.println("T");
numTails++; counter++;
}


} while(counter < numFlipped);

tryAgain = true;

} while (!tryAgain);

System.out.println("Number of heads is " + numHeads);
System.out.println("Number of tails is " + numTails);
System.out.println("");
System.out.println(" Would you like to play again? : Y/N ");


replayResponse = lit.nextLine();
replay = replayResponse.charAt(0);
if (replay == 'Y' || replay == 'y') {
tryAgain = false;
} else {
tryAgain = true;


}

lit.close();
System.out.println();
System.out.println("You exited out of the game.");
System.out.println("Goodbye!");
}

Answer

When scanning for int's you need to reset the input. Currently the scanner is looking for the next int. So add lit.nextLine(); like so:

 lit.nextLine();
 replayResponse = lit.nextLine();
    replay = replayResponse.charAt(0);
    if (replay == 'Y' || replay == 'y') {
        tryAgain = false;
    } else {
        tryAgain = true;

     }

You can also do:

if(lit.hasNextInt()) 
{
   numFlip = lit.nextInt();
}

To solve the type mismatch exception.

Comments