Create a new class named ValidatingInput in a file ValidatingInput.java using your editor of choice.
Create a new method called scanDouble and add the following code. Don’t forget to import the scanner class.
import java.util.Scanner;
public class ValidatingInput {
public static void scanDouble(){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
if(!in.hasNextDouble()) {
String word = in.next();
System.err.println(word + " is not a number");
return;
}
double x = in.nextDouble();
System.out.println(x + " is a number.");
}
}
Compile the class and then add the following main method.
public static void main(String[] args){
ValidatingInput.scanDouble();
}
Compile and then run the program. Enter any non-numeric character and note the result.
$ java ValidatingInput
Enter a number: xs
xs is not a number
Run the program again, only this time enter a number.
$ java ValidatingInput
Enter a number: 33
33.0 is a number