Question
Add a running total as you add items to the list for this program: import java.text.DecimalFormat; import java.util.ArrayList; import javax.swing.JOptionPane; public class BudgetProgram { public
Add a running total as you add items to the list for this program:
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class BudgetProgram {
public static void main(String[] args) {
// Created an array
ArrayList
DecimalFormat format = new DecimalFormat("#.00");
String input;
double budget, taxRate;
try {
// Setting budget
input = JOptionPane.showInputDialog("Please enter your budget amount.");
budget = Double.parseDouble(input);
// Tax
input = JOptionPane.showInputDialog("Please enter the tax rate (%).");
taxRate = Double.parseDouble(input);
// Items and price
while (!input.equalsIgnoreCase("Q")) {
input = JOptionPane.showInputDialog("Please enter item name (Q to stop)");
if (!input.equalsIgnoreCase("Q")) {
// Creates an item
Item item = new Item();
item.name = input;
input = JOptionPane.showInputDialog("Please enter item price");
item.price = Double.parseDouble(input);
// Adds item to an array
items.add(item);
}
}
// Creating a total price summary
String summary = "Items entered: " + items.size() + " ";
double totalPrice = 0;
for (Item itm : items) {
//item info
summary += itm.name + ", $" + itm.price + " ";
totalPrice += itm.price;
}
summary += "Price: $" + totalPrice + " ";//price
totalPrice += totalPrice * taxRate / 100.0;//adding tax
summary += "Including tax: $" + totalPrice + " ";//price with tax
summary += "Budget: $" + budget + " ";//budget
if (totalPrice > budget)
{
// print if it is over budget
summary += "Over budget by: $" + (format.format(totalPrice - budget)) + " extra ";
}
else
{
// print if it is under budget
summary += "Under budget with: $" + (format.format(budget - totalPrice)) + " left ";
}
// print the summary
JOptionPane.showMessageDialog(null, summary);
} catch (Exception e) {
// if an invalid input is entered, like a letter for price
JOptionPane.showMessageDialog(null, "Invalid input!");
}
}
}
//Class to get item to work
class Item {
String name;
double price;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started