Difference between revisions of "Calculating Area"
Line 24: | Line 24: | ||
int area; | int area; | ||
double totalCost; | double totalCost; | ||
+ | </pre> | ||
+ | Now the length and width must be read in. Input dialog boxes can be used to prompt the user for the values. The inputs are read in as strings, then parsed to integers before they can be stored as integer variables. Use the Integer.parseInt() function for this. | ||
+ | <pre> | ||
+ | input = JOptionPane.showInputDialog("Input length:"); | ||
+ | length = Integer.parseInt(input); | ||
+ | |||
+ | input = JOptionPane.showInputDialog("Input width:"); | ||
+ | width = Integer.parseInt(input); | ||
</pre> | </pre> | ||
Revision as of 21:45, 1 April 2010
Back to the Program-A-Day homepage
ProblemIt's time to replace the carpet in your living room, but how much will it cost? The carpet you want costs $8 per square foot plus an installation fee of $500. Your roommate has agreed to pay half, and you have a coupon for $50 off the total cost. Write a program that accepts the length and width (as integers) of a room. Calculate the total cost (as a double) of carpeting by multiplying the square footage by the price per square foot, plus installation. Your program will print total square footage, total cost, and your cost. |
SideSectionTitle
An image or By Students section | |
---|---|---|
SolutionStart off by initializing variables. You will need a string to store user input, along with some integers. Create these variables and set the integers to the values given in the problem. Named constants should normally be used here, these will be explained next week. String input; int costPSF = 8; // Cost of $8 per square foot int installFee = 500; // $500 installation fee int coupon = 50; // $50 off coupon You will also need variables to store the length and width input by the user, the calculated area, and the total cost. Remember that total cost is to be stored as a double (as cost may include dollars and cents). int length; int width; int area; double totalCost; Now the length and width must be read in. Input dialog boxes can be used to prompt the user for the values. The inputs are read in as strings, then parsed to integers before they can be stored as integer variables. Use the Integer.parseInt() function for this. input = JOptionPane.showInputDialog("Input length:"); length = Integer.parseInt(input); input = JOptionPane.showInputDialog("Input width:"); width = Integer.parseInt(input); | ||
Code |