Ch5 – Validating Input

  1. Create a new class named ValidatingInput in a file 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.out.print("Enter a number: ");
    if(!in.hasNextDouble()) {
      String word =;
      System.err.println(word + " is not a number");
    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){
  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