death symbiote
death symbiote

Reputation: 19

Creating 2 random input numbers then asking for a solution and if the user wants another 2 numbers to add

import java.util.Scanner;
public class mathstrainer {

    public static void main(String[] args) {
    Scanner answerinput=new Scanner(System.in);
    System.out.println("Welcome to Maths Trainer!");
    boolean choice=true;
    int max=15;
    int min=1;
    while(choice=true){
    int number1=(int)(Math.random()*max+min);
    int number2=(int)(Math.random()*max+min);
    System.out.println("what is "+number1+"+"+number2+"? >");
    int answer=answerinput.nextInt();
    int solution=number1+number2;
if(answer==solution){
    System.out.println("Correct! Well done!");
    System.out.println("Would you like another question? (Y/N)");
    String choiceword=answerinput.nextLine();
    choiceword=choiceword.toUpperCase();
    char choiceletter=choiceword.charAt(0);
    if(choiceletter=='Y'){
        choice=true;
    }
    else{
        choice=false;
    }

}
else{
    System.out.println("Incorrect! The right answer is "+solution);
    System.out.println("Would you like another question? (Y/N)");
    String choiceword=answerinput.nextLine();
    choiceword=choiceword.toUpperCase();
    char choiceletter=choiceword.charAt(0);
    if(choiceletter=='Y'){
        choice=true;
        }
    else{
        choice=false;
    }
}
}}}

It comes with the problem:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at mathstrainer.main(mathstrainer.java:36)

Where have I gone wrong, and how can I fix it?

I am trying to create a loop using a boolean variable to act as the question creator and repeator but the loop can be stopped by turning the boolean value to false.

Also, what does the problem even mean? I seem to get this same problem a lot.

Upvotes: 1

Views: 39

Answers (1)

Emerson Dallagnol
Emerson Dallagnol

Reputation: 1269

When you call answerinput.nextInt() the scanner reads the integer and continues in the same line, after, the answerinput.nextLine() will read the input until find a line break, returning a empty string in your case. Possible solutions:

  • add a nextLine() after nextInt() to read the line break character.
  • replace the nextLine() with next(). The Scanner.next() will find the next token in input.

Upvotes: 2

Related Questions