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 に答える