When using scanner is there a way to check that the user input is what we expect?
Say I want a double but the user enters a String what can I do to prompt the user to re-enter the value as a double?
With the following code if a number is not entered I get a mismatchException. I don't want the program to crash if the input is wrong.
Here is my code: import java.util.Scanner;
public class RoundingNumbers {
private double y;
private double x;
public RoundingNumbers(){
double y = 0;
double x = 0;
}
public void getNumber(){
System.out.print("Enter a decimal number: ");
Scanner num = new Scanner(System.in);
x = num.nextDouble();
}
public void roundNum(){
y = Math.floor(x + 0.5);
}
public void displayNums(){
System.out.println("The actual number is: " + x);
System.out.println("The rounded number is: " + y);
}
}