gpt4 book ai didi

java - 当数组在创建它的类之外定义时,为什么会出现 "Array constants can only be used in initializers"

转载 作者:行者123 更新时间:2023-12-02 06:34:41 25 4
gpt4 key购买 nike

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

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;

}
}

最佳答案

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

person2.names = new String[] {"Apple", "Banana"};

关于java - 当数组在创建它的类之外定义时,为什么会出现 "Array constants can only be used in initializers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19779831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com