user252514
user252514

Reputation: 337

validate data type at the time of user input

I want to validate the data type, (in my case it is 'int'), at the time of user input using Scanner.

I wrote code below.

    public static void main(String[] args) throws IOException {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter size of an array...");
    int n = 0;

     // 1st block, n <= 100
    do {
        System.out.println("Capacity must be less than or equal to 100");
        try {
            n = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Enter only integers ");
        }
    } while (n > 100);

    int[] arr = new int[n];

    // block 2. Value must be greater than 0 and less than 10000
    for (int i = 0; i < n;) {
        do {
            try {
                arr[i] = scanner.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Enter only integer value");
            }
        } while (arr[i] > 10000 || arr[i] < 1);
        i++;
    }

    scanner.close();

    for (int i = n - 1; i >= 0; i--)
        System.out.println(arr[i]);
    }
}

Issue is, in 1st block, if i give character, program terminates. "How to keep loop running on failed validation??"

in 2nd block if i give non integer, it runs infinitely with message, "Enter only integer value".

From debug, i conclude that, Without waiting for input it takes last non-int value which was provided before.

Why compiler is taking last value??

Any suggestion ?

Upvotes: 1

Views: 85

Answers (2)

F. Mudrunek
F. Mudrunek

Reputation: 31

As an addition to davidxxx's answer: Here's the same code using Scanner.hasNextInt() method.

Scanner scanner = new Scanner(System.in);

System.out.println("Enter size of an array...");
while (!scanner.hasNextInt()) scanner.next();
int arrayLength = scanner.nextInt();

int[] arr = new int[arrayLength];

boolean arrayFull = false;
int index = 0;

System.out.println("Enter array values");
while (!arrayFull){
    while (!scanner.hasNextInt()) scanner.next();
    int value = scanner.nextInt();
    if (value < 0 || value > 1000) {
        System.out.println("Enter only integer value < 0 and > 1000");
        continue;
    }
    arr[index++] = value;

    if (index >= arrayLength){
        arrayFull = true;
    }
}

Upvotes: 1

davidxxx
davidxxx

Reputation: 131546

1) You assign 0 as default value of the n integer you are using to get the user input : int n = 0;
So if the input triggers a InputMismatchException, you arrive in the while statement with a n that equals 0 and while (n > 100) with n = 0 is false.
So you exit the loop.
To solve this problem :

  • use a wrapper Integer : Integer n = null; that has a nullable value allows to know if no value was accepted in the scanner reading

  • change the while statement condition to check your requirement :

    while (n == null || n > 100);


2) For first case as for the second case, if the input doesn't match with the type required (here a int value), the current token in the scanner is not read.
Just ignore this token to avoid entering in an infinite loop :

   catch (InputMismatchException e) {
        ...
        scanner.nextLine();
    }

Upvotes: 2

Related Questions