Variable repeat error?

Why am I getting a compile-time error in the following code?

private static void phi(int n){
    if((n > 1000)
        for(int i = 3; i <= n; i += 2)
            //do something
    else
        for(int i = 35; i <= n; i += 90)
            //do something
}

The error says

java:22: error: variable i is already defined in method phi(int)

But according to me, at any scenario, either if statement or else statement will be executed, but never both will be executed at the same time.

Is this a loophole in Java’s compilation techniques or is my method wrong?


Source: java

1 Comment

  1. Digin Dominic

    There is more than one line after the if and before the else, so you have to use braces to get desired behaviour, not necessary in for statement, but mandatory in the if in this case.

    there is an extra ( in the first if!

    private static void phi(int n){
    if(n > 1000) {
    for(int i = 3; i <= n; i += 2)
    //do something
    } else {
    for(int i = 35; i <= n; i += 90)
    //do something
    }
    }

    Reply

Leave a Reply