有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

需要数组,但需要java。字符串发现Java类数组错误

我得到以下错误:

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
}

你知道为什么吗


共 (1) 个答案

  1. # 1 楼答案

    在您的代码中,我看到发生错误的唯一方法是如果您确实

    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不是数组,但是[]表示法只适用于数组类型

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