日期:2014-05-20  浏览次数:20767 次

高手帮改一个很小的程序
Java code
package control;


public class MakeArrary 
{

    public static int[] Test(int statr,int end)
    {
        int[] z = null;
        if(statr<=end)
        {
            int y=end-statr;
            for(int x=statr,i=0;x<=y;x++,i++)
            {
                z[0+i]=x;
            }
        }
        else
        {
            z=null;
        }
        return z;
    }
    public static void main(String[] args)
    {
        int[] z=Test(1,100);
        int y=z.length;
        for(int x=0;x<=y-1;x++)
        {
            System.out.print(z[x]);
        }
    }
}



------解决方案--------------------
public static int[] test(int statr, int end) {
int[] z = null;
if (statr <= end) {
int y = end - statr;
z = new int[y];
for (int x = statr, i = 0; x <= y; x++, i++) {
z[0 + i] = x;
}
} else {
z = null;
}
return z;
}

public static void main(String[] args) {
int[] z = test(1, 100);
int y = z.length;
for (int x = 0; x <= y - 1; x++) {
System.out.print(z[x]);
}
}

你的int数组没有初始化长度,而是null,所以会报空指针错误,增加红色的代码