0

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?


EDIT 2

Brackets seem to have fixed the problem. Thanks a lot blackbelt.


EDIT 1

Double parenthesis doesn't seem to be a reason as I still get an error after removing the parenthesis. In fact the double parenthesis got added by mistake.

Community
  • 1
  • 1
Confuse
  • 5,646
  • 7
  • 36
  • 58
  • 1
    if((n > 1000) you have an exrta bracket in here? also, check the answer out in this question in relation to "either if statement or else statement will be executed" : http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array – Alan Kavanagh May 14 '15 at 15:46

2 Answers2

3

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.

Also, as @Joseph82 pointed... 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
    }
}
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
1

Remove an extra ( from if((n > 1000) and use Blocks and Curly Braces.

Harsh Dattani
  • 2,109
  • 1
  • 17
  • 27