10. Only One Statement per Branch


Answer:

No. The programmer probably wants the three statements after the else to be part of a false block,
but has not used braces to show this.

Only One Statement per Branch

The false block was not put inside braces:

if ( num < 0 )
    System.out.println("The number " + num + " is negative.");   
else
    System.out.println("The number " + num + " is zero or positive.");  
    System.out.print  ("Positive numbers are greater ");  
    System.out.println("than zero. ");    

System.out.println("Good-bye for now");  

Our human-friendly indenting shows what we want, but the compiler ignores indenting. The compiler groups statements according to the braces. What it sees is the same as this:

if ( num < 0 )
System.out.println("The number " + num + " is negative."); // true-branch
else
System.out.println("The number " + num + " is zero or positive"); // false-branch
System.out.print ("Positive numbers are greater "); // always executed
System.out.println("or equal to zero. "); // always executed
System.out.println("Good-bye for now"); // always executed

The compiler expects a single statement to follow the if and a single statement to follow the else. However, a block statement works as a single statement.


Question 10:

How would you fix the problem?