i have a program that I am trying to add exception handling to. The problem is, the exception that i wrote up still exits the program. Basically i offer the user to enter in any int, if they throw me a char, the exception says that they cant do that and lets them enter another int. But it isn't working giving me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at cit130_hw10_q3.Cit130_hw10_q3.main(Cit130_hw10_q3.java:29)
Java Result: 1
Here's some code. Thanks for any help you might offer.
Scanner input = new Scanner(System.in);
System.out.println("Enter a series of integers." +
"When finished enter 999");
int userInput = 0;
int inputCount = 0;
do{
try{
System.out.println("Enter an integer: ");
userInput = input.nextInt();
addToArray(userInput, inputCount);
}
catch(Exception e){
System.out.println("Only integer values are accepted. Please try again");
}
inputCount++;
}while (userInput != 999);
public static void addToArray(int nextInt , int inputCount){
integerArray[inputCount] = nextInt;
}
Exceptionisjava.lang.Exceptionnot something elseaddToArrayfunction might throw some more light on the problem you are facing.. Please show that code..nextIntthrowsInputMismatchException, it will not advance the scanner. CallingnextIntagain will just try to re-read the same non-intagain. You need to invokenext()in thecatchblock to advance the token. With that additional tweak, your code works fine on my computer. I think RC has it right.