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?
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();
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With