Chapter 4: Writing Classes

Lab Exercises

 

Topics                         Lab Exercises

Classes and methods          Representing Names (submit)

Drawing Squares (submit)

 

GUIs: Buttons and               Voting with Buttons (submit)

Textfields                               Calculating Body Mass Index (extra credit)


 Representing Names

 

1.     Write a class Name that stores a person's first, middle, and last names and provides the following methods:

·       public Name(String first, String middle, String last)—constructor. The name should be stored in the case given; don't convert to all upper or lower case.

·       public String getFirst()—returns the first name

·       public String getMiddle()—returns the middle name

·       public String getLast()—returns the last name

·       public String firstMiddleLast()—returns a string containing the person's full name in order, e.g., "Mary Jane Smith".

·       public String lastFirstMiddle()—returns a string containing the person's full name with the last name first followed by a comma, e.g., "Smith, Mary Jane".

·       public boolean equals(Name otherName)—returns true if this name is the same as otherName. Comparisons should not be case sensitive. (Hint: There is a String method equalsIgnoreCase that is just like the String method equals except it does not consider case in doing its comparison.)

·       public String initials()—returns the person's initials (a 3-character string). The initials should be all in upper case, regardless of what case the name was entered in. (Hint: Instead of using charAt, use the substring method of String to get a string containing only the first letter—then you can upcase this one-letter string. See Figure 3.1 in the text for a description of the substring method.)

·       public int length()—returns the total number of characters in the full name, not including spaces.

 

2.     Now write a program TestNames.java that prompts for and reads in two names from the user (you'll need first, middle, and last for each), creates a Name object for each, and uses the methods of the Name class to do the following:

a.     For each name, print

·       first-middle-last version

·       last-first-middle version

·       initials

·       length

b.     Tell whether or not the names are the same.

 


Drawing Squares

 

1.     Write a class Square that represents a square to be drawn. Store the following information in instance variables:

·       size (length of any side)

·       x coord of upper left-hand corner

·       y coord of upper left-hand corner

·       color

 

Provide the following methods:

·       A parameterless constructor that generates random values for the size, color, x, and y. Make the size between 100 and 200, x between 0 and 600, y between 0 and 400. The squares can be any color—note that you can pass a single int parameter to the Color constructor, but it will only consider the first 24 bits (8 bits for each of R, G, B component).

 

·       IMPORTANT: Your random number generator must be declared at the class level (not inside the constructor), and must be declared static. So its declaration and initialization should appear with the declarations of size, color, x, and y, and should look like this:

 

private static Random generator = new Random();

 

·       A draw method that draws the square at its x,y coordinate in its color. Note that you need a Graphics object, like the page parameter of the paint method, to draw.Your draw method should take a Graphics object as a parameter.

 

2.     Now write an applet DrawSquares that uses your Square class to create and draw 5 squares. This code should be very simple; the paint method will simply create a Square and then draw it, repeated 5 times.  Don't forget to pass the Graphics object to draw.


 

Voting with Buttons

 

Files VoteCounter.java and VoteCounterPanel.java contain slightly modified versions of PushCounter.java and PushCounterPanel.java in listings 4.10 and 4.11 of the text. As in the text the program counts the number of times the button is pushed; however, it assumes ("pretends") each push is a vote for Joe so the button and variables have been renamed appropriately.

 

1.     Compile the program, then run it to see how it works.

 

2.     Modify the program so that there are two candidates to vote for—Joe and Sam. To do this you need to do the following:

a.     Add variables for Sam—a vote counter, a button, and a label.

b.     Add a new inner class named SamButtonListener to listen for clicks on the button for Sam. Instantiate an instance of the class when adding the ActionListener to the button for Sam.

c.     Add the button and label for Sam to the panel.

 

3.     Compile and run the program.

 


 

 

//*********************************************************
// VoteCounter.java
//
// Demonstrates a graphical user interface and event listeners to
// tally votes for two candidates, Joe and Sam.
//*********************************************************
import javax.swing.JFrame;
 
public class VoteCounter
{
    //----------------------------------------------
    // Creates the main program frame.
    //----------------------------------------------
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Vote Counter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        frame.getContentPane().add(new VoteCounterPanel());
        
        frame.pack();
        frame.setVisible(true);
    }
}
 

 

//*********************************************************
// VoteCounterPanel.java  
//
// Demonstrates a graphical user interface and event listeners to
// tally votes for two candidates, Joe and Sam.
//*********************************************************
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class VoteCounterPanel extends JPanel
{
    private int votesForJoe;
    private JButton joe;
    private JLabel labelJoe;
 
    //----------------------------------------------
    // Constructor: Sets up the GUI.
    //----------------------------------------------
    public VoteCounterPanel()
    {
        votesForJoe = 0;
 
        joe = new JButton("Vote for Joe");
        joe.addActionListener(new JoeButtonListener());
 
        labelJoe = new JLabel("Votes for Joe: " + votesForJoe);
 
        add(joe);
        add(labelJoe);
 
        setPreferredSize(new Dimension(300, 40));
        setBackground(Color.cyan);
    }
 
    //***************************************************
    // Represents a listener for button push (action) events
    //***************************************************
    private class JoeButtonListener implements ActionListener
    {
        //----------------------------------------------
        // Updates the counter and label when Vote for Joe 
        // button is pushed
        //----------------------------------------------
        public void actionPerformed(ActionEvent event)
        {
            votesForJoe++;
            labelJoe.setText("Votes for Joe: " + votesForJoe);
        }
    }
}
 
 

Calculating Body Mass Index

 

Body Mass Index (BMI) is measure of weight that takes height into account. Generally, a BMI above 25 is considered high, that is, likely to indicate that an individual is overweight. BMI is calculated as follows for both men and women:

 

(703 * height in inches) / (weight in pounds)2

 

Files BMI.java and BMIPanel.java contain skeletons for a program that uses a GUI to let the user compute their BMI.  This is similar to the Fahrenheit program in listings 4.12 and 4.13 of the text. Fill in the code as indicated by the comments and compile and run this program; you should see the BMI calculator displayed.

 

 

 

 

 

//********************************************************************

//  BMI.java  

//

//  Sets up a GUI to calculate body mass index.

//********************************************************************

 

import javax.swing.JFrame;

public class BMI

{

   //-----------------------------------------------------------------

   //  Creates and displays the BMI GUI.

   //-----------------------------------------------------------------

   public static void main (String[] args)

   {

 

       JFrame frame = new JFrame("BMI");

       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

       BMIPanel panel = new BMIPanel();

 

       frame.getContentPane().add(panel);

       frame.pack();

       frame.setVisible(true);

 

   }

}

 

 

 

//********************************************************************

//  BMIPanel.java     
//
//  Computes body mass index in a GUI.
//********************************************************************
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class BMIPanel extends JPanel
{
   private int WIDTH = 300;
   private int HEIGHT = 120;
 
   private JLabel heightLabel, weightLabel, BMILabel, resultLabel;
   private JTextField height, weight;
   private JButton calculate;
 
   //-----------------------------------------------------------------
   //  Sets up the GUI.
   //-----------------------------------------------------------------
   public BMIPanel()
   {
 
      //create labels for the height and weight textfields 
      heightLabel = new JLabel ("Your height in inches: ");
      weightLabel = new JLabel ("Your weight in pounds: ");
 
      //create a "this is your BMI" label
      //create a result label to hold the BMI value
 
      //create a JTextField to hold the person's height in inches
      //create a JTextField to hold the person's weight in pounds
 
      //create a button to press to calculate BMI
      //create a BMIListener and make it listen for the button to be pressed
 
 
      //add the height label and height textfield to the panel
      //add the weight label and weight textfield to the panel
      //add the button to the panel
      //add the BMI label to the panel
      //add the label that holds the result to the panel
 
      //set the size of the panel to the WIDTH and HEIGHT constants
      //set the color of the panel to whatever you choose
   }
 
   //*****************************************************************
   //  Represents an action listener for the calculate button.
   //*****************************************************************
   private class BMIListener implements ActionListener
   {
      //--------------------------------------------------------------
      //  Compute the BMI when the button is pressed
      //--------------------------------------------------------------
      public void actionPerformed (ActionEvent event)
      {
         String heightText, weightText;
         int heightVal, weightVal;
         double bmi;
 
         //get the text from the height and weight textfields
 
         //Use Integer.parseInt to convert the text to integer values
 
         //Calculate the bmi = 703 * weight in pounds / (height in inches)^2
 
         //Put result in result label.  Use Double.toString to convert double to string.
 
      }
   }
}