Chapter 64 Programming Exercises


Exercise 1 — Ideal Weight Calculator with a Slider

Write the ideal weight calculator so that height in inches is entered by using a slider. Use the approximate formula:

W = H2 / 30 , for female

W = H2 / 28 , for male
where W is the ideal weight in pounds, H is the height in inches

Set an action command for each radio button using setActionCommand(String) just as for push buttons. Add an action listener for each button using addActionListener(). Add a change listener for the slider using addChangeListener(). The ideal weight should be displayed in a text field when the user changes either a radio button or the slider.

Pick initial settings for the buttons and slider. When the program starts up display the ideal weight for those settings.


Click here to go back to the main menu.


Exercise 2 — Cookie Calculator

Rewrite the program from chapter 13 that decides it the user should buy cookies.

import java.util.Scanner ;
class CookieDecision
{
  public static void main (String[] args) 
  {
    Scanner scan = new Scanner( System.in );
    int hunger, look, smell ;

    System.out.print("How hungry are you?            (1-10): ");
    hunger = scan.nextInt();

    System.out.print("How nice do the cookies look?  (1-10): ");
    look   = scan.nextInt();

    System.out.print("How nice do the cookies smell? (1-10): ");
    smell  = scan.nextInt();

    if ( (hunger + look + smell ) > 15 )
      System.out.println("Buy cookies!"  );
    else
      System.out.println("Don't buy cookies.");
  }
}

Instead of prompting the user and scanning input, use three sliders with ranges 1 through 10. Write the output to a JTextField.

Click here to go back to the main menu.


Exercise 3 — Cricket Temperature Calculator

The snowy tree cricket chirps faster the hotter it gets. In the eastern United States, the temperature in Fahrenheit can be estimated by adding 40 to the number of chirps in 13 seconds. In the west, add 38 to the number of chirps in 12.5 seconds.

Click Here for a site that has cricket songs.

Write a program that uses a slider for the number of chirps and two radio buttons to select east or west. Assume that the number of chirps can be zero to sixty. Use the slider method:

public void setValue(int n)

to display the temperature as the setting of a second slider. Label the two sliders approriately.

Click here to go back to the main menu.