How to resolve "Array required, but (Class) found." error?

Asked

Viewed 755 times

1

Also create a test class where you should instantiate an object of the class "Letter" and then the objects that should be stored in the array of that class.

Carta teste = new Carta();
for (int i = 0; i < teste.length; i++) 
{
    if (teste instanceOf Figuras) {}
}

That’s part of the exercise I have to do. I already have the rest of the program done, just missing this part because it is giving the error "Array required, but Charter found".

I understand why the mistake is happening, but how do I fix it?

1 answer

3


The error happens because you are using the property length directly into the object (teste) of your class Carta.

Instead, you can access the array that belongs to your class (assuming it is public and has already been initialized) as follows:

Carta teste = new Carta();
for (int i = 0; i < teste.arrayDesejado.length; i++) 
{
    if (teste.arrayDesejado[i] instanceof Figuras) {}
}

Obs: another inconsistency is due to the use of instanceof (written entirely in lower case). In your code, you are testing whether teste is an instance of Figuras, which will never be true because it is already an instance of Carta. The same happens with my example above: arrayDesejado has a pre-established type in its definition; therefore, as this type is immutable, it would not be convenient to test whether a given position of the array holds an instance of a specific class or subclass.

An alternative would be to use a Arraylist within your class Carta to store the objects:

ArrayList<Object> listaDeObjetos = new ArrayList<Object>();

Then, to check which objects were added to the list you could use a loop that went through all its elements:

for (Object obj : teste.listaDeObjetos) 
{
    if (obj instanceof Figuras) {}
}
  • I used just one example in this case I’m working the class Carta is actually a name class Ginasio, which is a super class, which is why I make use of the instanceof. As to the ArrayList, I actually asked the teacher this question, but he said that in this exercise they wanted to use an array..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.