Java Lemonade Calculator - java

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

Related

How would I display a shape in JOptionPane.showMessageDialog() in Processing?

Part of the requirement is to replicate the bar graph in https://imgur.com/a/Gx2XOql
I tried this to see if I could rectangle in the dialogue window (obviously it didn't work):
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income + rect(10,10,10,10));
}
The rest of my code:
import javax.swing.JOptionPane;
//Input Variables
String prov_id = ""; //province_id will contain the user input for the province (E.g. 'AB').
float gross_income = 0; //gorss_income contains the user input for gross income (E.g. 30000).
//Output Variables:
//You will store the result of your analysis and calculations in these variables
float tax_rate = 0; //Variable tax_rate will hold the tax_rate percentage. You will assign a value for tax_rate based on the Taxable Income (Table 1) table given in the studio project document.
//The value of tax ranges between 0 to 1 (E.g. for Alberta, income of equal or less than $40000 tax = 0.25)
float net_income = 0; //Net income is calculated based on tax_rate. It is the take-home income after taxes are deducted.
//i.e. net_income = gross_income * (1 - tax_rate);
float tax_amount = 0; //tax amount is the amount of taxes paid based on gross income depending on the province.
//i.e. tax_amount = gross_income * tax_rate;
// prompt for and read the province id
prov_id = JOptionPane.showInputDialog("Please enter your province's two-letter abbreviation (e.g., AB for Alberta): ");
// prompt for and read the gross income
String answer = JOptionPane.showInputDialog("Please enter your taxable income: ");
//convert user input to folat
gross_income = Float.parseFloat(answer);
net_income=gross_income*(1-tax_rate);
tax_amount=gross_income*tax_rate;
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income);
}
}
The expected out put is supposed to be this: https://imgur.com/a/Gx2XOql
So far my code displays this: https://imgur.com/a/Gx2XOql
The window where the bar graphs are shown is Processing's not one from JOptionPane.showMessageDialog() since the window is named "TaxCalculator_kEY", which i assume is the name of the file, not "Message".

Code Double Equation Error for User Input Problem

My first assignment is to develop a code that allows the user to input data for the distance in miles they wish to travel, the fuel efficiency, and the cost of gas. Then create a code in order to calculate the total cost of the trip.
I have all the code for all the input values but I'm having trouble with the equation itself. Java is not recognizing "/". I can't understand what I'm doing unless I need to add a bit more code for the equation to work.
import java.util.Scanner;
public class DrivingCost
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
Scanner t = new Scanner(System.in);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
Scanner u = new Scanner(System.in);
System.out.print("Please enter the price per gallon (dollars): ");
String distanceInMiles = s.nextLine();
System.out.println("The distance (miles): " + distanceInMiles);
String fuelEfficiency = t.nextLine();
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
String pricePerGallon = u.nextLine();
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
}
}
This is the error I keep recieving:
DrivingCost.java:32: error: bad operand types for binary operator '/'
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
^
You're doing Math operation on String, you can't, you need double type
Double.parseDouble(sc.nextLine()); reads a line and parse to a double (benefits : avoid return line error in general, good habit to have)
sc.nextDouble() reads directly for a double
Use only one Scanner per source
Have a good order between print and scanner asking
Scanner sc = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
String distanceInMiles = Double.parseDouble(sc.nextLine());
System.out.println("The distance (miles): " + distanceInMiles);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
String fuelEfficiency = Double.parseDouble(sc.nextLine());
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
System.out.print("Please enter the price per gallon (dollars): ");
String pricePerGallon = Double.parseDouble(sc.nextLine());
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
You are trying to do calculations with strings. You have to parse doubles out of your string inputs. Just change your equation line to this:
double tripCost = (Double.valueOf(distanceInMiles) / Double.valueOf(fuelEfficiency)) * Double.valueOf(pricePerGallon);
P.S. Proper input validation would be a good improvement. In case user provide incorrect input. Also, as mentioned in the comments there is no need to use multiple Scanners. One will be enough.
You can get distanceInMiles, fuelEfficiency and pricePerGallon in double using s.nextDouble().
After that you should be able to perform double operation on these variables.
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
double distanceInMiles = s.nextDouble();
System.out.println("The distance (miles): " + distanceInMiles);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
double fuelEfficiency = s.nextDouble();
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
System.out.print("Please enter the price per gallon (dollars): ");
double pricePerGallon = s.nextDouble();
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
}

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

Calculating Gas Mileage efficiency

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.

Writing for loops/while loops?

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

Categories

Resources