RHS -> Allan-> SWC -> Exercises -> Stamp

Stamp

The problem
You are to develop a program, which can find the price for a stamp for a letter depending on the letters weight.
The table below shows the relation between letters weight and stamp price

     
Letter
   

Stamp price

 
0 g
<
weight
<=
50 g
4.50 DKK
 
50 g
<
weight
<=
100 g
6.50 DKK
 
100 g
<
weight
<=
250 g
12.50 DKK
 
250 g
<
weight
<=
500 g
21.00 DKK
 
500 g
<
weight
<=
1000 g
29.00 DKK
 
1000 g
<
weight
42.00 DKK


The solution

Create a project "Stamp" and create a new "Java class" and give it the name StampCalculator - uncheck the "Create Main Class" as we will create the application class later.

Declare a method in StampCalculator using the template below:

public double getPrice(int weight) {
        .....
}

Construct the code so it returns the price relevant for the given weight using the table above - you'll need a lot of nested if-else statements!
Compile it.


Testing the calculator

Now add a new file, choose "Java GUI Forms -> JFrame Form" - give it the name StampTestForm

Place a JPanel on the form and add a label and a text-field for entering the weight value, a label for showing the output (the price of the stamp) and a button to activate the action.
Your form should look something like:

     

Important: Add a instance variable of the StampCalculator type in the form-class (at the bottom of the file as usual) - remember to construct the object!

Now add code to the buttons action-event handler so a click will read the value from the text-field, typecast it to numerical (use Integer.parseInt()) and activates the getPrice() method in the StampCalculator object using the numerical value as argument.

The return value from this method should be put into the output-label.
Below is an example of this:

     


Adapting the StampCalculator

In your study-group discuss the following:

Change the method getPrice() into static and do the necessary changes in StampTestForm


Maintained by: Allan Helboe
Updated: 28 November, 2007 15:57