Reputation: 51
I want to check that the data entered by the user via terminal is the correct type needed in the program. If it is not, the code should loop so it asks for the data again before proceeding to the next step.
Example:
The message in terminal is as follows:
Enter Number:
and the user enters a string such as
yes
How can I loop the program and ask for the number again until the user enters a number of type double
?
The code so far for this is:
System.out.println("Enter number:");
double number = scanner.nextDouble();
Upvotes: 0
Views: 2883
Reputation: 159874
As you're using Scanner
, you could use Scanner.hasDouble()
. To ensure that you do get a valid double, some looping mechanism will be necessary:
boolean numberFound = false;
while (!numberFound) {
if (input.hasNextDouble()) {
number = input.nextDouble();
numberFound = true;
} else {
System.out.println("Invalid double " + input.next());
}
}
Upvotes: 1
Reputation: 25950
double number;
try
{
number = scanner.nextDouble();
number = parseDouble(inputString);
}
catch(NumberFormatException nfe)
{
System.out.println("Please enter a valid double!");
number = scanner.nextDouble();
number = parseDouble(inputString);
// if the input is not valid again, you need a loop, rethink.
}
Upvotes: 1