Read this chapter, which reviews how computers make decisions using if statements. As you read this tutorial, you will understand that sometimes it is important to evaluate the value of an expression and perform a task if the value comes out to be true and another task if it is false. In particular, try the simulated program under the heading "Simulated Program" to see how a different response is presented to the user based on if a number is positive or negative.
Pay special attention to the "More Than One Statement per Branch" header to learn how the 'else' statement is used when there is more than one choice.
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?