|
|
|
can mean:
|
|
|
|
|
|
|
![]() |
Note:
|
![]() |
Explanation:
|
(This is the only ambiguous syntax in the Java programming language which it had inherited from C)
|
|
Result:
![]() |
import java.util.Scanner; public class DanglingElse01 { public static void main(String[] args) { int country_code, state_code; double cost; Scanner in = new Scanner(System.in); // Construct Scanner object System.out.print("Enter country code: "); country_code = in.nextInt(); // Read in integer System.out.print("Enter state code: "); state_code = in.nextInt(); // Read in integer cost = 5.0; if ( country_code == 1 ) if ( state_code == 50 ) cost = 10.0; // Hawaii else cost = 20.0; // Outside US System.out.println("Shipping cost = " + cost); } } |
Sample execution:
Enter country code: 1 (code for US) Enter state code: 40 (not Hawaii) Shipping cost = 20.0 (should be $5 !) |
The reason is that the Java program is executed as follows:
![]() |
How to run the program:
|
|
if ( country_code == 1 ) { if ( state_code == 50 ) { cost = 10.0; // Hawaii } } else { cost = 20.0; // Outside US } |
|
If we try, we will get a syntax error:
if ( country_code == 1 ) { if ( state_code == 50 ) { cost = 10.0; // Hawaii } } <--- This extraneous } will cause a syntax error else { cost = 20.0; // Outside US } |
How to run the program:
|
Sample execution:
Enter country code: 1 (code for US) Enter state code: 40 (not Hawaii) Shipping cost = 5.0 (correct !!!) |