• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

If-else matching question

 
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

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?

Richard
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The case actually is

 
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,


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 ]
 
Richard Boren
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, I got it.

Richard
 
The overall mission is to change the world. When you've done that, then you can read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic