The Dangling else Problem:

The compiler ignores all indentation and follows the rule that an else always belongs to the closest if.

The ambiguous else is called a dangling else.

 


import java.util.Scanner;

public class AgeTest
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		System.out.print("Please enter your age: ");
		int age = in.nextInt();

		if(age >= 18)
		{
			System.out.println("Enjoy voting!");
			if(age >=65)
				System.out.println("Enjoy senior discount!");
		}
		else
			System.out.println("Play, play, play!!!");
	}
}

What will be printed if age is 5?

What will be printed if age is 20?

What will be printed if age is 70?


import java.util.Scanner;

public class AgeTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter your age: ");
int age = in.nextInt();

if(age >= 18)
System.out.println("Enjoy voting!");
if(age >=65)
System.out.println("Enjoy senior discount!");

else
System.out.println("Play, play, play!!!");
}
}