0

我在另一个类中设置了字符串数组,但是当我尝试以某种方式设置值时,它将返回“数组常量只能在初始化程序中使用”。

import java.util.Scanner;

class People {

    String[] names;
    int age;
    int height;

}

public class Class {
    public static void main(String args[]) {

        People person1 = new People();

        People person2 = new People();

        People person3 = new People();

        // I can set the values like this.

        person1.names[0] = "Joe";
        person1.names[2] = "!";
        person1.names[3] = "?";

        // But not like the more effective way.
        person2.names = {"Apple", "Banana"};

        person1.age = 13;
        person1.height = 164;

    }
}
4

1 回答 1

2

以下语法用于在声明行以外的行实例化数组:

person2.names = new String[] {"Apple", "Banana"};
于 2013-11-05T00:23:55.707 回答