I am trying to write a program that takes an integer value (n) from the user then invokes my catalan numbers method and finds the nth value. It all works aside from two errors; firstly when I type in 'quit' it gives the error message 'Exception in thread "main" java.lang.NumberFormatException: For input string: "quit"'. And secondly the output keeps on repeating the nth value of the first value of n i put in along with the answer for the new value of n. I am fairly sure this is because of the line 'System.out.println(i)' however I do not know how to fix it so it only shows the answer to the current value of n.
Here is my code:
public class Exercise_3 {
public static long catalan(int n) throws IllegalArgumentException {
int res = 0;
// Base case
if (n <= 1) {
return 1;
}
for (int i = 0; i < n; i++) {
res += catalan(i) * catalan(n - i - 1);
}
return res;
}
public static void exercise3a() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit :");
String input = scan.next();
int number = Integer.parseInt(input);
if (input.equals("quit")) {
System.out.println("quitting");
}
while (!input.equals("quit")){
int i = (int) catalan(number);
System.out.println(i);
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit :");
String continued;
continued = scan.next();
int continue_loop = Integer.parseInt(continued);
int f = (int) catalan(continue_loop);
System.out.println(f);
}
}
public static void main(String[] args) {
exercise3a();
}
}
Any help would be greatly appreciated.