The dangling else ambiguity

  1. Java's if statement has an ambiguity problem:

    Example: an ambiguious program (can be read in more than one way...)
       double shippingCharge;
    
       shippingCharge = 5.00;
       if ( country.equals("USA") )
          if ( state.equals("HI") )
             shippingCharge = 10.00;   // Shipping to Hawaii is $10
       else
          shippingCharge = 20.00;      // Shipping to outside USA is $20   
    
    


    See how this program can be read: click here

  2. To resolve this ambiguity, the Java (C/C++) language uses the following rule:

    So, the Java compiler will read this program as:
       double shippingCharge;
    
       shippingCharge = 5.00;
       if ( country.equals("USA") )
          if ( state.equals("HI") )       
             shippingCharge = 10.00; 
          else
             shippingCharge = 20.00; 
    
    

  3. How to force else to associate with the first if:

    So, the proper way to write the program is:
       double shippingCharge;
    
       shippingCharge = 5.00;
       if ( country.equals("USA") )
       {
          if ( state.equals("HI") )
             shippingCharge = 10.00;   // Shipping to Hawaii is $10
       }
       else
          shippingCharge = 20.00;      // Shipping to outside USA is $20   
    
    

    Associating the else with the second if will cause a syntax error !!!