具有整数数组的Java"变量在此位置只能为null"

ACa*_*ter 2 java arrays integer

Null pointer access: The variable 'numbers' can only be null at this location使用以下代码从intellisense 收到错误.(标记错误)

public static int isOne(int incoming){
    String original = Integer.toString(incoming);
    int length = original.length();
    int i;
    int numbers[] = null;

    for(i = 0; i < length; i++){
        String worker = Character.toString(original.charAt(i));
        int workInt = Integer.parseInt(worker);
/* HERE */  numbers[i] = workInt;
        System.out.print(i + "=" + workInt + ","); /* this line just tests it */
    }

    int z;
    int sum = 0;
    int thisNumber = 0;

    for(z = 0; z < length; z++){
/* HERE */  thisNumber = numbers[z]; 
        thisNumber = thisNumber * thisNumber;
        sum = sum + thisNumber;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行代码时,控制台会在第一个错误时给出异常.LogCat什么都没有.

Intellisense给出了@suppress两个错误的建议.

我真的没有线索,但我认为这可能是我初始化'数字'的时候.

谢谢你的帮助.

ami*_*mit 9

您分配numbersnull,而不是与数组指定.

更改:

int numbers[] = null;
Run Code Online (Sandbox Code Playgroud)

int[] numbers = new int[length];
Run Code Online (Sandbox Code Playgroud)

请注意,在java中,声明int[] myVar仅分配对数组的引用,并且实际上不创建数组对象.为了分配数组本身,您可以使用new int[size],并将新对象分配给您想要的变量.