0

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;
}
0

2 Answers 2

1

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();
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!! that worked, and I think I found my mistake, the while loop should be inside the for loop
0

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();
  }
}

2 Comments

oh @amin saffar already answered your question so all is good now. Good luck!
Sure! No problem! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.