Select a Chapter: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Back to the Main Page
Chapter Four listings: 11 classes

class GameApp
{
     /** Play the basic game repeatedly until the user tires.  */

     public static void main (String[ ] args)  
     {    BasicGame game = new BasicGame();
          game.playManyGames();
          System.exit (0);
     }  //======================
}     


import javax.swing.JOptionPane;

class NameChange
{
     /** Ask the user for his/her first name, then for the last
      *  name, then print them out in the opposite order.  */

     public static void main (String[ ] args)
     {    JOptionPane.showMessageDialog (null,
                   "Illustrate the use of JOptionPane methods");
          String firstName = JOptionPane.showInputDialog 
                             ("What is your first name?");
          String lastName = JOptionPane.showInputDialog 
                             ("What is your last name?");
          JOptionPane.showMessageDialog (null, 
                   "Reversed it is " + lastName + ", " + firstName);
          System.exit (0);   // needed when using JOptionPane
     }  //======================
}     


import javax.swing.JOptionPane;

public class BasicGame extends Object
{
     private String itsSecretWord = "duck";
     private String itsUsersWord = "none";


     public void playManyGames()  
     {    do
          {    playOneGame();
          }while (JOptionPane.showConfirmDialog (null, "again?")
                         == JOptionPane.YES_OPTION);
     }  //======================


     public void playOneGame()  
     {    askUsersFirstChoice();
          while (shouldContinue())
          {    showUpdatedStatus();
               askUsersNextChoice();
          }
          showFinalStatus();
     }  //======================


     public void askUsersFirstChoice()  
     {    itsUsersWord = JOptionPane.showInputDialog
                         ("Guess the secret word:");
     }  //======================


     public void askUsersNextChoice()  
     {    askUsersFirstChoice(); // no need to write the coding again
     }  //======================


     public boolean shouldContinue()  
     {    return ! itsSecretWord.equals (itsUsersWord);
     }  //======================


     public void showUpdatedStatus()  
     {    JOptionPane.showMessageDialog (null,
                         "That was wrong.  Hint:  It quacks.");
     }  //======================


     public void showFinalStatus()  
     {    JOptionPane.showMessageDialog (null,
                         "That was right.  \nCongratulations.");
     }  //======================
}


public class Person extends Object
{    
     private String itsFirstName;
     private String itsLastName;


     public Person (String first, String last)    // constructor
     {    super();
          itsFirstName = first;
          itsLastName = last;
     }    //=======================


     /** Return the first name. */

     public String getFirstName()
     {    return itsFirstName;
     }    //=======================


     /** Return the last name. */

     public String getLastName()
     {    return itsLastName;
     }    //=======================
}


public class Patient extends Person     
{    
     private String itsDoctor;


     public Patient (String first, String last, String doc)
     {    super (first, last);
          itsDoctor = doc;
     }    //=======================
}


public class Time extends Object
{
     private int itsHour;    // always in the range 0 to 23
     private int itsMin;     // always in the range 0 to 59


     /** Create an object for the given hour and minute.  If min
      *  is negative, adjust the values to make 0 <= min < 60. */

     public Time (int hour, int min)            // constructor
     {    super();
          itsHour = hour;
          for (itsMin = min;  itsMin < 0;  itsMin = itsMin + 60)
               itsHour--;
     }    //=======================


     /** Return the time expressed in military time. */

     public String toString()
     {    if (itsHour < 10)
               return ("0" + itsHour) + itsMin;
          else
               return ("" + itsHour) + itsMin;
     }    //=======================


     /** Return the result of adding this Time to that Time. */

     public Time add (Time that)
     {    Time valueToReturn = new Time (this.itsHour + that.itsHour, 
                                         this.itsMin + that.itsMin);
          if (valueToReturn.itsMin >= 60)
          {    valueToReturn.itsMin = valueToReturn.itsMin - 60;
               valueToReturn.itsHour++;
          }
          valueToReturn.itsHour = valueToReturn.itsHour % 24;
          return valueToReturn;
     }    //=======================
}


import javax.swing.JOptionPane;
class TimeTester
{
     public static void main (String[] args)
     {    Time t1 = new Time (13, 25);
          Time t2 = new Time (8, -150);
          JOptionPane.showMessageDialog (null, "1 " + t1.toString());
          JOptionPane.showMessageDialog (null, "2 " + t2.toString());
          Time t3 = t1.add (t2);
          JOptionPane.showMessageDialog (null, "3 " + t3.toString());
          t1 = t2.add (t3);
          JOptionPane.showMessageDialog (null, "1 " + t1.toString());
          System.exit (0);   // needed when using JOptionPane
     }    //=======================
}


import javax.swing.JOptionPane;

public class GuessNumber extends BasicGame
{
     private java.util.Random randy;
     private int itsSecretNumber;  
     private int itsUsersNumber;


     public GuessNumber()
     {    super();
          randy = new java.util.Random(); 
     }    //=======================


     public void askUsersFirstChoice()
     {    itsSecretNumber = 1 + randy.nextInt (100);
          askUsersNextChoice();
     }    //=======================


     public void askUsersNextChoice()
     {    String s = JOptionPane.showInputDialog
                         ("Guess my number from 1 to 100:");
          if (s != null && ! s.equals (""))
               itsUsersNumber = Integer.parseInt (s);
          else
               itsUsersNumber = -1;  // just to have a value there
     }  //======================


     public boolean shouldContinue()  
     {    return itsUsersNumber != itsSecretNumber;
     }  //======================


     public void showUpdatedStatus()
     {    if (itsUsersNumber > itsSecretNumber)
               JOptionPane.showMessageDialog (null, "Too high");
          else
               JOptionPane.showMessageDialog (null, "Too low");
     }    //=======================

     // inherited from BasicGame:
     //    playManyGames
     //    playOneGame
     //    showFinalStatus
}


public class BigVic extends Looper
{
     private int itsNumFilled;     // count this's filled slots
     private int itsNumEmpty;      // count this's non-filled slots


     public BigVic()                       // constructor
     {    // left as an exercise
     }    //======================


     /** Tell how many of the executor's slots are filled. */

     public int getNumFilled()
     {    return itsNumFilled;
     }    //======================


     /** Tell how many of the executor's slots are empty. */

     public int getNumEmpty()
     {    return itsNumEmpty;
     }    //======================


     /** Do the original putCD(), but also update the counters. */

     public void putCD()
     {    if ( ! seesCD() && stackHasCD())
          {    itsNumFilled++;
               itsNumEmpty--; 
               super.putCD();
          }
     }    //======================


     /** Do the original takeCD(), but also update the counters.*/

     public void takeCD()
     {    if (seesCD())
          {    itsNumFilled--;
               itsNumEmpty++;
               super.takeCD();
          }
     }    //======================
}


import javax.swing.JOptionPane;

public class Nim extends BasicGame
{
     private java.util.Random randy = new java.util.Random();
     private int itsNumLeft;
     private int itsMaxToTake;


     public void askUsersFirstChoice()
     {    itsNumLeft = 20 + randy.nextInt (21);
          itsMaxToTake = 3 + randy.nextInt (3); 
          askUsersNextChoice();
     }    //=======================


     public void askUsersNextChoice()
     {    int choice = 0;
          do
          {    String s = JOptionPane.showInputDialog
                       (itsNumLeft + " left. Take 1 to " + itsMaxToTake);
               if (s != null && ! s.equals (""))
                    choice = Integer.parseInt (s);
          }while (choice < 1 || choice > itsMaxToTake);
          itsNumLeft = itsNumLeft - choice;
     }    //=======================


     public boolean shouldContinue()  
     {    return itsNumLeft > itsMaxToTake;
     }  //======================


     public void showFinalStatus()
     {    if (itsNumLeft == 0)
               super.showFinalStatus();
          else
               JOptionPane.showMessageDialog (null, "I take "
                       + itsNumLeft + " and so I win.");
     }    //=======================


     public void showUpdatedStatus()
     {    int move = itsNumLeft % (itsMaxToTake + 1);
          if (move == 0)
               move = 1 + randy.nextInt (itsMaxToTake);
          itsNumLeft = itsNumLeft - move;
          JOptionPane.showMessageDialog (null, "I take " + move
                     + ", leaving " + itsNumLeft);
     }    //=======================
}


import javax.swing.JOptionPane;
import java.util.Random;

public class Mastermind extends BasicGame
{
     private Random randy;
     private int itsFirst;    // 100's digit of secret number
     private int itsSec;      //  10's digit of secret number
     private int itsThird;    //   1's digit of secret number
     private int usersFirst;  // 100's digit of user's guess
     private int usersSec;    //  10's digit of user's guess
     private int usersThird;  //   1's digit of user's guess


     public Mastermind()
     {    super();
          randy = new Random();
     }    //=======================


     public void askUsersFirstChoice()
     {    itsFirst = randy.nextInt (10);
          itsSec   = randy.nextInt (10);
          itsThird = randy.nextInt (10);
          askUsersNextChoice();
     }    //=======================


     public void askUsersNextChoice()
     {    String s;
          do
          {    s = JOptionPane.showInputDialog
                         ("Enter a three-digit integer:");
          }while (s == null || s.equals (""));
          int guess = Integer.parseInt (s);
          usersThird = guess % 10;
          usersFirst = guess / 100;
          usersSec = (guess / 10) % 10;
     }    //=======================


     public boolean shouldContinue()
     {    return usersFirst != itsFirst || usersSec != itsSec
                                        || usersThird != itsThird;
     }    //=======================


     public void showUpdatedStatus()
     {    int numRight = 0;
          int numWrong = 0;

          if (usersFirst == itsFirst)
               numRight++;
          else if (usersFirst == itsSec || usersFirst == itsThird)
               numWrong++;

          if (usersSec == itsSec)
               numRight++;
          else if (usersSec == itsFirst || usersSec == itsThird)
               numWrong++;

          if (usersThird == itsThird)
               numRight++;
          else if (usersThird == itsSec || usersThird == itsFirst)
               numWrong++;

          JOptionPane.showMessageDialog (null, " You have "
                  + numRight + " in the right place and "
                    + numWrong + " in the wrong place.");
     }  //======================
}


// Compile the BabyFrame class at the end of this file before
// trying to compile these two classes.

import javax.swing.JLabel;

     /** Calculate the centigrade equivalent of any Fahrenheit
      *  temperature that the user enters in a textfield.  */

public class CentigradeFrame extends BabyFrame
{
     private Jlabel itsLabel = new JLabel ("none");               //1

     public CentigradeFrame (String title)
     {    super (title);                                         //2
          this.setSize (250, 110);    // width, height           //3
          this.add (new JLabel ("What is the Fahrenheit temp?"));//4
          this.add (new BabyField_1 (15));                       //5
          this.add (itsLabel);                                   //6
          this.setVisible (true);                                //7
     }    //======================

     /** React to ENTER in textfield #1. */

     public void fieldAction_1 (BabyField_1 source)
     {    int temp = Integer.parseInt (source.getText());        //8
          int centi = (temp - 32) * 5 / 9;                       //9
          itsLabel.setText ("In centigrade that is " + centi);   //10
     }    //======================
}  

   
class CentigradeMain
{
     public static void main (String[ ] args)
     {    new CentigradeFrame ("Simple event handler");         //11
     }    //======================
}     


// Compile the BabyFrame class at the end of this file before
// trying to compile these two classes.

public class NimFrame extends BabyFrame  // based on Listing 4.8
{
     private java.util.Random randy = new java.util.Random();
     private int itsNumLeft;
     private int itsMaxToTake;
     private javax.swing.JLabel itsPrompt
                   = new javax.swing.JLabel ("Take 1 to 00");
     private BabyTextArea itsOutput = new BabyTextArea (6, 42);

     public NimFrame (String title)
     {    super (title);
          setSize (500, 250);
          add (new BabyButton_1 ("start new game"));
          add (itsPrompt);
          add (new BabyField_1 (4));
          add (itsOutput);
          setVisible (true);  // otherwise the frame will not appear
          buttonAction_1(); // start the software by starting a game
     }    //======================

     /** Initialize 2 variables and wait for user's first choice. */

     public void buttonAction_1()
     {    itsNumLeft = 20 + randy.nextInt (21);
          itsMaxToTake = 3 + randy.nextInt (3); 
          itsOutput.say ("We start with " + itsNumLeft);
          itsPrompt.setText ("Take 1 to " + itsMaxToTake);
     }    //======================

     /** This method executes when the user types a number in the 
           textfield. If it is legal, the computer makes its move. */

     public void fieldAction_1 (BabyField_1 source)
     {    int choice = 0;
          String s = source.getText();
          if (s != null && ! s.equals (""))
               choice = Integer.parseInt (s);
          if (choice >= 1 && choice <= itsMaxToTake)
          {    itsNumLeft = itsNumLeft - choice;     
               if (shouldContinue())
                    showUpdatedStatus();
               else
                    showFinalStatus();
          }
     }    //======================

     // showUpdatedStatus, showFinalStatus, and shouldContinue
     // are the same as in Listing 4.8, except itsOutput.say
     // replaces JOptionPane.showMessageDialog.

     public boolean shouldContinue()  
     {    return itsNumLeft > itsMaxToTake;
     }    //======================

     public void showFinalStatus()
     {    if (itsNumLeft == 0)
               itsOutput.say ("That was right. \nCongratulations.");
          else
               itsOutput.say ("I take " + itsNumLeft + " and so I win.");
     }    //=======================

     public void showUpdatedStatus()
     {    int move = itsNumLeft % (itsMaxToTake + 1);
          if (move == 0)
               move = 1 + randy.nextInt (itsMaxToTake);
          itsNumLeft = itsNumLeft - move;
          itsOutput.say ("I take " + move 
                           + ", leaving " + itsNumLeft);
     }    //=======================
}
   
class NimMain
{
     public static void main (String[ ] args)
     {    new NimFrame ("The Game of Nim");
     }    //======================
}     



// This class is not to be studied until after you study Chapter 9.
// Simply compile it before compiling any class that uses it.

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/** 1. How do you make an inner class? Just put it inside another class; 
      its heading can begin with either "public class" or "private class".
    2. What do you lose? You cannot have class methods or class 
      variables in the inner class. 
    3. What do you gain? The inner class can access private variables 
      and methods of the outer class. */

public class BabyFrame extends JFrame
{
     private boolean isMainFrame;

     /** Create a JFrame with the given title; use FlowLayout.  */

     public BabyFrame (String title)
     {    super (title);
          getContentPane().setLayout (new java.awt.FlowLayout());  // ##
          isMainFrame = true;
          addWindowListener (new Closer());
          setVisible (true);
     }

     /* Note:  An instructor may wish to modify this class to allow students
       to create applets in the same vein.  Do the following and recompile:
       1. Replace "JFrame" by "javax.swing.JApplet" in the class heading.
       2. Delete the BabyFrame constructor above, and the one at the end.
       3. Tell students their subclasses should use init(), not constructors.
          Their first init() statement should be the one marked ## above. */

     public java.awt.Component add (java.awt.Component given)
     {    this.getContentPane().add (given);
          return given;
     }

     private class Closer extends java.awt.event.WindowAdapter
     {
          public void windowClosing (java.awt.event.WindowEvent e)
          {    if (isMainFrame)
                    System.exit (0);
               else
                    setVisible (false);
          }
     }

     /** Create a JScrollPane containing a JTextArea.  It will display
          a given message on a line by itself. */

     public class BabyTextArea extends JScrollPane
     {
          private JTextArea itsArea;

          public BabyTextArea (int rows, int columns)
          {    super();
               itsArea = new JTextArea (rows, columns);
               // the following is required because we cannot
               // create the area and then say super(itsArea)
               this.setViewportView (itsArea);
          }

          /** Show the message in the scrolled text area. */

          public void say (String message)
          {    itsArea.append (message + "\n");
          }    //======================
     }     

     /** Create a JButton with the given title.  It is its own listener.
          It will call the void buttonAction_N method when clicked. */

     public class BabyButton_1 extends JButton implements ActionListener
     {
          public BabyButton_1 (String title)
          {    super (title);  // sets the label on the button
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    buttonAction_1();
          }
     }

     public void buttonAction_1()  // to be overridden
     {  }

     /** Create a JTextField with the given width (in characters, roughly).
          It is its own listener.  It will call the void fieldAction_N
          method when ENTER is pressed, passing itself as a parameter. */

     public class BabyField_1 extends JTextField implements ActionListener
     {
          public BabyField_1 (int textSize)
          {    super (textSize);  // sets the text in the textfield
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    fieldAction_1 ((BabyField_1) ev.getSource());
          }
     }

     public void fieldAction_1 (BabyField_1 source)  // to be overridden
     {  }


     public class BabyButton_2 extends JButton implements ActionListener
     {
          public BabyButton_2 (String title)
          {    super (title);  // sets the label on the button
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    buttonAction_2();
          }
     }

     public void buttonAction_2()  // to be overridden
     {  }



     public class BabyField_2 extends JTextField implements ActionListener
     {
          public BabyField_2 (int textSize)
          {    super (textSize);  // sets the text in the textfield
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    fieldAction_2 ((BabyField_2) ev.getSource());
          }
     }

     public void fieldAction_2 (BabyField_2 source)  // to be overridden
     {  }



     public class BabyButton_3 extends JButton implements ActionListener
     {
          public BabyButton_3 (String title)
          {    super (title);  // sets the label on the button
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }


          public void actionPerformed (ActionEvent ev)
          {    buttonAction_3();
          }
     }

     public void buttonAction_3()  // to be overridden
     {  }




     public class BabyField_3 extends JTextField implements ActionListener
     {
          public BabyField_3 (int textSize)
          {    super (textSize);  // sets the text in the textfield
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    fieldAction_3 ((BabyField_3) ev.getSource());
          }
     }


     public void fieldAction_3 (BabyField_3 source)  // to be overridden
     {  }



     public class BabyButton_4 extends JButton implements ActionListener
     {
          public BabyButton_4 (String title)
          {    super (title);  // sets the label on the button
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    buttonAction_4();
          }
     }

     public void buttonAction_4()  // to be overridden
     {  }



     public class BabyField_4 extends JTextField implements ActionListener
     {
          public BabyField_4 (int textSize)
          {    super (textSize);  // sets the text in the textfield
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    fieldAction_4 ((BabyField_4) ev.getSource());
          }
     }

     public void fieldAction_4 (BabyField_4 source)  // to be overridden
     {  }





     public class BabyButton_5 extends JButton implements ActionListener
     {
          public BabyButton_5 (String title)
          {    super (title);  // sets the label on the button
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    buttonAction_5();
          }
     }

     public void buttonAction_5()  // to be overridden
     {  }



     public class BabyButton_6 extends JButton implements ActionListener
     {
          public BabyButton_6 (String title)
          {    super (title);  // sets the label on the button
                this.addActionListener (this);  // connects to
                    // the following actionPerformed method
          }

          public void actionPerformed (ActionEvent ev)
          {    buttonAction_6();
          }
     }

     public void buttonAction_6()  // to be overridden
     {  }



     /** Create a JFrame with the given title; use FlowLayout.  
          The second parameter should be true if this is the main frame of 
          the application; it should be false if it is a "sub-frame." */

     public BabyFrame (String title, boolean isMain)
     {    super (title);
          getContentPane().setLayout (new java.awt.FlowLayout());  // ##
          isMainFrame = isMain;
          addWindowListener (new Closer());
          setVisible (true);
     }


     public JButton newButton (String label, ActionListener alis)
     {    JButton but = new JButton (label);
          but.addActionListener (alis);
          return but;
     }
}

All information Copyright (c)1999 - Dr. William C. Jones, Jr.
Layout and Design Copyright © Psumonix, LLC. All Rights Reserved.