【问题标题】:array required, but java.lang.String found Java Class Array Error需要数组,但 java.lang.String 发现 Java 类数组错误
【发布时间】:2014-01-06 05:41:27
【问题描述】:

我收到以下错误:

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
}

有什么想法吗?

【问题讨论】:

  • 您没有向我们展示引发异常的代码。这段代码很好。
  • 向我们提供异常发生的代码!
  • 保存并重新编译。
  • 尝试在调试器中单步执行您的代码,以确定失败的确切行以及当时的相关变量。
  • 这是编译时错误还是运行时异常?该消息看起来像是一个编译时问题。

标签: java arrays object instance


【解决方案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 不是数组,但[] 表示法仅适用于数组类型。

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

【讨论】:

  • 这实际上非常令人印象深刻。这是我的键盘的问题,我确实有另一个局部变量。谢谢!
  • @user1530491 键盘怎么会导致这个问题? :o
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多