Page 170 - CA_Blue( J )_Class9
P. 170

4         public static void main()
                     5         {

                     6             Scanner sc= new Scanner(System.in);
                     7             int a;

                     8             System.out.print("Enter a number :");
                     9             a=sc.nextInt();
                    10             System.out.println("--------------------------");

                    11             if(a>40)

                    12             {
                    13                 if(a>80)
                    14                 System.out.println(a + " is greater than 80");

                    15                 else
                    16                 System.out.println(a + " is greater than 40 and not greater than 80");

                    17             }
                    18             else

                    19             {
                    20                 System.out.println(a + " is not greater than 40");

                    21             }
                    22             System.out.println("--------------------------");

                    23         }
                    24     }

                  You will get the following output:

















                  Dangling Else
                  The dangling else problem in Java (and many other languages) occurs when there is ambiguity about which if
                  statement an else clause is associated with. This can happen when there are nested if statements without proper
                  braces {}.
                  Example of dangling else:

                      if(a==b)
                         if(a>c)

                   168    Touchpad Computer Applications-IX
   165   166   167   168   169   170   171   172   173   174   175