Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle invalid input if you need the user to enter an integer?

I'm trying to write a program that takes user integer inputs and does something with them, and continues to do so until the user enters a non-integer input, at which point the user will no longer be asked for input. This is what I've tried:

import java.io.IOException;

public class Question2 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean active = true;
        String num_string_positive = "";
        String num_string_negative = "";
        int my_int;
        while (active) {
            try {
                my_int = in.nextInt();
            } catch(IOException e) {
                active = false;
            }
            in.close(); 
        }
    }

}

This doesn't seem to work; there seems to be something wrong with the catch block. When I hover over IOException, Eclipse says "Unreachable catch block for IOException. This exception is never thrown from the try statement body". Shouldn't a non-integer input throw an I/O exception when I call the nextInt() method?

When I replace catch(IOException e) with catch(Exception e), the code does run, but it always terminates after one input, even if the input is an integer.

What am I doing wrong?

like image 363
Man Avatar asked Dec 18 '22 14:12

Man


1 Answers

First, if the input is not an Integer the exception that will be thrown is InputMismatchException, and you shouldn't close the scanner until you continue with it, try this instead:

import java.util.InputMismatchException;

public class Question2 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean active = true;
        String num_string_positive = "";
        String num_string_negative = "";
        int my_int;
        while (active) {
            try {
                my_int = in.nextInt();
            } catch(InputMismatchException e) {
                active = false;
                in.close();
            } 
        }
    }

}
like image 182
Ismail Avatar answered May 04 '23 00:05

Ismail