Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 720
dhlee Avatar asked Jan 25 '26 03:01

dhlee


2 Answers

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.

like image 197
Eran Avatar answered Jan 27 '26 17:01

Eran


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.

like image 30
Michael Avatar answered Jan 27 '26 16:01

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!