数组是必需的,但是找到了java.lang.String Java类数组错误

jak*_*389 1 java arrays object instance

我收到以下错误:

array required, but java.lang.String found
Run Code Online (Sandbox Code Playgroud)

我不知道为什么。

我想做的是将一个对象的实例(我认为这是正确的术语)放入该类型的类(对象的)数组中。

我上课:

public class Player{
     public Player(int i){
           //somecodehere
     }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的main方法中创建它的一个实例:

static final Player[] a = new Player[5]; // this is where I'm trying to create the array.
public static void main(String[] args){
     Player p = new Player(1);
     a[0] = p; //this is the line that throws the error
}
Run Code Online (Sandbox Code Playgroud)

任何想法为什么会这样?

Sot*_*lis 5

在您的代码中,我认为发生该错误的唯一方法是

static final Player[] a = new Player[5]; // this is where I'm trying to create the array.
public static void main(String[] args){
    String a = "...";
    Player p = new Player(1);
    a[0] = p; //this is the line that throws the error
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的局部变量a将覆盖static相同名称的变量。数组访问表达式

a[0]
Run Code Online (Sandbox Code Playgroud)

因此会导致编译错误,例如

Foo.java:13: error: array required, but String found
                a[0] = p; // this is the line that throws the error
Run Code Online (Sandbox Code Playgroud)

因为a它不是数组,但是该[]表示法仅适用于数组类型。

您可能只需要保存并重新编译。