[英]ArrayIndexOutOfBoundException when input is zero
這是我計算n的斐波那契的代碼。 當n = 0
,我不明白,引發了ArrayIndexOutOfBoundException
。 當n = 0
,從fib
函數return 0
。 是什么原因造成的?
import java.util.Scanner;
public class Fibonacci {
public static int fib(int n) {
int[] t = new int[n + 1];
t[0] = 0;
t[1] = 1;
for (int i = 2; i < t.length; i++) {
t[i] = t[i - 1] + t[i - 2];
}
return t[n];
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (;;) {
if (!in.hasNextInt()) {
in.next();
continue;
}
int n = in.nextInt();
if (n >= 0) {
System.out.println(fib(n));
} else {
System.out.println("Invalid input!");
}
break;
}
}
}
當n = 0時,數組int[] t = new int[n + 1];
僅包含1個元素。 但是,您嘗試分配兩個元素:
t[0] = 0;
t[1] = 1;
此代碼可以簡單得多! 為什么會出現此錯誤,是因為當您輸入0時,數組是由元素(0 + 1)創建的,因此是1個元素。 然后,您嘗試提供兩個元素值。 這是使用遞歸的斐波那契數列的示例
public int fibonacci(int n){
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.