修改有异常的斐波那契程序
Modifying a fibonacci program with an exception
我被分配了一项任务,看看当我向这个名为 FibonacciNumber 的程序输入非整数值(如 a、b、c 等)时会发生什么。我需要使用异常并修改程序,使其不会突然终止,而是给用户一个有意义的消息。现在被困在这个任务上一天半了,但仍然无法解决这个问题。
public class FibonacciNumber {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
try {
if (N < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
System.out.println(N);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
您需要做的就是检查解析输入时抛出的 NumberFormatException。这样做是这样的:
int n;
try {
n = Integer.parseInt(args[0]);
catch (NumberFormatException e) {
System.out.println("Your error message ");
return; // make sure the program cannot continue to execute
}
我被分配了一项任务,看看当我向这个名为 FibonacciNumber 的程序输入非整数值(如 a、b、c 等)时会发生什么。我需要使用异常并修改程序,使其不会突然终止,而是给用户一个有意义的消息。现在被困在这个任务上一天半了,但仍然无法解决这个问题。
public class FibonacciNumber {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
try {
if (N < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
System.out.println(N);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
您需要做的就是检查解析输入时抛出的 NumberFormatException。这样做是这样的:
int n;
try {
n = Integer.parseInt(args[0]);
catch (NumberFormatException e) {
System.out.println("Your error message ");
return; // make sure the program cannot continue to execute
}