dhlee
dhlee

Reputation: 37

How to fix 'cannot be resolved to a variable' error in Java

I'm trying to implement a very simple sorting method that takes int array and sorts elements in ascending order, but I'm stuck with errors about variables

    public int[] sort1(int[] a){
        for (int i=0; i<a.length;i++)
            for(int j=i+1; j<a.length; j++)
                int min = a[i];
                if (a[j] < min) {
                    a[i] = a[j];
                    a[j] = min;
                    min = a[i];
                }
        return a;
    }

i cannot be resolved to a variable j cannot be resolved to a variable min cannot be resolved to a variable

I don't know why these errors come up and how to fix them.

Upvotes: 2

Views: 12466

Answers (2)

Michael
Michael

Reputation: 44250

To complement Eran's answer, to the compiler this block

for (int j=i+1; j<a.length; j++)
    int min = a[i];
    if (a[j] < min) {
        a[i] = a[j];
        a[j] = min;
        min = a[i];
    }

is really something more like this

for (int j=i+1; j<a.length; j++) int min = a[i];
if (a[j] < min) {
    a[i] = a[j];
    a[j] = min;
    min = a[i];
}

Remember, Java is not a whitespace-aware language like Python, for example.

The first line here is also illegal. You can't perform assignment in a for-loop without braces - probably because there is no way to access the variable after the assignment since it is immediately out of scope.

Upvotes: 3

Eran
Eran

Reputation: 394156

You are missing curly braces:

public int[] sort1(int[] a){
    for (int i=0; i<a.length;i++) {
        for(int j=i+1; j<a.length; j++) {
            int min = a[i];
            if (a[j] < min) {
                a[i] = a[j];
                a[j] = min;
                min = a[i];
            }
        }
    }
    return a;
}

The inner loop has multiple statements, so you must enclose them with curly braces.

While the outer loop has only one statement, it is still advisable to enclose it with curly braces too.

Upvotes: 8

Related Questions