1

I'm creating a math program where a user inputs an answer. I want to display a message that says "All solutions must be entered as decimal numbers". How would I make sure that the user inputs a double and if not display that message. I've tried this so far:

if(userLetter.equalsIgnoreCase("a")) {
    System.out.print("What is the solution to the problem:" + " " + ran1Shift + " " + "+" + " " + ran2Shift + " = ");
    double userNum = input.nextDouble();
        if(userNum == additionAnswer){
            System.out.println("That's correct!");
        }
        else{
            System.out.println("The correct solution is: " + additionAnswer);
        }
    }

So basically I have it set now to display whether the answer is exactly true or false but how could I make another part which catches if the user enters a non-double? Thank you for your help :)

3 Answers 3

2

Assuming input is a Scanner, then you can call Scanner.hasNextDouble() which returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. Something like,

if (input.hasNextDouble()) {
    double userNum = input.nextDouble();
    if (userNum == additionAnswer) {
        System.out.println("That's correct!");
    } else {
        System.out.println("The correct solution is: " + additionAnswer);
    }
} else {
    System.out.println("All solutions must be entered as decimal numbers");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I figured that could work I just wasn't sure how to implement it.
If your question is answered, please accept an answer.
0

nextDouble is guaranteeing that it will only scan a token that looks like a double from standard input. Since you want to catch the invalid input, you'll have to do more work.

The below is re-entrant; it will allow the user to keep adding input until valid input is brought in. I leave the prompting of the user as an exercise for the reader.

boolean valid = false;
do {
    try {
        double userNum = Double.parseDouble(input.nextLine());
        // other code to use `userNum` here
        valid = true;
    } catch(NumberFormatException e) {
        System.out.println("Not a valid double - please try again.");
    }
} while(!valid);

Comments

0

You can use a loop to allow user to re-enter a number in case he make a mistake.

System.out.println("Enter a double number:");
while (!input.hasNextDouble())
{
    System.out.println("Invalid input\n Enter a double number:");
    input.next();
}
double userInput = input.nextDouble();    
System.out.println("You entered: " + userInput);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.