[英]array required, but java.lang.String found Java Class Array Error
I'm getting the following error: 我收到以下错误:
array required, but java.lang.String found
and I'm not sure why. 我不知道为什么。
What I'm trying to do is put an instance of an object (I believe that is correct terminology), into an array of that type of class (of the object). 我想做的是将一个对象的实例(我相信这是正确的术语)放入该类型的(对象的)类数组中。
I have the class: 我上课:
public class Player{
public Player(int i){
//somecodehere
}
}
then in my main method I create an instance of it: 然后在我的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
}
Any ideas why this is? 任何想法为什么会这样?
In your code, the only way I see for that error to happen is if you actually had 在您的代码中,我认为发生该错误的唯一方法是
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
}
In this case, your local variable a
would shadow the static
variable of the same name. 在这种情况下,您的局部变量a
将遮盖同名的static
变量。 The array access expression 数组访问表达式
a[0]
would therefore cause a compilation error like 因此会导致编译错误,例如
Foo.java:13: error: array required, but String found
a[0] = p; // this is the line that throws the error
since a
is not an array, but the []
notation only works for array types. 因为a
不是数组,但是[]
表示法仅适用于数组类型。
You probably just need to save and recompile. 您可能只需要保存并重新编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.