空指针异常排序合并数组列表

时间:2015-04-04 21:40:35

标签: java

我一直试图弄清楚如何正确打印我的方法的返回。

当程序打印返回我的方法时,我在第45行(我试图打印方法的行)上给出了nullPointerException错误。

*我确实尝试将方法返回静态,因此可以访问。

如何初始化"答案"变量,以便我可以在我的方法之外打印它? 提前谢谢

import javax.swing.JOptionPane;
public class ListSortMerge {

static int[]answer;

public static void main(String[] args) {
int v1 = 0, v2 = 0;

    for(int c = 0; c <= 1; c++) {
        String values = JOptionPane.showInputDialog("How many values would you like to store in list "+(c+1)+"?");
        if (c==0) {
            v1 = Integer.parseInt(values);
        }
        else{
        v2 = Integer.parseInt(values);
        }
    }

    int[] numbers1 = new int[v1];
    int[] numbers2 = new int[v2];

    merge(numbers1,numbers2);

    int i;

    System.out.println("\nList 1 before the sort");
    System.out.println("--------------------");
    for(i = 0; i < (v1); i++) {
        System.out.println(numbers1[i]);
     }

    System.out.println("\nList 2 before the sort");
    System.out.println("--------------------");
    for(i = 0; i < (v2); i++) {
        System.out.println(numbers2[i]);
    }

    System.out.println("\nList after the sort");
    System.out.println("--------------------");
    for(i = 0; i < (v1+v2); i++) {
        System.out.println(answer[i]);
    }
}

public static int[] merge(int[] a, int[] b) {

int[] answer = new int[a.length + b.length];


for(int c = 0; c < (a.length); c++)
{
    String aVal1 = JOptionPane.showInputDialog("Input list 1 value " +(c+1));
    a[c] = Integer.parseInt(aVal1);
    }

for ( int c = 0; c < (b.length); c++){
        String aVal2 = JOptionPane.showInputDialog("Input list 2 value " +(c + 1));
        b[c] = Integer.parseInt(aVal2);
        }


int i = 0, j = 0, k = 0;

while (i < a.length && j < b.length)
{
    if (a[i] < b[j])       
        answer[k++] = a[i++];

    else        
        answer[k++] = b[j++];               
}

while (i < a.length)  
    answer[k++] = a[i++];


while (j < b.length)    
    answer[k++] = b[j++];

return answer;

}
}

1 个答案:

答案 0 :(得分:0)

您有两个不同的answer变量:一个是merge函数中的局部变量,另一个是类中的静态字段。你永远不会初始化第二个。