Java Programer
Java Programer

Reputation: 45

Validating user's input for only int or double values

I need to validate the user's input so that the value entered is a double or an int; then store the int/double values in an array and show an error message if the user enters invalid data.

For some reason my code crashes if the user enters invalid data.
Could you please review my code below and tell me what is possibly wrong?

public static double[] inputmethod() {
    double list[] = new double[10];
    Scanner in = new Scanner(System.in);
    double number;
    System.out.println("please enter a double : ");

    while (!in.hasNextDouble()) {
        in.next();
        System.out.println("Wrong input, Please enter a double! ");
    }
    for (int i = 0; i < list.length; i++) {
        list[i] = in.nextDouble();
        System.out.println("you entered a double, Enter another double: ");

    }
    return list;
}

Upvotes: 0

Views: 532

Answers (2)

Whooper
Whooper

Reputation: 625

You are basically on the right track already! All you have to do is to put your while loop which validates the user input inside your for loop. Your code should look something like this.

public class InputTest{

  public static double[] inputmethod() {
    double list[] = new double[10];
    Scanner in = new Scanner(System.in);
    double number;
    System.out.print("Please enter a double: ");

    for (int i = 0; i < list.length; i++) {
      while(!in.hasNextDouble()){
        in.next();
        System.out.print("Wrong input! Please enter a double: ");
      }
      System.out.print("You entered a double! Enter another double: ");
      list[i] = in.nextDouble();
    }
    return list;
  }

  public static void main(String args[]){
    double list[] = inputmethod();
  }
}

Upvotes: 0

amin saffar
amin saffar

Reputation: 2033

For validate user inter the double or not do like below:

 public class TestInput {

    public static double[] inputmethod() {
        double list[] = new double[10];
        Scanner in = new Scanner(System.in);
        double number;
        System.out.println("please enter a double : ");

        for (int i = 0; i < list.length; i++) {
            while (!in.hasNextDouble()) {
                in.next();
                System.out.println("Wrong input, Please enter a double! ");
            }
            list[i] = in.nextDouble();
            System.out.println("you entered a double, Enter another double: ");

        }
        return list;
    }

    public static void main(String args[]) {
        inputmethod();
    }

}

Upvotes: 1

Related Questions