0

A user has to input only numbers(int, float, double) into an ArrayList. If a user inputs anything but numbers, an exception InputMismatchException must be thrown.

I thought of using Number class.

Scanner input = new Scanner(System.in);
ArrayList<Number> number = new ArrayList<Number>();
System.out.println("Enter number");
(data_type???) number_var = input.??????;
number.add(number_var);

This code will be in do while asking user if he/she wants to continue to give input or not. The only problem is how to restrict user to give input as only numbers. This should be done without creating another class but a method is allowed to restrict user.

  • 1
    Possible duplicate of [Validating input using java.util.Scanner](https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom Dec 01 '17 at 12:25

2 Answers2

0

You could just accept all numbers as doubles. Ints and floats could be converted to doulbles seemlesly:

Scanner input = new Scanner(System.in);
List<Double> number = new ArrayList<Double>();
System.out.println("Enter number");
number.add(input.nextDouble());
Marcin Pietraszek
  • 2,779
  • 1
  • 14
  • 29
0

The docs for Scanner should describe what you need. Your scanner can read input as any kind of number that you want. If the input doesn't match what you are expecting it will throw the InputMismatchException.