Java 给数组赋值的空指针异常

Java null pointer exception from assigning value to array

我正在编写一个程序,它将获取多个数字并按升序和降序显示它们。当我尝试将输入分配给数组时,我得到一个空指针异常,我不确定为什么。任何帮助将不胜感激。

这是我的代码:

static int[] numbers;
public static void main(String[] args) {
    int i=0;        
    while(i<50)
    {            

        String input = JOptionPane.showInputDialog("Enter any number or type X to exit");
        System.out.println(input);
        if(input.equals("X"))
        {
            break;
        }
        numbers[i]=Integer.parseInt(input);//This is where i get the exception          
        i++;
    }

您还没有实例化numbers。你需要做的:

numbers = new int[50];

在方法的开头。

但是,实际上您最好使用允许动态调整大小的 ArrayList<Integer>,而不是固定大小的数组。你会这样做:

List<Integer> numbers = new ArrayList<Integer>();
...
numbers.add(Integer.parseInt(input));

如果您将超过 50 个数字添加到数组中,这不会导致问题,而固定大小的数组会。