【发布时间】:2015-04-19 18:24:04
【问题描述】:
我想用斐波那契数创建一个多维数组。我需要创建奇数行。编译后我收到 NullPointerException。你能帮我找到这个问题的解决方案吗?
public class Scratchpad01
{
public static int fib(int n)
{
if(n <= 1)
{
return n;
}
else
{
return fib(n-1) + fib(n-2);
}
}
public static void main (String args[])
{
int[][] tab = new int[11][];
int count;
for(int i=1; i<11; i++)
{
if(fib(i) % 2 == 0) continue;
else tab[i] = new int[fib(i)];
}
for(int i=1; i<11; i++)
{
count = tab[i].length;
for(int j=0; j<tab[i].length; j++){
tab[i][j] = count--;
}
}
for(int i=1; i<11; i++)
{
for(int j=0; j<tab[i].length; j++)
{
System.out.print(tab[i][j] + " ");
}
System.out.println("");
}
}
}
删除此行后if(fib(i) % 2 == 0) continue;收到:
1
1
2 1
3 2 1
5 4 3 2 1
8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
但我需要:
1
1
3 2 1
5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
...
【问题讨论】:
-
从哪里获得 NPE?
-
我在第 23 行得到 NPE,即“count = tab[i].length;”
标签: java arrays multidimensional-array nullpointerexception null-pointer