Decision Making

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.

8. More than one Statement per Branch


Answer:

    Enter an integer:
    0
    The number 0 is zero or positive
    Good-bye for now

Zero is neither negative nor positive, (although often programs treat zero as if it were positive).
It would be nice to treat it as a separate case. This problem will be fixed in a few pages.

More than one Statement per Branch


Here is the program again with some added statements:

import java.util.Scanner;

public class NumberTester
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner( System.in );
    int num;

    System.out.println("Enter an integer:");
    num = scan.nextInt();

    if ( num < 0 )
    {
      System.out.println("The number " + num + " is negative.");   // true-branch
      System.out.println("Negative numbers are less than zero.");  // true-branch
    } 
    else
    {
      System.out.println("The number " + num +                     // false-branch
        " is zero or positive.");                                  // false-branch
      System.out.print  ("Positive numbers are greater ");         // false-branch
      System.out.println("than zero. ");                           // false-branch
    }

    System.out.println("Good-bye for now");    // always executed
  }
}

To include more than one statement in a branch, enclose the statements with braces, { and }. A group of statements grouped together like this is called a block statement, (or usually, just block).

There can be as many statements as you want in a block. A block can go any place a single statement can go. All the statements in the true block are executed when the answer to the question is true.

Of course, all the statements in the false block are executed when the answer to the question is false. The false block consists of the block that follows the else. Notice that the very last statement in the program is not part of the false block.

Indenting: Indent all the statements in a block to the same level. If a statement takes more than one line, the additional lines are further indented. In these notes, braces each have their own line and are indented to the same level as the if and else. But different coding standards call for different formats. It is important to be consistent.


Question 8:

The user enters a 17. What will the new program print?