在Java中访问数组元素时如何修复NullPointerException?

问题描述 投票:0回答:1
I’m working on a Java program where I am trying to access elements from an array, but I keep getting a NullPointerException. Here’s the code I have:

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = null; // Array is not initialized
        System.out.println(numbers[0]); // Trying to access an element
    }
}

我认为数组应该正确初始化,但我仍然得到一个 NullPointerException 。如何解决此问题并在访问数组元素之前正确初始化数组?

nullpointerexception
1个回答
0
投票

您的数组初始化时值为

null
,这意味着它不存在。

你应该这样做:

int[] numbers = new int[10]; //Initializes a new array with a size of ten
for (int i = 0; i < numbers.length; i++) { //fills the array with number from 0 to numbers.length - 1
        numbers[i] = i + 1;
    }
System.out.println(numbers[0])
© www.soinside.com 2019 - 2024. All rights reserved.