繁体   English   中英

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

[英]array required, but java.lang.String found Java Class Array Error

我收到以下错误:

array required, but java.lang.String found

我不知道为什么。

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

我上课:

public class Player{
     public Player(int i){
           //somecodehere
     }
}

然后在我的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
}

任何想法为什么会这样?

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

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
}

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

a[0]

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

Foo.java:13: error: array required, but String found
                a[0] = p; // this is the line that throws the error

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM