Back to the Program-A-Day homepage
Problem
We need an adding machine! Your goal: Allow the cashier to enter prices. When done with one customer, entering a blank number prints the total the customer owes. Typing 'done' will exit the program.
|
|
Getting Started
|
Solution
Simple as pie really. You should already know about JOptionPane wonders for entering data, you just need to convert that text to numbers, and add them. An initial loop should be your starting point where numbers are asked and the running total is printed. That's your loop for an individual customer. If nothing is submitted, that's your clue they want to exit the loop.
The next step is to introduce an outer loop so we can deal with more than one customer per program run. Zeroing counts and printing the final total should be a cakewalk for a superstar programmer such as yourself.
|
Code
Solution Code
// Put this in a file named SuperMarket.java
import javax.swing.JOptionPane;
class SuperMarket
{
public static void main(String args[])
{
String input = "";
double totalPrice = 0;
double currentPrice = 0;
input = JOptionPane.showInputDialog("Price for item:");
while (!input.equals("done")) // Loop until user inputs 'done'
{
while (input.length() > 0) // Loop until user enters blank data
{
// Convert it to a number (no error checking!)
currentPrice = Float.parseFloat(input);
// Throw that price into the total
totalPrice += currentPrice;
// Get yo'self some more input
input = JOptionPane.showInputDialog("Price for item");
}
// Give some output
JOptionPane.showMessageDialog(null, "Their total is " + totalPrice);
// We don't need our total anymore
totalPrice = 0;
// Ask for more input
input = JOptionPane.showInputDialog("Price for item:");
}
JOptionPane.showMessageDialog(null, "Thank you. Have a great day!");
}
}
|
Back to the Program-A-Day homepage