Assignment 3 - Primitive Types
Use Java's primitive types to discover the true cost of those easy monthly payments.
How much is that "doggie" in the window, really? When it comes to buying "on time", sometimes it's really hard to get the information you need.
Suppose you want to buy a new $3,500 computer system. Should you use your credit card, or finance it through the store? How much will your monthly payments be? How much lower will your payments be if you finance it over 3 years instead of 2?
Here's a Java applet that can give you some answers.
In this homework, you'll build an applet that uses primitive types. This assignment is a little larger than the applet you built last week. Rather than trying to build it in one big piece, you'll have to carefully work through each of the steps, one at a time.
Before you start this you should know:
- How to enter, compile, and run a Java applet. This includes writing the source code, compiling with javac [or jikes], building an HTML file to hold your applet and running the applet inside appletviewer and inside your Web browser.
- How to post your .class files on your Web site, along with the necessary HTML file and the correct links.
- How to write a simple applet that uses Label objects.
You should also know:
- How and where to put the import statements.
- Which import statements you need to use.
- The basic structure of a class as well as the relationship between the name of the class and file that contains the class.
- How to create attributes and where to put them.
- How to end each line of code.
- How to write the init() method.
- How to send a message to an object
This homework assumes you already know how to do these tasks, and it does not focus on them. Instead, it covers the material from Lesson 3. You should have at read through the material at least once before getting started, otherwise, you'll find yourself wasting a lot of effort.
To successfully complete the homework, you must understand how to:
- Create and add TextField objects to your applet.
- Create and add Buttons to your applet.
- Extract a String from a TextField object.
- Insert text into a TextField object.
- Create int, double, and String variables, as required.
- Write Java expressions involving basic numeric operators and operands.
- Respond to ActionEvents generated when a Button is clicked.
Step-By-Step Instructions
Begin by downloading the Assignment 3 starter file, HowMuch.java. Use the code it contains to get started, then add each of the pieces requested below.
Step 1
Identify yourself. Make sure you enter your personal information to the top of your source code. Add your name, your class, your Java ID number [1036-100], and a brief description of the program. Every program you write should include this information.
Step 2
Import the required packages. Add the necessary import statments to ensure that you can use Buttons and Labels, as well as the import statement necessary to respond to events, and the import statement necessary to format numeric output. [You'll have to read the lesson on "Numeric Output" to find out what goes here. This information is not in your book.] Don't forget to add the import statement required to extend the Applet class.
Step 3
Define your applet's fields. Add the necessary TextField, Button, and Label object attributes to your class.
- You'll need a separate TextField for the user to enter the borrowed amount; another where the user can enter the yearly interest rate, and a third where the user can enter the number of years to finance the purchase.
Hint: I usually name my user-interface fields with a trailing identifier that identifies the kind of object it is. In this case, for instance, I'd give the purchase amount object the name, amountTF, where the TF stands for TextField.
- You'll need two Label fields to display the output from your program. One Label will display the monthly payment [paymentLbl ], and one Label will display the total cost of your purchase, including interest.
- You'll need one Button field. When the user of your applet presses the Button, you'll retrieve the values they've entered into the TextFields, calculate the payment and total cost for the purchase, and display the nicely formatted data in your two Label fields.
Step 4
Initialize your applet. Inside your init() method, you must add each of your object attributes to the surface of the applet, so that the user can see them and interact with them. You also should create some additional Label objects to identify each of the input and ouput components.
Let's add the components, and their Labels, one by one:
- Inside the init() method, create a local Label object variable that contains the text "Amount Borrowed". Make sure the Label is aligned to the right. [This requires you to use a 2-argument Label constructor. See the Java documentation for the Label class if you don't know how.]
- Add the descriptive Label to the applet, using the add() method. On the following line, add the amount borrowed text field to the applet as well.
- Repeat the same steps--create a local, descriptive Label and then add the Label field and its associated component to the applet--for each of the remaining fields. You can see the suggested text for each component by examining the applet at the top of this page.
- Finally, add your Button object to the applet, after all of the other components have been added.
Step 5
Hook up the event system. Even though your applet has a Button, the Button won't notify your applet when it is clicked, unless you tell it to. Here's how:
- You "activate" your Button object by sending it the addActionListener() message, and passing along the name this as an argument. (You are, in effect, telling your Button object to notify your applet [this ] when it is clicked.) This code must go inside the init() method. Put it after the line that adds the Button to the applet.
- Button objects are only willing to send event notifications to "specially marked" applets. To tell Java that your applet is willing and able to accept such notification, add the phrase implements ActionListener to the end of your applet's class header.
Step 6
Get input from the user. Once activated, your applet's button will look for a method named actionPerformed() whenever it is clicked. Every applet that implements ActionListener must include a method named actionPerformed() to handle those requests. I've added a skeletal actionPerformed() method for you. All you have to do is write the code to fill it in.
Inside the actionPerformed() method, you have to calculate the cost of your loan. The first step in calculating the cost of a loan is to retrieve the information about the amount borrowed, the yearly interest rate, and the term of the loan.
Here's how you do that: [Add this code inside the actionPerformed() method.]
- Create three local String variables, one to hold the text stored in each of your TextField objects.
- Send each TextField object a getText() message. When it receives that message, it will return the text that it contains. Save the text returned by getText() in your String variables by using the assignment operator.
Step 7
Convert the input. The input entered by the user is in textual form. Before you can do calculations, however, you need to convert it to binary form. Because the HowMuch applet deals with fractional numbers, you should convert each entry to a double value.
Here are the steps required to convert a String like "123.45" into a floating point double value. For more in-depth information, make sure you read Lesson 3.5, "Getting Numeric Input".
- Create a local Double object for each of the String variables extracted in Step 5. Construct your Double objects by passing each String to the appropriate constructor, like this:
Double amountDbl = new Double(amountStr);
where amountStr is one of the String variables initialized in Step 5. [Note that a Double variable is different than a double [little d] variable. A Double variable is an object, but it can't be used for arithmetic. A double variable is a primitive value.]
- Create a primitive double local variable to match each of the Double objects created in the previous step. Initialize your double variables by sending your Double objects the doubleValue() message, like this:
double amount = amountDbl.doubleValue();
Step 8
Perform the calculations. Now that you've retreived the information from the user, you'll need to manipulate that information to calculate the answers required by the problem.
Here's what you need to know to perform your calculations:
The formula to calculate a payment, when the loan amount, interest rate, and term are all known is:
loan amount x interest rate
payment = ____________________________________
1 - (1 / (1 + interest rate))term * 12
When you perform your calculations, you can use two of the numbers you obtained in the previous step--loan amount and loan term--without any further processing.
You need to modify the interest rate variable, however, before you can use it, because the user expects a monthly rate, and the user entered a yearly rate. In addition, the rate entered by the user needs to be converted to a decimal percentage.
Here's what you need to do:
- Since the user entered the interest rate as 7.5, rather than .075, the first step is to divide the interest rate by 100, and store the result back in the interest rate variable. This is the actual yearly interest rate.
- The formula above, however, requires a monthly interest rate, not a yearly one. Divide the interest rate calculated in the previous step, this time by 12, and store the result back in your interest rate variable.
Once the interest rate is squared away, create a new double variable called payment, plug the rest of the variables into the formula shown above, and store the result in payment. Since Java doesn't have an exponentiation operator, you'll have to use the Math.pow() method to calculate the "bottom" part of the interest calculation like this:
(1 - (Math.pow(1/(1+rate), term * 12)))
Step 9
Display the output. To display the output send the setText() message to the Label objects you created in Step 3. One complication is that you have to convert your new binary answers back into Strings before they can be displayed.
Here's a summary of how to do that. For more information, look at Lesson 3.6, "Numeric Formatting".
- Create a new local NumberFormat object using the getCurrencyInstance() method.
- Send your NumberFormat object the format() message. Pass the number you want formatted as an argument.
- Save the formatted String obtained by calling the format() method, and pass it to the appropriate setText() method.
Format the payment variable [computed in Step 8] for the first output label. For the total cost label, simply multiply the monthly payment by 12 and then multiply the result by the term to find the total cost.
Finishing Up
Post your applet. Once you've tested your applet locally, add it to the Assignment 3 HTML file on your Web site.
|