Based on K&B 1.5 p318 �...Java law decrees that an else clause belongs to the innermost if to which it might possibly belong(..., the closest preceding if that doesn�t have an else.)..."
I thought, the last else would belong to if ( x == 5 ) since it did not have an else, but compile error: �else� without �if� is given. The pattern is �if, if, else, if, else, else�, which I see indented as
Commenting out lines 6, 7, 10, and 11 which gives �if, if, else, else� pattern, will compile and run. Both cases have equal number of if�s and else�s. Which I see as:
Soooo why doesn�t line 10�s else match up with line 1�s if? Isn�t it the closest if without an else?
If you dont have brackets....than as you know if statement ends with (
if ( x == 5 ) // 1 if ( x > 2 ) // 2 System.out.println( ">2" ) ; // 3 else // 4 System.out.println( "!>2" ) ; // 5
So line 2 and 3 are a if statement, line 4 and 5 are a else statement. Line 1 is the starting of this big if statement comprising of 2,3,4,5 . Line 1 can have a else without a bracket directly at line 6. But in your code it doesnt happen. A new if clause starts at line 6. So the if clause at line 1 doesnt get a else statement.
[ April 25, 2007: Message edited by: megha joshi ] [ April 25, 2007: Message edited by: megha joshi ]