Simple Divison for Calculator not working - java

I'm Trying to make a calculator that will figure in tax, tip, and splitting between multiple people, but the last feature isn't working and I can't figure out why. I know it will probably be a simple fix but I'm new to Java so I just can't find it. Note: this is my first actual Java program so please be understanding with my probably obvious mistake.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TaxFinder {
static Scanner scan = new Scanner(System.in);
public static double priceD, taxD, totalTax, total, priceTipped, pricePP;
public static int peopleI;
public static String price, tax, people, ifTip, tip, ifSplit;
public static void main(String args[]){
ifTip = JOptionPane.showInputDialog("Was your purchase in a restaurant?");
if (ifTip.equalsIgnoreCase("yes")){
price = JOptionPane.showInputDialog("What was the cost of your bill ($)?");
priceD = Double.parseDouble(price);
tax = JOptionPane.showInputDialog("What is your tax rate (decimal)?");
taxD = Double.parseDouble(tax);
tip = JOptionPane.showInputDialog("Do you want to tip 5, 10, 15, or 20% ?");
if (tip.equals("5")){
priceTipped = priceD * .05;
}
else if (tip.equals("10")){
priceTipped = priceD * .1;
//System.out.println("Your price tipped is " + priceTipped);
}
else if (tip.equals("15")){
priceTipped = priceD * .15;
}
else if (tip.equals("20")){
priceTipped = priceD * .2;
}
totalTax = priceD * taxD;
total = priceD + totalTax + priceTipped;
}
else if (ifTip.equalsIgnoreCase("no")){
price = JOptionPane.showInputDialog("How much did your purchase cost ($)?");
priceD = Double.parseDouble(price);
tax = JOptionPane.showInputDialog("What is your tax rate (decimal)?");
taxD = Double.parseDouble(tax);
totalTax = priceD * taxD;
total = priceD + totalTax;
}
JOptionPane.showMessageDialog(null, "Your total is: $" + total, "Shopping Calculator", JOptionPane.PLAIN_MESSAGE);
ifSplit = JOptionPane.showInputDialog("Are you splitting the cost with other people?");
if (ifSplit.equalsIgnoreCase("yes")){
people = JOptionPane.showInputDialog("How many people including you?");
peopleI = Integer.parseInt(people);
pricePP = total / peopleI;
JOptionPane.showMessageDialog(null, "The total is $" + total + " per person", "Shopping Calculator", JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null, "Have a nice day!", "Shopping Calculator", JOptionPane.PLAIN_MESSAGE);
}
else if (ifSplit.equalsIgnoreCase("no")){
JOptionPane.showMessageDialog(null, "Have a nice day!", "Shopping Calculator", JOptionPane.PLAIN_MESSAGE);
}
}
}

Just use pricePP instead of total variable here :
JOptionPane.showMessageDialog(null, "The total is $" + total
+ " per person", "Shopping Calculator",
JOptionPane.PLAIN_MESSAGE);
because you output another variable, which isn't devided.

Related

Sales receipt, multiple choices (if/else), while loop, customer ability to change selections

None of the other posts seemed to fit accordingly.
I'm really struggling with producing this program without errors. I've come up with this below, however, if you run the program it is not adequately looping and if you choose the same candy twice the math isn't adding to the previous selection.
For the second part, I need to recode to adjust so that the customer may change the current selections if they'd like. So, I need the first part running perfectly.
import java.util.Scanner; //Program uses Scanner
import java.util.Calendar; //Program uses calendar
public class ClairAndreaG005PA2
{//Begin class ClairAndreaG005PA2
public static void main(String[] args)
{
/**Begin method. The customer is asked whether to proceed with a candy purchase.
* As long as the candy choice is in the proper range, prompt for the quantity,
* calculate the item total and subtotal; otherwise, print an error message. If it’s
* the first item in the purchase, ass it to the sales, a receipt with a $ sign for the
* item total. If not format the item without a $ sign for the item total
* and add it to the sales receipt. Start the process again when the customer wants
* to add another candy purchase. When the customer is done, the sales tax and the
* total calculated, the sales receipt is finalized and printed.
*/
int quantity = 0,
formatFirstItem = 1,
choice = 0;
final double TAX_RATE = .0825; //tax rate declared
double price = 0,
itemTotal = 0,
subtotal = 0,
taxAmount = 0,
total = 0;
char proceed = ' '; //proceed variable for loop
String candy = new String();
Calendar dateTime = Calendar.getInstance(); //situational date and time
Scanner input = new Scanner(System.in);
String salesReceipt = String.format("%n%nFAIRYTALE SWEETS%n"
+ "North Star Mall%n"
+ "San Antonio, TX%n"
+ "Date: %n", dateTime
+ "Time: %n", dateTime);
//Initiating variables and calculations
System.out.printf("%nDo you want to proceed with your candy purhase? \'Y\' or \'N\': ");
proceed = input.nextLine().charAt(0);
//End Prompt 1
while(Character.toUpperCase(proceed) == 'Y')
{
System.out.printf("%nFAIRYTALE SWEETS"
+ "%n%n1. Arabian Nights Chocolate Coins - 1 lb. Bag %5s%,7.2f"
+"%n2. Beauty and the Beast Lollipops - 1 lb. Bag %,12.2f"
+"%n3. Mad Hatter Jelly Beans - 1 lb. Bag %,20.2f"
+"%n4. Pinocchio's Candy Cones - Each %,23.2f"
+"%n5. Sleeping Beauty Caramel Apples - Each %,17.2f"
+"%n%nEnter your choice: ", "$", 2.25, 2.50, 1.75, 0.75, 1.25);
choice = input.nextInt();
//Prompt 2 Candy Menu
if(choice > 0)
{if(choice < 6)
{if(choice == 1)
{candy = "Arabian Nights Chocolate Coins";
price = 2.25;
}
else
{if(choice == 2)
{ candy = "Beauty and the Beast Lollipops";
price = 2.50;
}
else
{if(choice == 3)
{candy = "Mad Hatter Jelly Beans";
price = 1.75;
}
else
{if(choice == 4 )
{candy = "Pinocchio's Candy Cones";
price = 0.75;
}
else
{candy = "Sleeping Beauty Caramel Apples";
price = 0.75;
}
}
}
}
System.out.printf("%nQuantity for %s: ", candy);
quantity = input.nextInt();
//quantity of selections
}
else
{ System.out.println("Invalid candy choice! Try again.");
}
//Choices and selections
itemTotal = quantity * price; //calculation 1
subtotal += itemTotal; //calculation 2
System.out.printf("%nWould you like to make another candy purchase? \'Y\' or \'N\': ");
proceed = input.next().charAt(0);
if(formatFirstItem == 1 )
{
salesReceipt += String.format("%n%s"
+ "%n %d # $%.2f ex. %-24s $%,10.2f%n", candy,
quantity, price, " ", itemTotal);
formatFirstItem = 0;
}
else
{
salesReceipt += String.format("%s"
+ "%n %d # $%.2f ea. %-25s %,10.2f%n", candy,
quantity, price, " ", itemTotal);
}
//End if FormatFIrst Item is 1 or else formatFirstItem NOT 1
}
}//End while loop selection
taxAmount = TAX_RATE * subtotal;// calculation 3
total = taxAmount + subtotal; // calculation 4
salesReceipt += String.format("%n%36s %-6s $%,10.2f"
+ "%n%36s %-7s %,10.2f"
+ "%n%n%36s %-6s $%,10.2f%n", "SUBTOTAL: ", " ",
subtotal, "TAX # 8.250%: ", " ", taxAmount,
"TOTAL: ", " ", total);
System.out.printf("%s", salesReceipt);
}
}
Let me know!

Money format - how do I use it?

I'm a junior in high school. Having a tough time figuring out how to use money format. I'm doing an exercise in A Guide to Programming in Java (Second Edition) where I have to prompt the employees for the number of burgers, fries, and sodas.
Fries are $1.09, burgers are $1.69, and sodas are $0.99.
Here is my code:
import java.util.Scanner;
/**
* Order pg. 101
*
* Garret Mantz
* 2/10/2016
*/
public class Order {
public static void main(String[]args) {
final double pburgers=1.69;
final double pfries=1.09;
final double psodas=0.99;
final double ptax=0.065;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tendered;
double change;
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of sodas: ");
sodas = input.nextDouble();
System.out.print("Enter the amount tendered: ");
tendered = input.nextDouble();
totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
change = tendered - total;
System.out.println("Your total before tax is: \n" + totaltax);
System.out.println("Tax: \n" + tax);
System.out.println("Your final total is: \n" + total);
System.out.println("Your change is: \n" + change);
}
}
I just want to use the money format, but I'm not sure how. I'm sure it's a dumb question, but thank you for helping out!
Change your println to these, and see if that helps:
System.out.format("Your total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
System.out.format("Your change is: $%-5.2f\n", change);
There is also this:
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String totalTaxString = formatter.format(totaltax);
String taxString = formatter.format(tax);
String totalString = formatter.format(total);
String changeString = formatter.format(change);
System.out.format("Your total before tax is: %s\n", totalTaxString);
System.out.format("Tax: %s\n", taxString);
System.out.format("Your final total is: %s\n", totalString);
System.out.format("Your change is: %s\n", changeString);
Output:
Your total before tax is: $8.53
Tax: $0.55
Your final total is: $9.08
Your change is: $10.92

Program won't display output correctly

I'm writing a program that is supposed to display the output based off of some numbers that are typed in. I'm ending up with an output and it is completely blank, and none of the calculations are being performed
/**
*
* #NMATA003PA1.java
* #author Nicholas Mata
* #version 1.00 2015/09/25
*
* Program Purpose: This program controls whether a customer can calculate the cost of his/her stock purchases.
*
*/
import java.util.Scanner; //Scanner is imported to capture user input
import java.util.Calendar;//Calendare is imported to reflect the current date when necessary
public class MataN003PA1
{
public static void main(String[] args)//Customer will be able to calculate costs of multiple trades
{
String customerName = "", date = "";//Customer name and date are declared as Strings
int shares = 0, noOfStocks = 0;//shares and noOfShares are declared as integers, they are set to zero
double sharePrice = 0, stockCost = 0, commission = 0, totalCost = 0, onlineFee = 0, totalStockCost = 0, totalCommissions = 0, totalOnlineFees = 0;
/**
* sharePrice, stockCost, commission, totalCost, onlineFee, totalStockCost, totalCommissions, totalOnline Fees are declared
* as double, they are also set to zero
*/
char onlineTrade = ' ', brokerAssisted = ' ', another = ' '; // onlineTrade and brokerAssisted are declared as char variables, set to blank
Calendar dateTime = Calendar.getInstance(); //dateTime is declared
Scanner input = new Scanner(System.in);
System.out.printf("%nYEE-TRADE, INC. - The Wild West of Electronic Trading"
+"%n%nWelcome to Yee-Trade's stock purchase calculator.%n");
System.out.printf("%n%nWhat is your name? ");
customerName = input.nextLine();
System.out.printf("%nDo you want to calculate your stock purchases? Enter 'Y' or 'N' to exit: ");
another = input.nextLine().charAt(0);
while (Character.toUpperCase(another) == 'Y')
{
noOfStocks = noOfStocks + 1;
System.out.printf("%nHow many shares did you purchase? ");
shares = input.nextInt();
System.out.printf("%nWhat is the price per share? ");
sharePrice = input.nextDouble();
input.nextLine();
stockCost = shares * sharePrice;
totalStockCost = totalStockCost + stockCost;
totalCost = totalCost + stockCost;
System.out.printf("%nIs this an online trade? Enter 'Y' or 'N': ");
onlineTrade = input.nextLine().charAt(0);
if (Character.toUpperCase(onlineTrade) == 'Y')
{
onlineFee = 5.95;
totalOnlineFees = totalOnlineFees + onlineFee;
totalCost = totalCost + onlineFee;
}//END if_1
else
{
System.out.printf("%nIs this a broker assisted trade? Enter 'Y' or 'N': ");
brokerAssisted = input.nextLine().charAt(0);
if (Character.toUpperCase(brokerAssisted) == 'Y')
{
commission = stockCost * .02;
totalCommissions = totalCommissions + commission;
totalCost = totalCost + commission;
}//END if_2
else
{
System.out.printf("%nINVALID TRADE TYPE! %n");
noOfStocks = noOfStocks - 1;
totalStockCost = totalStockCost - stockCost;
totalCost = totalCost - stockCost;
}//end else_2
}//end else_1
System.out.printf("%nEnter 'Y' to calculate the cost of another stock purchase or 'N' to exit: ");
another = input.nextLine().charAt(0);
}//END WHILE LOOP
if (noOfStocks > 0);
{
System.out.printf("%nYEE-TRADE, INC."
+"%nTOTAL COST OF STOCK PURCHASES"
+"%nFOR %s", customerName);
System.out.printf("%nAS OF ");
System.out.printf("%1$TB %1$Td, %1$TY%n", dateTime);
System.out.printf("%nTotal Stock Cost: $", totalStockCost);
System.out.printf("%nTotal Online Fees: $", totalOnlineFees);
System.out.printf("%nTotal Commissions: $", totalCommissions);
System.out.printf("%n%nTOTAL COST: $", totalCost);
}//END if_3
System.out.printf("%nThank you for using Yee-Trade's stock purchase calculator! ");
noOfStocks = 0;
System.exit(0);}//END MAIN
}//END CLASS
You should not always try to format the output if it is not necessary.
Here's your problem :
System.out.printf("%nAS OF ");
System.out.printf("%1$TB %1$Td, %1$TY%n", dateTime);
System.out.printf("%nTotal Stock Cost: $" + totalStockCost);
System.out.printf("%nTotal Online Fees: $", totalOnlineFees);
System.out.printf("%nTotal Commissions: $", totalCommissions);
System.out.printf("%n%nTOTAL COST: $", totalCost);
You'll have to replace most of these with the following
System.out.printf("%nAS OF ");
System.out.printf("%1$TB %1$Td, %1$TY%n", dateTime);
System.out.println("Total Stock Cost: $" + totalStockCost);
System.out.println("Total Online Fees: $" + totalOnlineFees);
System.out.println("Total Commissions: $" + totalCommissions);
System.out.println("TOTAL COST: $" + totalCost);
Here is the output I get :
YEE-TRADE, INC. - The Wild West of Electronic Trading
Welcome to Yee-Trade's stock purchase calculator.
What is your name? Yassin
Do you want to calculate your stock purchases? Enter 'Y' or 'N' to exit: Y
How many shares did you purchase? 50
What is the price per share? 50
Is this an online trade? Enter 'Y' or 'N': Y
Enter 'Y' to calculate the cost of another stock purchase or 'N' to exit: N
YEE-TRADE, INC.
TOTAL COST OF STOCK PURCHASES
FOR Yassin
AS OF OCTOBRE 04, 2015
Total Stock Cost: $2500.0
Total Online Fees: $5.95
Total Commissions: $0.0
TOTAL COST: $2505.95
Thank you for suing Yee-Trade's stock purchase calculator!

Java Lemonade Calculator

Assignment is to:
Display any welcome message at the top of the output screen
Create variables to hold the values for the price of a cup of lemonade.
Display the price per glass.
Ask the user for their name, and store it as a String object. Refer to the user by name, whenever you can.
Ask the user how many glasses of lemonade they would like to order. Save this as a variable with the appropriate data type.
Store the San Diego tax rate of 8% as a constant variable in your program.
Calculate the subtotal, total tax, and total price, and display it on the screen.
Ask the user how they would like to pay for the lemonade, and save the input as a char variable.
Ask the user to enter either 'm' for money, 'c' for credit card, or 'g' for gold
Using the DecimalFormat class, make all currency data printed to the screen display 2 decimal places, and also a '$" sign.
Need help figuring out how to get tax rate of 8% as a constant variable in my program
that way I can calculate the subtotal, total tax, and total price, and display it on the screen
So far this is what I have:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class FirstProgram {
public static void main(String[] args) {
double cost = 7.55;
double amount = 7.55;
final double CA_SALES_TAX = 0.08;
int tax, subtotal, total;
subtotal = (int) (amount * cost);
tax = (int) (subtotal * CA_SALES_TAX);
total = tax + subtotal;
Scanner input = new Scanner(System.in);
double fnum = 7.55, tax1 = fnum * 0.08, answer = tax1 + fnum;
System.out.println("Welcome to the best Lemonade you'll ever taste! ");
System.out.println("My lemonade would only cost you a measly: $" + amount);
System.out.println("What is your name?");
String first_name;
first_name = input.nextLine();
System.out.println("Hi " +first_name+ ", how many glasses of lemonade would you like?");
fnum = input.nextDouble();
System.out.println("Subtotal: $" + (amount * fnum));
System.out.println("Tax: $" + (tax1 * CA_SALES_TAX));
tax1 = input.nextDouble();
Any help is appreciated
It looks like you already have the sales tax set as constant that is what the "final" keyword is being used for. As for your code i see some redundancies and am not sure as to why you are casting to integers. I made some mods for what I think you want it to do.
public static void main(String[] args) {
double cost = 7.55;
final double CA_SALES_TAX = 0.08;
double subtotal,tax,total;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the best Lemonade you'll ever taste! ");
System.out.println("My lemonade would only cost you a measly: $" + cost);
System.out.println("What is your name?");
String first_name = input.nextLine();
System.out.println("Hi " +first_name+ ", how many glasses of lemonade would you like?");
int fnum = input.nextInt();
//calc subtotal, tax, total
subtotal = fnum * cost;
tax = subtotal *CA_SALES_TAX;
total = tax + subtotal;
// print them all out
System.out.println("Subtotal: $" + (subtotal));
System.out.println("Tax: $" + (tax));
System.out.println("Total Price: $" + (total));
}

Why isn't my code calculating the correct total?

I'm having trouble trying to find out the running total. Each time I calculate the running total it miscalculates and gives me the incorrect answer. I'm not sure what it is. I cant tell if it has something to do with the method calling I did in main, the if statement in takeOrder or neither.
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class MyCoffeeHouse {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null, "What is your name?");
greetCustomer(name);
double totalPrice = takeOrder(name);
calculateFinalPrice(totalPrice);
}
public static void greetCustomer(String name) {
// greet customer
JOptionPane.showMessageDialog(null, "Hello " + name + ", Welcome to A Cup of Java!");
}
public static double takeOrder(String name) { // this method returns
String[] food = {"coffee", "bagel", "tea", "muffin"};
double[] price = {3.99, 1.99, 2.99, 4.99};
double totalprice = 0;
DecimalFormat dec = new DecimalFormat("#.00");
for (int index = 0; index < food.length; index++) {
JOptionPane.showMessageDialog(null, "Our menu offers: " + food[index] + "(s) which is " + "$"
+ price[index]);
}
int numItems =
Integer.parseInt(JOptionPane.showInputDialog(name + ", How many items are "
+ "you interested in purchasing?"));
// running total
for (int index = 0; index < numItems; index++) {
String input =
JOptionPane.showInputDialog(null, "Which items are you interested in purchasing from "
+ "our menu: coffee, bagel, tea, or muffin?");
if (input.equalsIgnoreCase(food[index])) {
totalprice += price[index];
}
}
return totalprice;
}
public static void calculateFinalPrice(double totalPrice) {
double salestax = (totalPrice * 0.07) + totalPrice; // 7% salestax
double finalprice;
DecimalFormat dec = new DecimalFormat("#.00");
int input =
JOptionPane.showConfirmDialog(null, "Would you like to dine in?", "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (input == JOptionPane.YES_OPTION) {
finalprice = totalPrice + (salestax * 0.02);
JOptionPane.showMessageDialog(null, "The final price is $" + finalprice);
} else {
DecimalFormat dec = new DecimalFormat("#.00");
JOptionPane.showMessageDialog(null, "The final price is $" + dec.format(salestax));
}
}
}
When you do
double salestax= totalPrice + 0.07; //7% salestax
This means you are adding 7 cents in tax, not 7 percent. To add 7 % you need to multiply the original price by 1.07 or 100% + 7% = 107%
double salestax= totalPrice * 1.07; // add 7% salestax
When you do
finalprice=salestax + 0.02;
You are adding 2 cents. Note: at this point you can add another 2% however adding 7% and another 2% is not the same at adding 9% as 1.07 * 1.02 > 1.09.
Get the chosen food item before you loop to test for the price.
// First get the input
String input=JOptionPane.showInputDialog(null,//
"Which items are you interested in purchasing from "
+ "our menu: coffee, bagel, tea, or muffin?");
for(int index=0;index<numItems;index++) {
// now loop all of the items, and check what was picked.
if(input.equalsIgnoreCase(food[index])) {
totalprice+=price[index];
}
}

Categories

Resources