Reputation: 469
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 :)
Upvotes: 1
Views: 3389
Reputation: 77
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);
Upvotes: 0
Reputation: 106430
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);
Upvotes: 0
Reputation: 201447
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");
}
Upvotes: 2