Chapter 3: Using Classes and Objects (2)

Lab Exercises

 

Topics                                     Lab Exercises

Enumerated Types                               Playing with Cards (required)

 

Panels                                                    Nested Panels (required)

 

Wrapper Classes                                  Experimenting with the Integer Class (extra credit)

 

Formatting Classes                              Formatting Output (extra credit)

 

 


Playing With Cards

 

Write a class that defines an enumerated type named Rank with values ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king. The main method

should do the following:

 

  1. Declare variables highCard, faceCard, card1, and card2 of type Rank.

 

  1. Assign highCard to be an ace, faceCard to be a jack, queen or king (your choice), and card1 and card2 to be two different numbered cards (two through ten - your choice).

 

  1. Print a line, using the highCard and faceCard objects, in the following format:

 

A blackjack hand: ace and .....

 

The faceCard variable should be printed instead of the dots.

 

  1. Declare two variables card1Val and card2Val of type int and assign them the face value of your card1 and card2 objects. Use your card1 and card2 variables and the ordinal method associated with enumerated types. Remember that the face value of two is 2, three is 3, and so on so you need to make a slight adjustment to the ordinal value of the enumerated type.

 

  1. Print two lines, using the card1 and card2 objects and the name method, as follows:

 

           A two card hand:   (print card1 and card2)

           Hand value:  (print the sum of the face values of the two cards)


 Nested Panels

 

The program NestedPanels.java is from Listing 3.8 of the text. Save the program to your directory and do the following:

 

  1. Compile and run the program. Experiment with resizing the frame and observe the effect on the components.
  2. Modify the program by adding a third subpanel that is twice as wide, but the same height, as the other two subpanels. Choose your own label and color for the subpanel (the color should not be red, green, or blue). Add the panel to the primary panel after the other two panels.
  3. Compile and run the modified program. Again, experiment with resizing the frame and observe the effect on the components.
  4. Now add a statement to the program to set the preferred size of the primary panel to 320 by 260. (What would be the purpose of this?). Compile and run the program to see if anything changed.
  5. Now add another panel with background color blue and size 320 by 20. Add a "My Panels" label to this panel and then add this panel to the primary panel before adding the other panels. Compile and run the program. What was the effect of this panel?

 

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

//  NestedPanels.java       Author: Lewis/Loftus

//

//  Demonstrates a basic component hierarchy.

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

import java.awt.*;

import javax.swing.*;

 

public class NestedPanels

{

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

   //  Presents two colored panels nested within a third.

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

   public static void main (String[] args)

   {

      JFrame frame = new JFrame ("Nested Panels");

      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

 

      // Set up first subpanel

      JPanel subPanel1 = new JPanel();

      subPanel1.setPreferredSize (new Dimension(150, 100));

      subPanel1.setBackground (Color.green);

      JLabel label1 = new JLabel ("One");

      subPanel1.add (label1);

 

      // Set up second subpanel

      JPanel subPanel2 = new JPanel();

      subPanel2.setPreferredSize (new Dimension(150, 100));

      subPanel2.setBackground (Color.red);

      JLabel label2 = new JLabel ("Two");

      subPanel2.add (label2);

 

      // Set up primary panel

      JPanel primary = new JPanel();

      primary.setBackground (Color.blue);

      primary.add (subPanel1);

      primary.add (subPanel2);

 

      frame.getContentPane().add(primary);

      frame.pack();

      frame.setVisible(true);

   }

}

Formatting Output

 

File Deli.java contains a partial program that computes the cost of buying an item at the deli. Save the program to your directory and do the following:

 

  1. Study the program to understand what it does.

 

  1. Add the import statements to import the DecimalFormat and NumberFormat classes.

 

  1. Add the statement to declare money to be a NumberFormat object as specified in the comment.

 

  1. Add the statement to declare fmt to be a DecimalFormat object as specified in the comment.

 

  1. Add the statements to print a label in the following format (the numbers in the example output are correct for input of $4.25 per pound and 41 ounces). Use the formatting object money to print the unit price and total price and the formatting object fmt to print the weight to 2 decimal places.

 

      *****  CS Deli  *****

     

     Unit Price: $4.25 per pound

     Weight: 2.56 pounds

     

     TOTAL:  $10.89

 


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

// DeliFormat.java

//

// Computes the price of a deli item given the weight

// (in ounces) and price per pound -- prints a label,

// nicely formatted, for the item.

//

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

 

import java.util.Scanner;

 

public class Deli

{

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

    //  main reads in the price per pound of a deli item

    //  and number of ounces of a deli item then computes

    //  the total price and prints a "label" for the item

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

 

    public static void main (String[] args)

    {

        final double OUNCES_PER_POUND = 16.0;

 

        double pricePerPound;  // price per pound

        double weightOunces;   // weight in ounces

        double weight;               // weight in pounds 

        double totalPrice;       // total price for the item

     

        Scanner scan = new Scanner(System.in);

 

        // Declare money as a NumberFormat object and use the

        // getCurrencyInstance method to assign it a value

 

 

        // Declare fmt as a DecimalFormat object and instantiate

        // it to format numbers with at least one digit to the left of the

        // decimal and the fractional part rounded to two digits.

 

 

        // prompt the user and read in each input

        System.out.println ("Welcome to the CS Deli!!\n ");

       

        System.out.print ("Enter the price per pound of your item: ");

        pricePerPound = scan.nextDouble();

 

        System.out.print ("Enter the weight (ounces): ");

        weightOunces = scan.nextDouble();

 

        // Convert ounces to pounds and compute the total price

        weight = weightOunces / OUNCES_PER_POUND;

        totalPrice = pricePerPound * weight;

 

        // Print the label using the formatting objects

        // fmt for the weight in pounds and money for the prices

    }

}


Experimenting with the Integer Class

 

Wrapper classes are described on pages 138-140 of the text. They are Java classes that allow a value of a primitive type to be "wrapped up" into an object, which is sometimes a useful thing to do. They also often provide useful methods for manipulating the associated type. Wrapper classes exist for each of the primitive types: boolean, char, float, double, int, long, short, and byte.

 

Write a program IntWrapper that uses the constants and methods of the Integer class (page 140 for a short list, pages 819-820 for a complete list) to perform the following tasks. Be sure to clearly label your output and test your code for each task before proceding.

 

  1. Prompt for and read in an integer, then print the binary, octal and hexadecimal representations of that integer.

 

  1. Print the maximum and minimum possible Java integer values. Use the constants in the Integer class that hold these values -- don't type in the numbers themselves. Note that these constants are static (see the description on page 140 and the signature on page 819).

 

  1. Prompt the user to enter two decimal integers, one per line. Use the next method of the Scanner class to read each of them in. (The next method returns a String so you need to store the values read in String variables, which may seem strange.) Now convert the strings to ints (use the appropriate method of the Integer class to do this), add them together, and print the sum.