OK, here's my problem. Our teacher wants us to create a program that creates a Fibonacci sequence and then the user can do operation with the array of numbers (like get number at an index, etc). I wanted to go above and beyond and idiot-proof it. I asked her about try/catch statements but she said that it was not in the curriculum.So, I did research and made this code:
while( valid ) {
try {
lengthOfSequence = keyboard.nextInt();
} catch ( Exception e ) {
out.println( "You entered an " + e + ". Please enter a number between 1 and " + maxLength );
throw e;
}
}
(valid it true initially) So the code is supposed to get an integer that the user inputs. Then take that integer and assign it to lengthOfSequence. Running it properly (inputting an integer) will allow the code to run correctly, but when I plug in a "o" (or any other string) for my input, the catch is not catching the Exception and I get this error:
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 FibonacciRunner.main(FibonacciRunner.java:28)
I've tried many ways to try to fix it including:lengthOfSequence = Integer.parseInt( keyboard.nextLine() );
which gives me
java.lang.NumberFormatException: For input string: "o"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at FibonacciRunner.main(FibonacciRunner.java:29)
I've also tried naming the exception InputMismatchException
and NumberFormatException
but still I get an error.
I'm a novice at coding and at Stack Overflow, so thank you in advance for the help
EDIT:
I have tried removing the throw e
but all that does is create an endless loop of the code outputting "You entered an java.util.InputMismatchException. Please enter a number between 1 and 101".
Also I removed this from the try statement because I thought it would not pertain to the question
if( lengthOfSequence > 1 && lengthOfSequence < maxLength ) {
fibonacci.createSequence( lengthOfSequence );
valid = false;
}