我正在尝试编写一个程序,该程序从用户那里获取一个整数值 (n),然后调用我的 catalan numbers 方法并找到第 n 个值。除了两个错误之外,这一切都有效;首先,当我输入“退出”时,它会给出错误消息“线程“主”java.lang.NumberFormatException 中的异常:对于输入字符串:“退出”。其次,输出不断重复输入的第一个 ni 值的第 n 个值以及 n 的新值的答案。我很确定这是因为'System.out.println(i)'行但是我不知道如何修复它,所以它只显示了n当前值的答案。
这是我的代码:
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();
}
}
任何帮助将不胜感激。