• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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
 
Curse your sudden but inevitable betrayal! And this tiny ad too!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic