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 。如何解决此问题并在访问数组元素之前正确初始化数组?
您的数组初始化时值为
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])