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

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) {}
}

This is a part of the exercise that I have to do. I already have the rest of the program done, only this part is missing because it is giving the error "Array required, but Charter found".

I realize why the error is happening, but how do I solve it?

    
asked by anonymous 05.04.2014 / 12:31

1 answer

3

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

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) {}
}

Note: Another incongruence 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 since it is already an instance of Carta . The same thing happens with my example above: arrayDesejado has a type pre-set in its definition; therefore, since this type is immutable, it would not be convenient to test whether a given array position saves an instance of a specific class or subclass.

An alternative would be to use a ArrayList within your class Carta to save the objects:

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

Then, to check which objects have been added to the list you could use a loop to scroll through all its elements:

for (Object obj : teste.listaDeObjetos) 
{
    if (obj instanceof Figuras) {}
}
    
05.04.2014 / 13:44