Answer:

In this case, the braces are not really needed, but are probably a good idea, for clarity:

if ( a == b )
{  
    if ( d == e )
        total = 0;

    else
        total = total + b;
}

Complete Add Up Numbers Program

Here is the complete program that adds up user-entered integers. It now includes nested ifs that select the proper ending for the numbers in the prompt:

import java.io.*;

// Add up all the integers that the user enters.
// After the last integer, the user enters a 0.
//
class AddUpNumbers
{
  public static void main (String[] args )  
  {
    Scanner scan = new Scanner( System.in );
    String inputData;
    String suffix;
    int value;             // integer entered by the user
    int count = 0;         // how many integers added so far
    int sum   = 0;         // initialize the sum

    // get the first value
    System.out.println( "Enter first integer (enter 0 to quit):" );
    value = scan.nextInt();

    while ( value != 0 )    
    {
      //add value to sum
      sum   = sum + value;     // add current value to the sum
      count = count + 1;       // one more integer added

      // prompt for the next value 
      if ( count+1  == 2  )
        suffix = "nd"; 
      else
        if ( count+1 == 3  )
          suffix = "rd";
        else
          suffix = "th"; 
      System.out.println( "Enter the " + (count+1) + suffix + 
                          " integer (enter 0 to quit):" );

      //get the next value from the user 
      value = scan.nextInt();
      
    }

    System.out.println( "Sum of the integers: " + sum );
  }
}

The program is getting a little bit complicated. The logic involved in prompting the user for the next integer is more complicated than the logic involved in doing the main job of adding up all the integers. It would be nice to put the prompting logic into a separate method called something like promptUser(). This is the topic of a future chapter.

QUESTION 14:

(Thought Question:) The main topic of this chapter is sentinel-controlled loops. Must a sentinel be an integer?