tags:

views:

48

answers:

3

Hi,

the program gives following exception:

Exception in thread "main" java.lang.NullPointerException at myclasses.BubbleSort.run(BubbleSort.java:42) at acm.program.Program.runHook(Program.java:1519) at acm.program.Program.startRun(Program.java:1508) at acm.program.Program.start(Program.java:729) at myclasses.BubbleSort.main(BubbleSort.java:49)

what is wrong?

thank you very much!

package myclasses;

import acm.program.DialogProgram;

public class BubbleSort extends DialogProgram {
    int[] array;

    public int[] getArray() {
    return array;
    }

    public void setArray(int[] array) {
    this.array = array;
}   


void swap(int firstPos, int secondPos) {
    int temp = array[firstPos];
    array[firstPos] = array[secondPos];
    array[secondPos] = temp;
}

public void bubblesort() {
    int i, j, k;
    for (i = 1; i < array.length; i++) {
        j = i;
        k = array[i];
        while (j > 0 && array[j - 1] > k) {
            array[j] = array[j - 1];
            --j;
        }
        array[j] = k;
    }
} 


public void run() {
    BubbleSort a = new BubbleSort();
    a.setArray(new int[] {1, 3, 5, 7, 6, 2});
    a.bubblesort();
    StringBuffer sb = new StringBuffer(a.array.length * 2);
    for (int i = 0; i < getArray().length; i++) sb.append(getArray()[i]).append(" ");
    println(sb);

}    


public static void main(String[] args) {
    new BubbleSort().start(args);

            }

}
A: 

Check what getArray() is returning. My guess would be null

Or

For one of the iterations getArray()[i] returns null

Scobal
I dont know why it should be return null.
qzar
A: 

Change the for loop in your run method to:

for (int i = 0; i < a.getArray().length; i++) sb.append(a.getArray()[i]).append(" ");

Explanation:

On this line you had 2 calls to getArray() which will call getArray() on the instance of BubbleSort created in main whereas the array has been set on a, the instance of BubbleSort created in run() so the 2 calls to getArray in the for loop need to be a.getArray(). The array in the instance created in main has never been set so getArray().length will throw a NullPointerException.

mikej
thank you very much! this was the problem.
qzar
A: 

Line 42 is for (int i = 0; i < getArray().length; i++) sb.append(getArray()[i]).append(" ");

Only object that can ben null on this line getArray. So add this to your for loop (int i = 0; getArray()!=null && i < getArray().length; i++) .

Also I would check the method populating the content of getArray() to see why it's null.

CoolBeans