0

I've declared public static arrays for name and id:

public static String[] name = new String[19];     
public static int[] id  = new int[19];

But java compiler says:

java:70: error: array required, but String found
java:71: error: array required, but int found

I don't know what's wrong. Is it how I declared the variables or in the method that I wrote?

public static boolean add(String name, int id, int i) 
{
    if (i < 20) {
        name[i] = name;
        id[i] = id;
        return true;
    }
    else if (i > 20) {
        for (int j = 0; j < id.length; j++) {
            if (id[j] == 0 && name[j].equals("null"))
                id[j] = id;
            name[j] = name; 
        }
        return true;
    }
    else
        return false;
}

2 Answers 2

2

You have a collision between the static name String array and the local name String variable passed to the add method.

The best solution would be to use different names. It would make the code much easier to understand.

If you still insist on using the same name, you can resolve the name collision by accessing the static array using the class name:

YourClassName.name[i]= name;

The same applies to your id int array and id int variable.

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

Comments

2

Pay close attention to how you're using your variables. name (inside of your method) is a String, but you're doing an array element access on it. with i. The same is true for id; it is an int, but you're doing an array element access on it.

You're effectively shadowing your static variables, which causes confusion and heartache.

Consider renaming the parameters to your method, or using the class name to reference them.

Either:

public static boolean add (String theName , int theIds, int i)

or:

// for every usage of id and name as arrays
MyClass.name[i]= name;
MyClass.id[i]=id;

Comments

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.