2

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.

2
  • 2
    You are missing a { after for(int j=i+1; j<a.length; j++) (and } later) Commented Sep 16, 2019 at 8:57
  • 4
    You definitely should always use braces, even if the body of the for or if statements contain a single statement. It'll save you from errors exactly like this. Commented Sep 16, 2019 at 9:02

2 Answers 2

8

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.

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

Comments

3

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.

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.