Exercises

Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.


8.2 Create a class called Complex for performing arithmetic with complex numbers. Write a driver program to test your class.

Complex numbers have the form

realPart + imaginaryPart * i

where i is

Use floating-point variables to represent the private data of the class. Provide a constructor method that enables an object of this class to be initialized when it is declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods for each of the following:

  1. Addition of two Complex numbers: The real parts are added together and the imaginary parts are added together.
  2. Subtraction of two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
  3. Printing Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.

8.3 Create a class called Rational for performing arithmetic with fractions. Write a driver program to test your class.

Use integer variables to represent the private instance variables of the class–the numerator and the denominator. Provide a constructor method that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form (i.e., the fraction

2/4

would be stored in the object as 1 in the numerator and 2 in the denominator). Provide a no- argument constructor with default values in case no initializers are provided. Provide public methods for each of the following:

  1. Addition of two Rational numbers. The result of the addition should be stored in reduced form.
  2. Subtraction of two Rational numbers. The result of the subtraction should be stored in reduced form.
  3. Multiplication of two Rational numbers. The result of the multiplication should be stored in reduced form.
  4. Division of two Rational numbers. The result of the division should be stored in reduced form.
  5. Printing Rational numbers in the form a/b, where a is the numerator and b is the denominator.
  6. Printing Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.)

8.4 Modify the Time3 class of Fig. 8.5 to include the tick method that increments the time stored in a Time3 object by one second. Also provide method incrementMinute to increment the minute and method incrementHour to increment the hour. The Time3 object should always remain in a consistent state. Write a driver program that tests the tick method, the incrementMinute method and the incrementHour method to ensure that they work correctly. Be sure to test the following cases:

  1. Incrementing into the next minute.
  2. Incrementing into the next hour.
  3. Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).

8.5 Modify the Date class of Fig. 8.8 to perform error checking on the initializer values for instance variables month, day and year. Also, provide a method nextDay to increment the day by one. The Date object should always remain in a consistent state. Write a driver program that tests the nextDay method in a loop that prints the date during each iteration of the loop to illustrate that the nextDay method works correctly. Be sure to test the following cases:

  1. Incrementing into the next month.
  2. Incrementing into the next year.

8.6 Combine the modified Time3 class of Exercise 8.4 and the modified Date class of Exercise 8.5 into one class called DateAndTime. Modify the tick method to call the nextDay method if the time is incremented into the next day. Modify methods toString and toUniversalString() to output the date in addition to the time. Write a driver program to test the new class DateAndTime. Specifically test incrementing the time to the next day.

8.7 Modify the set methods in the program of Fig. 8.5 to return appropriate error values if an attempt is made to set one of the instance variables hour, minute or second of an object of class Time to an invalid value. (Hint: Use boolean return types on each method.)

8.8 Create a class Rectangle. The class has attributes length and width, each of which defaults to 1. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0.

8.9 Create a more sophisticated Rectangle class than the one you created in Exercise 8.8. This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set method that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The set method also verifies that the supplied coordinates do, in fact, specify a rectangle. Provide methods to calculate the length, width, perimeter and area. The length is the larger of the two dimensions. Include a predicate method isSquare which determines if the rectangle is a square.

8.10 Modify the Rectangle class of Exercise 8.9 to include a draw method that displays the rectangle inside a 25-by-25 box enclosing the portion of the first quadrant in which the rectangle resides. Use the methods of the Graphics class to help output the Rectangle. If you feel ambitious, you might include methods to scale the size of the rectangle, rotate it and move it around within the designated portion of the first quadrant.

8.11 Create a class HugeInteger which uses a 40-element array of digits to store integers as large as 40 digits each. Provide methods inputHugeInteger, outputHugeInteger, add- HugeIntegers and substractHugeIntegers. For comparing HugeInteger objects, provide methods isEqualTo, isNotEqualTo, isGreaterThan, isLessThan, IsGreaterThanOrEqualTo and isLessThanOrEqualToeach of these is a "predicate" method that simply returns true if the relationship holds between the two HugeIntegers and returns false if the relationship does not hold. Provide a predicate method isZero. If you feel ambitious, also provide the method multiplyHugeIntegers, the method divideHugeIntegers and the method modulusHugeIntegers.

8.12 Create a class TicTacToe that will enable you to write a complete program to play the game of Tic-Tac-Toe. The class contains as private data a 3-by-3 double array of integers. The constructor should initialize the empty board to all zeros. Allow two human players. Wherever the first player moves, place a 1 in the specified square; place a 2 wherever the second player moves. Each move must be to an empty square. After each move determine if the game has been won, or if the game is a draw. If you feel ambitious, modify your program so that the computer makes the moves for one of the players automatically. Also, allow the player to specify whether he or she wants to go first or second. If you feel exceptionally ambitious, develop a program that will play three-dimensional Tic-Tac-Toe on a 4-by-4-by-4 board [Note: This is a challenging project that could take many weeks of effort!].

8.13 Explain the notion of package access in Java. Explain the negative aspects of package access as described in the text.

8.14 What happens when a return type, even void, is specified for a constructor?

8.15 Create a Date class with the following capabilities:

  1. Output the date in multiple formats such as

    MM/DD/YYYY
    June 14, 1992
    DDD YYYY

  2. Use overloaded constructors to create Date objects initialized with dates of the formats in part a).

8.16 Create class SavingsAccount. Use a static class variable to store the annualInterestRate for all of the savers. Each object of the class contains a private instance variable savingsBalance indicating the amount the saver currently has on deposit. Provide method calculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12; this interest should be added to savingsBalance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new value. Write a driver program to test class SavingsAccount. Instantiate two different savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the new balances for each of the savers. Then set the annualInterestRate to 5% and calculate the next month’s interest and print the new balances for each of the savers.

8.17 Create class IntegerSet. Each object of the class can hold integers in the range 0 through 100. A set is represented internally as an array of booleans. Array element a[i] is true if integer i is in the set. Array element a[j] is false if integer j is not in the set. The no-argument constructor initializes a set to the so-called "empty set" (i.e., a set whose array representation contains all false values).

Provide the following methods: Method unionOfIntegerSets creates a third set which is the set-theoretic union of two existing sets (i.e., an element of the third set’s array is set to true if that element is true in either or both of the existing sets; otherwise, the element of the third set is set to false). Method intersectionOfIntegerSets creates a third set which is the set-theoretic intersection of two existing sets i.e., an element of the third set’s array is set to false if that element is false in either or both of the existing sets; otherwise, the element of the third set is set to true). Method insertElement inserts a new integer k into a set (by setting a[k] to true). Method deleteElement deletes integer m (by setting a[m] to false). Method setPrint prints a set as a list of numbers separated by spaces. Print only those elements that are present in the set. Print --- for an empty set. Method isEqualTo determines if two sets are equal. Write a program to test your IntegerSet class. Instantiate several IntegerSet objects. Test that all your methods work properly.

8.18 It would be perfectly reasonable for the Time1 class of Fig. 8.1 to represent the time internally as the number of seconds since midnight rather than the three integer values hour, minute and second. Clients could use the same public methods and get the same results. Modify the Time1 class of Fig. 8.1 to implement the Time1 as the number of seconds since midnight and show that there is no visible change to the clients of the class.

8.19 (Drawing Program) Create a drawing applet that randomly draws lines, rectangles and ovals. For this purpose, create a set of "smart" shape classes where objects of these classes know how to draw themselves if provided with a Graphics object that tells them where to draw (i.e., the applet’s Graphics object allows a shape to draw on the applet’s background). The class names should be MyLine, MyRect and MyOval.

The data for class MyLine should include x1, y1, x2 and y2 coordinates. Method drawLine method of class Graphics will connect the two points supplied with a line. The data for classes MyRect and MyOval should include an upper-left x-coordinate value, an upper-left y-coordinate value, a width (must be nonnegative) and a height (must be nonnegative). All data in each class must be private.

In addition to the data, each class should define at least the following public methods:

  1. A constructor with no arguments that sets the coordinates to 0.
  2. A constructor with arguments that sets the coordinates to the supplied values.
  3. Set methods for each individual piece of data that allow the programmer to independently set any piece of data in a shape (e.g., if you have an instance variable x1, you should have a method setX1).
  4. Get methods for each individual piece of data that allow the programmer to independently retrieve any piece of data in a shape (e.g., if you have an instance variable x1, you should have a method getX1).
  5. A draw method with the first line

public void draw( Graphics g )

will be called from the applet’s paint method to draw a shape onto the screen.

The preceding methods are required. If you would like to provide more methods for flexibility, please do so.

Begin by defining class MyLine and an applet to test your classes. The applet should have a MyLine instance variable line that can refer to one MyLine object (created in the applet’s init method with random coordinates). The applet’s paint method should draw the shape with a statement like

line.draw( g );

where line is the MyLine reference and g is the Graphics object that the shape will use to draw itself on the applet.

Next, change the single MyLine reference into an array of MyLine references and hard code several MyLine objects into the program for drawing. The applet’s paint method should walk through the array of MyLine objects and draw every one.

After the preceding part is working, you should define the MyOval and MyRect classes and add objects of these classes into the MyRect and MyOval arrays. The applet’s paint method should walk through each array and draw every shape. Create five shapes of each type.

Once the applet is running, select Reload from the appletviewer’s Applet menu to reload the applet. This will cause the applet to choose new random numbers for the shapes and draw the shapes again.

In Chapter 9, we will modify this exercise to take advantage of the similarities between the classes and to avoid reinventing the wheel.


Selected Answers

Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.


8.2

// Exercise 8.2 Solution
// Complex.java
// Definition of class Complex

public class Complex {
   private double real;
   private double imaginary;

   // Initialize both parts to 0
   public Complex() { this( 0.0, 0.0 ); }

   // Initialize real part to r and imaginary part to 0
   public Complex( double r ) { this( r, 0.0 ); }

   // Initialize real part to r and imaginary part to i
   public Complex( double r, double i )
   {
      real = r;
      imaginary = i;
   }

   // Add two Complex numbers
   public Complex add( Complex right )
   {
      return new Complex( real + right.real,
                    imaginary + right.imaginary );
   }

   // Subtract two Complex numbers
   public Complex subtract( Complex right )
   {
      return new Complex( real - right.real,
                    imaginary - right.imaginary );
   }

   // Return String representation of a Complex number
   public String toString() 
      { return "(" + real + ", " + imaginary + ")"; }
}

// Exercise 8.2: ComplexTest.java
// Test the Complex number class
import javax.swing.*;

public class ComplexTest {
   public static void main( String args[] )
   {
      Complex a, b;
      a = new Complex( 9.9, 7.7 );
      b = new Complex( 1.2, 3.1 );
 
      String result = "a = " + a;
      result += "\nb = " + b;
      result += "\na + b = " + a.add( b );
      result += "\na - b = " + a.subtract( b );
   
      JOptionPane.showMessageDialog(
            null, result, "Complex Test",
            JOptionPane.INFORMATION_MESSAGE );
      System.exit( 0 );
   }
}

8.4

// Exercise 8.4 Solution
// Time3.java
// Time3 class definition
public class Time3 {
   private int hour;     // 0 - 23
   private int minute;   // 0 - 59
   private int second;   // 0 - 59

   // Time constructor initializes each instance variable
   // to zero. Ensures that Time3 object starts in a 
   // consistent state.
   public Time3() { setTime( 0, 0, 0 ); }

   // Time3 constructor: hour supplied, minute and second
   // defaulted to 0.
   public Time3( int h ) { setTime( h, 0, 0 ); }

   // Time3 constructor: hour and minute supplied, second
   // defaulted to 0.
   public Time3( int h, int m ) { setTime( h, m, 0 ); }

   // Time3 constructor: hour, minute and second supplied.
   public Time3( int h, int m, int s ) { setTime( h, m, s ); }

   // Set Methods
   // Set a new Time3 value using military time. Perform 
   // validity checks on the data. Set invalid values 
   // to zero.
   public void setTime( int h, int m, int s )
   {
      setHour( h );    // set the hour
      setMinute( m );  // set the minute
      setSecond( s );  // set the second
   }

   // set the hour 
   public void setHour( int h ) 
      { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); }

   // set the minute 
   public void setMinute( int m ) 
      { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); }

   // set the second 
   public void setSecond( int s ) 
      { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

   // Get Methods
   // get the hour
   public int getHour() { return hour; }

   // get the minute
   public int getMinute() { return minute; }

   // get the second
   public int getSecond() { return second; }

   // Convert to String in military-time format
   public String toMilitaryString()
   {
      return ( hour < 10 ? "0" : "" ) + hour +
             ( minute < 10 ? "0" : "" ) + minute;
   }

   // Convert to String in standard-time format
   public String toString()
   {
      return ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ) +
             ":" + ( minute < 10 ? "0" : "" ) + minute +
             ":" + ( second < 10 ? "0" : "" ) + second +
             ( hour < 12 ? " AM" : " PM" );
   }

   // Tick the time by one second
   public void tick()
   {
      setSecond( second + 1 );

      if ( second == 0 )
         incrementMinute();
   }

   // Increment the minute
   public void incrementMinute()
   {
      setMinute( minute + 1 );

      if ( minute == 0 )
         incrementHour();
   }

   // Increment the hour
   public void incrementHour()
   {
      setHour( hour + 1 );
   }
}

// Exercise 8.4 Solution
// TimeTest.java
// Demonstrating the Time class set and get methods
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class TimeTest extends JApplet
            implements ActionListener {
   private Time3 t;
   private JLabel hrLabel, minLabel, secLabel;
   private JTextField hrField, minField, secField, display;
   private JButton tickButton;

   public void init()
   {
      t = new Time3();

      hrLabel = new JLabel( "Set Hour" );
      hrField = new JTextField( 10 );
      hrField.addActionListener( this );
      minLabel = new JLabel( "Set Minute" );
      minField = new JTextField( 10 );
      minField.addActionListener( this );
      secLabel = new JLabel( "Set Second" );
      secField = new JTextField( 10 );
      secField.addActionListener( this );
      display = new JTextField( 30 );
      display.setEditable( false );
      tickButton = new JButton( "Add 1 to Second" );
      tickButton.addActionListener( this );
       
      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
      c.add( hrLabel );
      c.add( hrField );
      c.add( minLabel );
      c.add( minField );
      c.add( secLabel );
      c.add( secField );
      c.add( display );
      c.add( tickButton );
      updateDisplay();      
   }

   public void actionPerformed( ActionEvent e )
   {
      if ( e.getSource() == tickButton )
         t.tick();
      else if ( e.getSource() == hrField ) {
         t.setHour( Integer.parseInt( e.getActionCommand().toString() ) );
         hrField.setText( "" );
      }
      else if ( e.getSource() == minField ) {
         t.setMinute( Integer.parseInt( e.getActionCommand().toString() ) );
         minField.setText( "" );
      }
      else if ( e.getSource() == secField ) {
         t.setSecond( Integer.parseInt( e.getActionCommand().toString() ) );
         secField.setText( "" );
      }

      updateDisplay();
   }

   public void updateDisplay()
   {
      display.setText( "Hour: " + t.getHour() +
         "; Minute: " + t.getMinute() +
         "; Second: " + t.getSecond() );
      showStatus( "Standard time is: " + t.toString()+
         "; Military time is: " + t.toMilitaryString() );
   }
}

8.7

// Exercise 8.7 Solution
// Time3.java
// Program adds validation to Fig. 8.5 example

public class Time3 {
   private int hour;     // 0 - 23
   private int minute;   // 0 - 59
   private int second;   // 0 - 59

   public Time3() { this( 0, 0, 0 ); }

   public Time3( int h ) { this( h, 0, 0 ); }

   public Time3( int h, int m ) { this( h, m, 0 ); }

   public Time3( int h, int m, int s ) { setTime( h, m, s ); }

   public boolean setTime( int h, int m, int s )
   {
      boolean hourValid, minuteValid, secondValid;

      hourValid = setHour( h );      // set the hour
      minuteValid = setMinute( m );  // set the minute
      secondValid = setSecond( s );  // set the second

      return ( hourValid && minuteValid && secondValid );
   }

   public boolean setHour( int h ) 
   {
      if ( h >= 0 && h < 24 ) {
         hour = h;
         return true;
      }
      else {     
         hour = 0;
         return false;
      }
   }  

   // set the minute 
   public boolean setMinute( int m ) 
   {  
      if ( m >= 0 && m < 60 ) {
         minute = m;
         return true;
      }
      else {    
         minute = 0;
         return false;
      }
   }

   // set the second 
   public boolean setSecond( int s ) 
   {
      if ( s >= 0 && s < 60 ) {
         second = s;
         return true;
      }
      else {    
         second = 0;
         return false;
      }
   }

   // Get Methods  
   public int getHour() { return hour; }

   public int getMinute() { return minute; }

   public int getSecond() { return second; }

   public String toMilitaryString()
   {
      return ( hour < 10 ? "0" : "" ) + hour +
             ( minute < 10 ? "0" : "" ) + minute;
   }

   public String toString()
   {
      return ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ) +
             ":" + ( minute < 10 ? "0" : "" ) + minute +
             ":" + ( second < 10 ? "0" : "" ) + second +
             ( hour < 12 ? " AM" : " PM" );
   }
}

// Exercise 8.7 Solution
// TimeTest.java
// Program adds validation to Fig. 8.5 example
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class TimeTest extends JApplet
          implements ActionListener {
   private Time3 t;
   private JLabel hrLabel, minLabel, secLabel;
   private JTextField hrField, minField, secField, display;
   private JButton tickButton;

   public void init()
   {
      t = new Time3();

      hrLabel = new JLabel( "Set Hour" );
      hrField = new JTextField( 10 );
      hrField.addActionListener( this );
      minLabel = new JLabel( "Set Minute" );
      minField = new JTextField( 10 );
      minField.addActionListener( this );
      secLabel = new JLabel( "Set Second" );
      secField = new JTextField( 10 );
      secField.addActionListener( this );
      display = new JTextField( 30 );
      display.setEditable( false );
      tickButton = new JButton( "Add 1 to Second" );
      tickButton.addActionListener( this );

      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
      c.add( hrLabel );
      c.add( hrField );
      c.add( minLabel );
      c.add( minField );
      c.add( secLabel );
      c.add( secField );
      c.add( display );
      c.add( tickButton );
      updateDisplay();      
   }

   public void actionPerformed( ActionEvent e )
   {
      if ( e.getSource() == tickButton )
         tick();
      else if ( e.getSource() == hrField ) {
         if( t.setHour( Integer.parseInt( e.getActionCommand().toString() ) ) )
            hrField.setText( "" );
         else
            hrField.setText( "Invalid hour" );
      }
      else if ( e.getSource() == minField ) {
         if ( t.setMinute( Integer.parseInt( e.getActionCommand().toString() ) ) )
            minField.setText( "" );
         else
            minField.setText( "Invalid minute" );
      }
      else if ( e.getSource() == secField ) {
         if ( t.setSecond( Integer.parseInt( e.getActionCommand().toString() ) ) )
            secField.setText( "" );
         else
            secField.setText( "Invalid second" );
      }

      showStatus( "" );
      updateDisplay();
   }

   public void updateDisplay()
   {
      display.setText( "Hour: " + t.getHour() +
         "; Minute: " + t.getMinute() +
         "; Second: " + t.getSecond() );
      showStatus( "Standard time is: " + t.toString()+
         "; Military time is: " + t.toMilitaryString() );
   }

   public void tick()
   {
      t.setSecond( ( t.getSecond() + 1 ) % 60 );

      if ( t.getSecond() == 0 ) {
         t.setMinute( ( t.getMinute() + 1 ) % 60 );

         if ( t.getMinute() == 0 )
            t.setHour( ( t.getHour() + 1 ) % 24 );
      }
   }
}

8.8

// Exercise 8.8 Solution
// MyRectangle.java
// Definition of class MyRectangle

public class MyRectangle {
   private double length, width;

   public MyRectangle()  { this( 1.0, 1.0 ); }

   public MyRectangle( double l, double w )
   {
      setLength( l );
      setWidth( w );
   }

   public void setLength( double len )
   { length = ( len >= 0.0 && len <= 20.0 ? len : 1.0 ); }

   public void setWidth( double w )
   { width = ( w >= 0 && w <= 20.0 ? w : 1.0 ); }

   public double getLength() { return length; }

   public double getWidth() { return width; }

   public double perimeter() { return 2 * length + 2 * width; }

   public double area() { return length * width; }
}

// Exercise 8.8 Solution
// Definition of class RectangleTest
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class RectangleTest extends JApplet
          implements ActionListener {
   private JLabel prompt1, prompt2;
   private JTextField input1, input2;
   private MyRectangle r;

   public void init()
   {
      prompt1 = new JLabel( "Length:" );
      prompt2 = new JLabel( "Width:" );
      input1 = new JTextField( 10 );
      input2 = new JTextField( 10 );
      input2.addActionListener( this );
      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
      c.add( prompt1 );
      c.add( input1 );
      c.add( prompt2 );
      c.add( input2 );
      r = new MyRectangle();
   }

   public void paint( Graphics g )
   {
      g.drawString( "Length = " + r.getLength(), 25, 75 );
      g.drawString( "Width = " + r.getWidth(), 25, 90 );
      g.drawString( "Perimeter = " + r.perimeter(), 25, 105 );
      g.drawString( "Area = " + r.area(), 25, 120 );
   }

   public void actionPerformed( ActionEvent e )
   {
      double d1, d2;

      d1 = Double.parseDouble( input1.getText() );
      d2 = Double.parseDouble( input2.getText() );

      r.setLength( d1 );
      r.setWidth( d2 );
      repaint();
   }
}

8.13 Explain the notion of package access in Java. Explain the negative aspects of package access as described in the text.

ANS: Package access allows a class, method, or variable to be accessible within the same package. Package access does not promote good OOP when applied to an instance variable, because it destroys the notion of information hiding.

8.14 What happens when a return type, even void, is specified for a constructor?

ANS: It is treated as a method and is not considered to be a constructor.

8.18

// Exercise 8.18 Solution
// Time1 class definition

public class Time1 {
   private int totalSeconds;

   public Time1() { setTime( 0, 0, 0 ); }

   public void setTime( int h, int m, int s )
   {
      int hour, minute, second;

      hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
      minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
      second = ( ( s >= 0 && s < 60 ) ? s : 0 );

      totalSeconds = hour * 3600 + minute * 60 + second;
   }

   public String toMilitaryString()
   {
      int hour, minute, temp;

      hour = totalSeconds / 3600;
      temp = totalSeconds % 3600;
      minute = temp / 60;

      return ( hour < 10 ? "0" : "" ) + hour +
             ( minute < 10 ? "0" : "" ) + minute;
   }

   public String toString()
   {
      int hour, minute, second, temp;

      hour = totalSeconds / 3600;
      temp = totalSeconds % 3600;
      minute = temp / 60;
      second = temp % 60;

      return ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ) +
             ":" + ( minute < 10 ? "0" : "" ) + minute +
             ":" + ( second < 10 ? "0" : "" ) + second +
             ( hour < 12 ? " AM" : " PM" );
   }
}

// Exercise 8.18 Solution
// TimeTest.java
// Class TimeTest to exercise class Time
import javax.swing.*;

public class TimeTest {
   public static void main( String args[] )
   {
      Time1 t = new Time1();
      String result = "";

      result += "The initial military time is: " +
                    t.toMilitaryString();
      result += "\nThe initial standard time is: " +
                    t.toString();

      t.setTime( 13, 27, 6 );
      result += "\nMilitary time after setTime is: " +
                    t.toMilitaryString();
      result += "\nStandard time after setTime is: " +
                    t.toString();

      t.setTime( 99, 99, 99 );
      result += "\nAfter attempting invalid settings:";
      result += "\nMilitary time: " + t.toMilitaryString();
      result += "\nStandard time: " + t.toString();
 
      JOptionPane.showMessageDialog(
            null, result, "Time1Test",
            JOptionPane.INFORMATION_MESSAGE );     
      System.exit( 0 );
   }
}