Problems with sorting (not a statement)

83 Views Asked by At

The function is suposed to sort the highscore board in the game according to time.

public void sort()
{
    boolean unsorted = true;
    int i;

    for ( ; unsorted; i < this.inputArray.length - 1)
    {  
        unsorted = false;
        i = 0; continue;
        if (Integer.parseInt(this.inputArray[i][1]) <= Integer.parseInt(this.inputArray[(i + 1)][1]))
        {
            int tempTime = Integer.parseInt(this.inputArray[i][1]);
            String tempName = this.inputArray[i][0];
            this.inputArray[i][1] = this.inputArray[(i + 1)][1];
            this.inputArray[i][0] = this.inputArray[(i + 1)][0];
            this.inputArray[(i + 1)][1] = String.valueOf(tempTime);
            this.inputArray[(i + 1)][0] = String.valueOf(tempName);
            unsorted = true;
        }
        i++;
    }
}

The problem is, that IDE throws a "not a statement" error at 'for' loop, and "unreachable statement" error on 'if'.

Can anyone help?

2

There are 2 best solutions below

0
On

The first error is because

i < this.inputArray.length - 1

is not something you can execute - that is, it's not a statement. But the third part in the brackets of a for loop is the statement which will be executed at the end of each iteration of the loop.

The second error is because

continue;

means start the loop again, with the next iteration. Which means that everything after the continue is dead code that can never be reached. The compiler is trying to protect you from what can only be a mistake.

0
On

Unreachable Statement: You assign i = 0, and then continue, and put i++ at the end, i will never be anything else than 0, so the if clause is unreachable

Your for loop syntax is incorrect as well:

for (initialization; termination;
     increment) {
    statement(s)
}
  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • The termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop

(Taken from Oracle doc)