Thursday, 18 December 2014

// The "Exercise45C_Chapter4" class.
// (from the Carter book)

// Exercise 4.5 - Question 3 (a & b):

// Describe what the fragment does and re-write it using a DO-WHILE statement.

import java.awt.*;
import hsa.Console;

public class Exercise45C_Chapter4
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        // Question 3 (a):

        // 1) prompt the user for a positive integer (0 to stop).
        // 2) read in a positive integer ('value').
        // 3) assign 'value' to 'biggest'.
        // 4) in a WHILE loop, compare 'value' to 0 (value != 0).
        // 5) in an IF statement, if ('value' > 'biggest') is true,
        //    assign 'value' to 'biggest'.
        // 6) prompt the user for another positive integer (0 to stop).
        // 7) read in a positive integer ('value') (0 to stop).

        // Re-written as a DO-WHILE loop:

        int value, biggest = 0;
        do
        {
            c.println ("Enter any integer value - 0 to stop: ");
            c.println ("Calculate the positive value of any negative integer");
            c.println ("then, print out the biggest value you entered");
            c.println ();
            value = Math.abs (c.readInt ()); // makes the input positive
            if (value > biggest)
            {
                biggest = value;
            }
        }
        while (value != 0);
        c.println ("The biggest value you entered is: " + biggest);

        // Question 3 (b):

        // 1) in a FOR loop, must declare and initialize 'i' to 0.
        // 2) in a FOR loop, compare 'i' to 0 (i == 0).
        // 3) in a FOR loop, no incrementation / decrementation occurs.
        // 4) prompt the user as to whether they should continue (Y/N).
        // 5) read in the user's response as a character (Y/N).
        // 6) in an IF statement, if (response == 'Y' || response == 'y'),
        //    then assign 1 to 'i'.  DO loop ends only when the user
        //    reads in 'N' or 'n' to the user prompt to continue.

        // Re-written as a DO-WHILE loop:

        int i = 0;
        char response = 'y';
        do
        {
            if (response == 'N' || response == 'n')
            {
                i = 1;
            }
            c.println ("Continue? (Y/N)");
            response = c.readChar ();
        }
        while (i == 0);
        c.println ("i = " + i);
        c.println ("That's all folks!");

    } // main method
} // Exercise45C_Chapter4 class

No comments:

Post a Comment