Ch5 – Validating Input

  1. Create a new class named ValidatingInput in a file ValidatingInput.java using your editor of choice.
  2. 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.");
  }
}
  1. Compile the class and then add the following main method.
public static void main(String[] args){
  ValidatingInput.scanDouble();
}
  1. 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
  1. Run the program again, only this time enter a number.
$ java ValidatingInput
Enter a number: 33
33.0 is a number