1

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:

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?

7
  • 4
    You are not showing us the code that is throwing the exception. This code is fine. Commented Jan 6, 2014 at 5:42
  • provide us with the code that exception happened! Commented Jan 6, 2014 at 5:43
  • 1
    Just save and recompile. Commented Jan 6, 2014 at 5:43
  • Try stepping through your code in a debugger to identify the exact line that is failing and what the relevant variables are at the time. Commented Jan 6, 2014 at 5:44
  • Is this a compile-time error or a run-time exception? The message reads like a compile-time problem. Commented Jan 6, 2014 at 5:44

1 Answer 1

5

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. 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.

You probably just need to save and recompile.

Sign up to request clarification or add additional context in comments.

2 Comments

That was actually very impressive. It was a problem with my keyboard, I did have another local variable. Thank you!
@user1530491 how come keyboard can cause this problem? :o

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.