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

空指针异常,第18行,请指正。
[code=Java][/code]import java.util.*;
public class Test1 {
Test1 []a;
int n;
int [] array ;
ArrayList<Integer> b = new ArrayList<Integer>();
public void initialArray(){
Scanner in = new Scanner(System.in);
n = in.nextInt();
a = new Test1[n];
array = new int [n];
for(int op = 0; op < n; op ++){
array [op] = 0;
a[op] = new Test1();
}
for(int start = 0; start < n; start ++){
for(int start1 = 0; start1 < n; start1 ++){
a[start].array[start1] =(int)((Math.random()*n)+1);
a[start].b.add(a[start].array[start1]);
}
System.out.print(a[start].b);
}
}
public void sortArray(){
for(int start = 0; start < n; start ++){
Collections.sort(a[start].b);
System.out.print(a[start].b);
}
}
public static void main(String [] args){
Test1 go = new Test1();
go.initialArray();
System.out.println();
go.sortArray();
}
}


------解决方案--------------------

不是给你指出的错误的所在。。。我汗。。。下面代码可以了

Java code
import java.util.*;

public class Test1 {
    Test1[] a;
    int n;
    int[] array;
    ArrayList<Integer> b = new ArrayList<Integer>();

    public void initialArray() {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        a = new Test1[n];
        array = new int[n];
        for (int op = 0; op < n; op++) {
            array[op] = 0;
            Test1 t1 = new Test1();
            t1.array = array;
            a[op] = t1;
        }
        for (int start = 0; start < n; start++) {
            for (int start1 = 0; start1 < n; start1++) {
                a[start].array[start1] = (int) ((Math.random() * n) + 1);
                a[start].b.add(a[start].array[start1]);
            }
            System.out.print(a[start].b);
        }
    }

    public void sortArray() {
        for (int start = 0; start < n; start++) {
            Collections.sort(a[start].b);
            System.out.print(a[start].b);
        }
    }

    public static void main(String[] args) {
        Test1 go = new Test1();
        go.initialArray();
        System.out.println();
        go.sortArray();
    }
}

------解决方案--------------------
Java code

a[start].array[start1] = (int) ((Math.random() * n) + 1);//a[start].array没有初始化,
在你代码里面a = new Test1[n];array = new int[n];只是对当前对象的array进行了初始化,而你取得的是a[start]这里面的array都没有被初始化。所以报错