Question: Based on the dangling-else discussion in Exercise 3.27, state the output for each of the following code segments when x is 9 and y is

Based on the dangling-else discussion in Exercise 3.27, state the output for each of the following code segments when x is 9 and y is 11 and when x is 11 and y is 9. We eliminated the indentation from the following code to make the problem more challenging.

a)

123456 if (x < 10) if (y > 10) System.out.println(

b)

if (x < 10) { if (y > 10) 9System.out.println(

Exercise 3.27

The Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can lead to what is referred to as the dangling-else problem. The indentation of the nested statement

12345 5 if (x > 5) if (y > 5) System.out.println( 5");">

appears to indicate that if x is greater than 5, the nested if statement determines whether y is also greater than 5. If so, the statement outputs the string "x and y are > 5". Otherwise, it appears that if x is not greater than 5, the else part of the if…else outputs the string "x is

12345 if (x > 5) if (y > 5) else System.out.println( 5"); is">

in which the body of the first if is a nested if…else. The outer if statement tests whether x is greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second condition is false, the string "x is Equally bad, if the outer if statement’s condition is false, the inner if…else is skipped and nothing is displayed. For this exercise, add braces to the preceding code snippet to force the nested if…else statement to execute as it was originally intended.

123456 if (x < 10) if (y > 10) System.out.println("*****"); 4 else System.out.println("#####"); 6 System.out.println("$$$$S");

Step by Step Solution

3.41 Rating (154 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

The images provided include code segments with conditional statements Lets analyze each code segment for the given input values of x and y Starting wi... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Java How To Program Late Objects Questions!