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



我一直在努力找出如何正确打印方法的返回。

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

*我确实尝试过使方法的返回为静态的,这样它就可以访问了。

如何初始化"answer"变量,以便在方法之外打印它?提前感谢

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;
}
}

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

最新更新