Why isn't my code calculating the correct total? - java

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];
}
}

Related

Using multiple arrays as information in a method

I'm struggeling a bit with arrays and user what's inside with loops. I have this question for example (ignore what's inside of the previewOrder method, i was trying stuff out):
public class Ex1_19 {
final static String NAMES[]= {"Spa reine 25 ","Bru plate 50","Bru pét 50",
"Pepsi","Spa orange", "Schweppes Tonic","Schweppes Agr","Ice Tea","Ice Tea Pêche",
"Jus d'orange Looza", "Cécémel", "Red Bull","Petit Expresso","Grand Expresso","Café décaféiné ",
"Lait Russe ","Thé et infusions","Irish Coffee ","French Coffee ","Cappuccino","Cécémel chaud",
"Passione Italiano","Amour Intense", "Rhumba Caliente ","Irish Kisses ","Cuvée Trolls 25",
"Cuvee Trolls 50","Ambrasse-Temps 25","Ambrasse-Temps 50 ","Brasse-Temps Cerises 25",
"Brasse-Temps Cerises 50","La Blanche Ste Waudru 25","Blanche Ste Waudru 50",
"Brasse-Temps citr 25","Brasse-Temps citr 50","Spaghetti Bolo ","Tagl Carbonara",
"Penne poulet baslc ","Tagl American","Tagl saum"};
final static double NETPRICES[]= {2.2, 2.3,3.9,2.2,2.2,2.6,2.6,2.6,2.6,2.6,2.6,4.5,2.2,2.2,2.2,2.5,2.5,7.0,7.0,2.8,2.8,6.2,6.2,6.2,6.2,
2.9,5.5,2.7,5.1,3.1,5.8,2.6,4.9,2.6,4.9,10.8,11.2,12.2,14.5,16.9};
public static void main(String[] args) {
int Order[][]={{3,2},{1,3},{12,4},{37,1},{36,3},{0,0},{0,0},{0,0}, {0,0}};
previewOrder(Order);
}
public static void previewOrder(int order[][]) {
int i = 0;
int j = 0;
while(i < order.length && j < order.length) {
System.out.println(NAMES[i]);
i++;
j++;
}
}
}
My result has to be something like this but with what's inside the "order" array:
Bru pét 50 3.9 2 7,80
Spa reine 25 2.2 3 6,60
Red Bull 4.5 4 18,00
Tagl Carbonara 11.2 1 11,20
Spaghetti Bolo 10.8 3 32,40
In my exercice I have to use a while loop and I have to put the order array in my method parameters. I can't figure out how to make them all communicate.
Sorry if this question has been answered somewhere else but I don't know how to search for it.
EDIT: I know that Orders does not use zero based index, but starts at 1. This is probably because "Order" is supposed to be a user entry. The first number of the array is like a drink number.
I wasn't very clear on the expected output.
Bru pét 50 (NAME[3]) 3.9 (NETPRICE[3]) 2 (Order[][2]) 7.80 NETPRICE[3] * Order[][2] and this for every occurence in Order
The Order array (btw: should be named order or orders) obviously contains references to ordered items and their amount. It's a two dimensional array, like a table with two columns.
Your expected output of "Bru pét 50 3.9 2 7,80", coming from Order[0] {3,2} indicates that the first element (Order[0][0]) is a reference to the items name (from NAMES) and the price (from NETPRICES). The second value of each "row" is the item amount (2) and finally there's the computed total.
For reasons unknown, Orders does not not use zero-based indexed, but starts at 1. So ORDER[0] having value {3,2} actually referes to NAMES[2] and NETPRICES[2]. This needs to be taken into account when picking the right item form NAMES and NETPRICES.
Anyhow: This is what your method could look like. You still need to tweak the output according to your needs.
public static void previewOrder(int order[][]) {
for (int i = 0; i < order.length; i++) {
int index = order[i][0] - 1;
if (index < 0 || index > NAMES.length || index > NETPRICES.length) {
continue;
}
String name = NAMES[order[i][0] - 1];
double price = NETPRICES[order[i][0] - 1];
int amount = order[i][1];
double total = amount * price;
System.out.println(
name + " " + price + " " + amount + " " + total
);
}
}
Try this.
public static void previewOrder(int order[][]) {
Stream.of(order)
.filter(x -> x[0] != 0)
.forEach(x -> {
String name = NAMES[x[0] - 1];
int unit = x[1];
double price = NETPRICES[x[0] - 1];
System.out.printf("%s %.1f %d %.2f%n",
name, price, unit, price * unit);
});
}
output:
Bru p?t 50 3.9 2 7.80
Spa reine 25 2.2 3 6.60
Red Bull 4.5 4 18.00
Tagl Carbonara 11.2 1 11.20
Spaghetti Bolo 10.8 3 32.40
or
public static void previewOrder(int order[][]) {
for (int[] row : order) {
if (row[0] == 0)
continue;
String name = NAMES[row[0] - 1];
int unit = row[1];
double price = NETPRICES[row[0] - 1];
System.out.printf("%s %.1f %d %.2f%n",
name, price, unit, price * unit);
}
}
When I see tightly coupled arrays, I think of creating a class.
public class Product {
String name;
double unitPrice;
public Product () {
name = "*** Unnamed Product ***";
unitPrice = 0.0;
}
public Product (String name, double unitPrice) {
this.name = name;
this.unitPrice = unitPrice;
}
public String getName () { return name; }
public double getPrice () { return unitPrice; }
public String toString () { return name + " # " + unitPrice + " ea.";}
}
Then, you can have one array where you previously had two:
public class Ex1_19 {
static final Product [] productList = {
new Product("Spa reine 25 ", 2.2),
new Product("Bru plate 50", 2.3),
new Product("Bru pét 50", 3.9),
new Product("Pepsi", 2.2),
new Product("Spa orange", 2.2),
new Product("Schweppes Tonic", 2.6),
new Product("Schweppes Agr", 2.6),
new Product("Ice Tea", 2.6)
// and so on
};
}
The preview order method, without formatted output, might look like this:
public static void previewOrder (int[][] order) {
double total = 0.0;
double itemCount = 0;
int lineNum = 0;
for (int i = 0; i < order.length; ++i) {
int row = order[i][0] - 1;
if (row < 0) {
break;
}
int qty = order [i][1];
double amt = productList [row].getPrice () * qty;
System.out.println (++lineNum + " " + productList[row].getName()
+ " " + productList[row].getPrice () + " " + qty
+ " " + amt);
itemCount += qty;
total += amt;
}
System.out.println ("===\nTotal: " + total + " for " + itemCount + " items.");
}

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!

Why is my code not finding the file?

So I'm doing a project for class and this is my code. This is my first semester coding and I can't for the life of me figure out why java can't find my file. Any input or advice would be great. I don't mean to just put this all of this code out here and be like whats wrong with my code but I've been on this for a few days with no success and it's due tomorrow.
import java.util.Scanner;
import java.io.*;
public class Project3_Josh_Rivera
{
public static void main(String[] args) throws IOException
{
File file = new File("boarding.txt");
Scanner inFile = new Scanner(file);
String firstName, lastName, dogBreed;
int dogWeight, days, numOfRecords;
double subTotal, total, totalAllBills = 0, totalTax, averageBill = 0;
numOfRecords = 1;
//read the file
while(inFile.hasNext())
{
firstName = inFile.nextLine();
lastName = inFile.nextLine();
dogBreed = inFile.nextLine();
dogWeight = inFile.nextInt();
days = inFile.nextInt();
inFile.nextLine();
if(inFile.hasNext())
{
inFile.nextLine();
}
numOfRecords++;
//call title method
displayTitle();
//call calculateSubtotal method
subTotal = calculateSubtotal(dogWeight, days, dogBreed);
//call calculateTax method
totalTax = calculateTax(subTotal);
//call the calculateTotal method
total = calculateTotal(subTotal, totalTax);
//call the calculateAllBills method and add the totals to totalAllBills
totalAllBills = calculateAllBills(total);
//call the calculateAverageBills mehtod
averageBill = calculateAverageBill(totalAllBills, numOfRecords);
//call the displayInformation method
displayInformation(firstName,lastName,dogBreed,dogWeight,days,subTotal,totalTax,total);
}//end while
inFile.close();
//output to display total of the bills and average bill cost
System.out.printf("The total of the bills is: $%.2f", totalAllBills);
System.out.printf("\nThe average bill cost is : $%.2f", averageBill);
}//end main
//method to display the title
public static void displayTitle()
{
System.out.println("Madison Kennel Grooming\n\n");
}
//method to calculate the subtotal
public static double calculateSubtotal(double dogWeight,int days,String dogBreed)
{
//calculate subtotal
double subtotal = .70 * dogWeight * days;
int HighRiskFee = 20;
//calculate subtotals with high risk fee
if(dogBreed.equalsIgnoreCase("Pit bull"))
subtotal += HighRiskFee;
else if(dogBreed.equalsIgnoreCase("Rottweiler"))
subtotal += HighRiskFee;
else if(dogBreed.equalsIgnoreCase("Doberman Pinscher"))
subtotal += HighRiskFee;
return subtotal;
}
//method to calculate the tax
public static double calculateTax(double subTotal)
{
double tax = 0.06;
double totaltax;
totaltax = subTotal * tax;
return totaltax;
}
//method to calculate the total
public static double calculateTotal(double subTotal,double totalTax)
{
double total = subTotal + totalTax;
return total;
}
//method to calculate all bills
public static double calculateAllBills(double total)
{
double totalBills = 0;
totalBills += total;
return totalBills;
}
//method to calculate average bills
public static double calculateAverageBill(double totalAllBills,int numOfRecords)
{
double average = totalAllBills / numOfRecords;
return average;
}
//method to display information
public static void displayInformation(String firstName,String lastName,String dogBreed,int dogWeight,int days,double subTotal,double totalTax,double total)
{
System.out.println("\nCustomer: " + firstName + " " + lastName);
System.out.println("Breed: " + dogBreed);
System.out.println("Dog's weight: " + dogWeight + " pounds.");
System.out.println("Boarding days: " + days + " day(s).");
System.out.printf("Subtotal for " + days + " days: $%.2f", subTotal);
System.out.printf("\nTax amount: $%.2f", totalTax);
System.out.printf("\nTotal due: $%.2f", total);
System.out.println();
}
}//end class
This is the exception error I get:
Exception in thread "main" java.io.FileNotFoundException: boarding.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at Project3_Josh_Rivera.main(Project3_Josh_Rivera.java:10)
Looks like you are not placing the file i.e. boarding.txt at correct place.
If you want to keep the code same way... then move the file to one level up from src folder into the main project folder.

Value stored in accessor method used in a for loop?

Essentially, I need to use the value from the getOriginalPrice method in a module.
When I simply put item.getOriginalPrice * .1, my code still compiles.
Not sure whats going on with this one.
Here is my code (not pasting the original class code unless needed).
import java.util.Scanner;
class InventoryApp {
public static void main(String[] args) {
String invNum = " ";
double ogPrice = 1;
int finishItems;
Inventory saleItem;
saleItem = new Inventory();
Scanner keyb = new Scanner(System.in);
System.out.println("Input the item numbers and original price for each item");
System.out.println("and I will show you the discounted price of each item");
System.out.println("for each day of the sale this week.");
System.out.println("Enter stop at the first prompt to end your list.");
System.out.println("Enter the item number of the item (Ex. 2b)");
invNum = keyb.next();
saleItem.setItemNumber(invNum);
while (!invNum.equals("stop")) {
System.out.println("Enter the item's original price (Ex 23.50");
ogPrice = keyb.nextDouble();
saleItem.setOriginalPrice(ogPrice);
printSaleData(saleItem);
System.out.println("Enter the item's item number");
invNum = keyb.next();
saleItem.setItemNumber(invNum);
}//end While
}//end main
public static void printSaleData(Inventory item) {
System.out.println("Item Number: " + item.getItemNumber());
for(int x = 1; x < 7; x = x + 1) {
item.getOriginalPrice() = item.getOriginalPrice -
(item.getOriginalPrice * .1);
System.out.println("Day: " + x + "\t" + "Price: $" + item.getOriginalPrice());
}//end for
}
}//end Class
Your printSaleDate method is not valid java. From your posted info, it's not clear what's your expected output.
But strictly speaking this is your posted method once fixed:
for (int x=1; x<7; x++) {
double discountedPrice = item.getOriginalPrice() * 0.1;
System.out.println("Day: " + x + "\tPrice: $" + discountedPrice);
}

Simple Divison for Calculator not working

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.

Categories

Resources