I'm in a programming class in high-school, and I was given an assignment to make a basic subtotal and top calculator, but I work at a restaurant, so it seemed a little pointless to make a calculator that only let you read in one food. So I tried to make it able to take in multiple food items and add them to one price variable. Sorry if some of this code may seem inefficient or redundant. It's only high-school of course.
The issue is, when I run it, it gets up to the asking if there was another food item the user would like to add, and when I type in "Yes" or "No", the program does nothing. Keeps running, but goes no further. Any explanations?
import java.text.NumberFormat;
import java.util.Scanner;
public class Price {
/**
* #param args
*/
public static void main(String[] args) {
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes"));
}
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}
}
You have an infinite loop here:
while (done.equalsIgnoreCase("Yes"));
Once you enter Yes, it will keep sitting there and doing nothing because the value of done is Yes and never changes.
Also your loop structure is a bit odd. Your outer for loop runs as many times as the quantity of the first item. But shouldn't you only be multiplying that number to the cost? Because you are either running the loop for as long as the number of items the user entered (by asking them up front) or you don't ask them the total number of items and simply ask them to enter Yes if they want to add more items; you can't really do both.
Your loop should probably look something like this:
String input = "Yes";
while(input.equalsIgnoreCase("Yes")) {
System.out.println ("How many of the first item did you get? ");
quantity1 = kb.nextInt();
System.out.println ("What was the price of that single item? ");
unitPrice1 = kb.nextDouble();
//total += unitPrice1 * quantity1 - you don't have this in your code, but this is where you would be calculating the running total
System.out.println("Was there another food item you'd like to add? ");
input = kb.next();
}
you need to exit for loop when user enters yes, so you can use label here like below:
outerloop:
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes")){
break outerloop;
}
}
Your current code does not do anything inside the while loop if you don't enter yes. And if you enter yes it will be stuck in infinite loop because of your while loop. This is not the efficeint way of looping, but this code will have least change in your current code.
You're while loop is doing nothing, you had given it a condition, but it has no instruction.
Try something like this..(sorry for my rusty java)
'public static void main(String[] args) {
//variable declaration
bool running = true
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
while(running = true){
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
if(done.equalsIgnoreCase("No")){
running = false
//Allows you to break out of the while loop if the user does not want to add anything else
//DO NOT USE BREAK STATMENTS, IT IS A POOR PROGRAMMING PRACTICE.
};//end if
}//end for
}//end while
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
//You should comment whats going on here
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
//Output
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}//end main
Related
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));
}
Since premium gasoline is more expensive than regular, I need to calculate gas mileage one must get on premium gasoline to make up the cost differential between that and regular gasoline. This value is represented by the gasmileageRequired variable.
Question: Am I calculating the gasmileageRequired variable correctly?
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
public class GasMileage {
public static void main(String[] args) {
//Variable declarations
Scanner scan = new Scanner(System.in);
NumberFormat numFmt = new DecimalFormat("##.###");
NumberFormat costFmt = DecimalFormat.getCurrencyInstance();
double tankSize = 0;
final double regularCost;
final double premiumCost;
double regularGasMileage = 0;
//User enters gas tank size
System.out.print("What is the size of your gas tank? (in gallons) ");
tankSize = scan.nextDouble();
//User enters price of regular gasoline
System.out.print("What is the cost of regular gasoline per gallon? (in $) ");
regularCost = scan.nextDouble();
//User enters price of premium gasoline
System.out.print("What is the cost of premium gasoline per gallon? (in $) ");
premiumCost = scan.nextDouble();
//User enters cars' gas mileage
System.out.print("What is your cars' gas mileage on regular gasoline? (miles/gallon) ");
regularGasMileage = scan.nextDouble();
//Variable declarations
double totalregularCost = regularCost * tankSize;
double totalpremiumCost = premiumCost * tankSize;
double costDifference = totalpremiumCost - totalregularCost;
double gasmileageRequired = regularGasMileage + (premiumCost/costDifference);
scan.close();
//Begin output
System.out.println("\nGas tank size: " + tankSize + " gallons");
System.out.println("\nTotal cost of regular gasoline: " + costFmt.format(totalregularCost) + "\nGas mileage (regular): " + numFmt.format(regularGasMileage) + " miles/gallon");
System.out.println("\nTotal cost of premium gasoline: " + costFmt.format(totalpremiumCost) + "\nGas mileage required to make up for cost increase: " +
numFmt.format(gasmileageRequired) + " miles/gallon");
}
}
gasmilageRequired is being calculated correctly, yes. It should tell you how many MPG u would need to get in order to make up the price difference.
This is for an assignment in my class. It is to make an automatic ordering system. I'm still new to Java so everything doesn't necessarily click just yet. I think most things work for the most part but the main thing I am having trouble with is making the loop itself and making an exit for it.
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
while (itemnumber < 1 || itemnumber > 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double total = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber){
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Price Total: " + total);
}
This is my first time posting on this site, but I think I found your problem. There are two large errors, indicated by the arrows:
while (itemnumber >= 1 || <-- itemnumber <= 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
} <--
1) This should be a '&&' not a '||'. You want it to be within the range. Right now the number it reads has to be greater than or equal to 1 OR less than or equal to 4, which is all integers.
2) You close your loop prematurely. What your code does right now (after the && switch) is it takes numbers 1-4 and keeps repeating the "Enter the item number...." line until you put a number not in the range, then it continues.
The fix: there are a few ways to fix this. My fix would be thus, and the explanation will come after:
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
double total = 0;
while (itemnumber >= 1 && itemnumber <= 4) {
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber)
{
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print("Price Total: " + total);
}
}
Explanation: In essence, you had like 90% of it. I moved the mentioned '}' to the end here:
itemnumber = userInput.nextInt();
} <--
That way, it loops over this code until the user ends.
Additionally, your loop does not need much fixing. It can be used with the && fix. However, you have to put that top line before the loop.
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
And then you put the same line at the end of the loop to reset itemnumber. What your loop does is if itemnumber is between 1 and 4, it executes the following code. Otherwise, it stops. By checking before you enter the loop, you set itemnumber so that way the loop has something to check. And you put the next input at the end of the loop so that way your program finishes totaling its first execution before moving on to the next.
Additionally, you should move the variable 'total' out of the loop as seen above. If you keep looping over it and resetting it to 0, your total will output 0 every time. Best to keep the creation of total out of the loop, and its modification inside the loop.
Small tip, use System.out.println(); instead of System.out.print(); it puts the outputs on its own line. Looks a little nicer.
I think that covers it. If you want more explanation, I'd be more than happy to give it to you. Java is pretty fun once you get used to it. It just takes time. :D
I've written this program but am running into a logical error upon compilation.
My input would be 1, 2, 6, 10 for the selection of products and the coinciding output should be
Total items ordered: 3
Price of items ordered: $747.00
Sales Tax: $48.55
Total amount due: $795.55
Strangely enough it is giving me
Total items ordered: 3
Price of items ordered: $6611.00
Sales Tax: $429.715
Total amount due: $7040.715
Is there an error within my for loop conditions or calculations, or my array that is leading to this hyper-inflated output?
import java.util.Scanner;
public class GrapefruitOrderingArray {
//Declare Constants
public static final int SIZE = 100;
public static final int[] itemPrices = {49,299,329,399,199,1299,1199,999,599};
public static void main(String[] args) {
// Declare Variables
Scanner input = new Scanner (System.in);
String CustomerName;
int[] naNumber = new int [SIZE];
int nProducts = 0;
double nTotal = 0;
double dFinalPrice = 0.0;
int nCount = 0;
//Declare Constants
final int SENTINEL = 10;
final double SALES_TAX = 0.065;
//Prompt user to enter name
System.out.println("Please enter your name: ");
//Enter user name
CustomerName = input.nextLine();
System.out.println("");
//Begin Product Listing Declarations with respect to array above
System.out.println("GRAPEFRUIT PRODUCT:");
System.out.println("1. gPod shuffle $" + itemPrices[0]);
System.out.println("2. gPod Touch $" + itemPrices[1]);
System.out.println("3. gPad Mini $" + itemPrices[2]);
System.out.println("4. gPad 2 $" + itemPrices[3]);
System.out.println("5. gPhone $" + itemPrices[4]);
System.out.println("6. gMac $" + itemPrices[5]);
System.out.println("7. MacNovel Pro $" + itemPrices[6]);
System.out.println("8. MacNovel Air $" + itemPrices[7]);
System.out.println("9. MiniMac $" + itemPrices[8]);
System.out.println("10. Complete my order");
//Keep reading until the input is terminated by sentinel
System.out.println("\nPlease select an item from the menu above: ");
//Read number entered by the user
naNumber[nCount] = input.nextInt();
//Begin while-loop statement
while (naNumber[nCount] != SENTINEL) {
System.out.println("\nPlease select another item from the menu above: ");
nCount++;
//Read number entered by the user
naNumber[nCount] = input.nextInt();
}
System.out.println("Thank you for ordering with Grapefruit Company, " + CustomerName);
//Call final price calculation
dFinalPrice = calculateTotalPrice(naNumber,itemPrices,nTotal);
//Print blank line to screen
System.out.println("");
//Total amount of product ordered
System.out.println("Total items ordered: " + nCount );
//Total price of items ordered
System.out.println("Price of items ordered: $" + dFinalPrice );
//Sales tax associated with the purchase
System.out.println("Sales tax: $" + SALES_TAX * dFinalPrice );
//Total amount due by the customer to Grapefruit Co.
System.out.println("Total amount due: $" + (SALES_TAX * dFinalPrice + dFinalPrice ));
} //End main method
private static double calculateTotalPrice(int[] naNumber, int[] itemPrices) {
double total = 0;
//Calculate entered items
for(int i = 0; i < naNumber.length; i++){
if(naNumber[i] != 0) {
total += itemPrices[naNumber[i] - 1];
}
}
return total;
}
} //end class calculateTotalPriceOfItemsOrdered
You naNumber will contain numbers from 1 to 9. This means that you'll be multiplying the item prices by some large numbers at some points, hence why you're getting large totals.
What I think you want to do is
double itemTotal = itemPrices[naNumber[i] - 1];
nTotal += itemTotal;
Without multiplying itemPrices[i] by naNumber[i]
Also you don't really need to pass nTotal to the method and initialise a double with every loop. You can just declare a field outside the loop:
double total = 0;
Use it inside the loop like this:
total += itemPrices[naNumber[i] - 1];
And return it at the end of the method.
So your method would look something like that:
private static double calculateTotalPrice(int[] naNumber, int[] itemPrices) {
double total = 0;
//Calculate entered items
for(int i = 0; i < naNumber.length; i++){
if(naNumber[i] != 0) {
total += itemPrices[naNumber[i] - 1];
}
}
return total;
}
There are three problems here.
You put the sentinel value, 10, into the array of items the user has chosen.
You use the loop index rather than the number the user chose when calculating price.
You multiply the price of each item by its number. So the user buys 6 of item 6.
In your main method, you need to read the user's input into another variable, and only insert it into the array if it is not the sentinel value.
In your calculateTotalPrice method, you should calculate the price of an individual line item like this:
double itemTotal = itemPrices[naNumber[i] - 1];
I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}