Creating trip cost calulator - java

I am working on an assignment for school and I have a basic program already that calculates the total cost of a trip by asking the total mileage, average mpg of car, and cost per gallon of gas. This works great but I also need to add a few more items and I am unsure of how to do so. First I need to include a menu of some sort giving the option to either calculate the trip cost or exit the program. Next I need to incorporate somewhere in the program a bit asking if the user wants an oil change or not and then based on the answer adding this to the total.
import java.util.Scanner;
public class GasCalculator {
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
double cost = (miles / mpg * gas + oil);
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + cost + "."));
}
}
As you can see I added a little bit asking if they want an oil change. My vision of doing it would be to create a variable for either the y or n answer and then an if else statement based on whether y or n. If y it will add 39.99 to a new variable "oil". If n it will make the variable 0. Oil has been incorporated into the final equation regardless of it's value for ease.
I am not looking for anyone to do my assignment for me. I guess I am looking to see what this would look like or if anyone has any input as far as how I should tackle this. Thank you for any help you can provide!

First I need to include a menu of some sort giving the option to
either calculate the trip cost or exit the program.
You can use a switch statement.
//ask for user to enter 0 to exit, 1 to calculate the trip
switch(answer) {
case 0 : System.exit(0);
break;
case 1 : //calculate cost trip here
break;
default : System.exit(0);
}
Next I need to incorporate somewhere in the program a bit asking if
the user wants an oil change or not and then based on the answer
adding this to the total
Well you can get the value of the user with your Scanner object like you did and write an if statement to check this value.
System.out.println("Would you like an oil change? Enter Y or N");
//here get the value of the user using your scanner object
double oil = 0;
if(/*test if value is equals to y*/)
oil += 39.99;
Hints :
to avoid testing if the value is "y" or "Y", use the method equalsIgnoreCase of the String class.
when this will works you can wrap the functionnality of calculating the trip cost in a method and call this method in the case 1 of the switch statement.

Edit
import java.util.Scanner;
public class GasCalculator {
public static void main (String args[])
{
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
char oil = scan.next().charAt(0);
if (Character.toUpperCase(oil) == 'Y'){
System.out.println("Cost of oil change id 39.99);
System.out.println("39.99 will be added to your total cost");
total += 39.99;
}
double cost = (miles / mpg * gas);
total += cost;
String menu = "Pick a menu option: \n"
+ "1. Calculate total \n"
+ "2. exit";
System.out.println(menu);
int choice = scan.nextInt();
if (choice == 1){
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + total + "."));
} else {
System.exit(0);
}
}
}

You can implement exit option like this:
System.out.println("Choose your desired option:\n1)Calculate Trip Cost\n2)Exit");
int answer = scan.nextInt();
if (answer==1){
// the rest of your program
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
double cost = (miles / mpg * gas + oil);
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + cost + "."));
}

Related

Program repeats user input even when an equivalency condition / the first if-statement has been met

I need an instance in my program to work in that if the user inputs a payment number (payment) that is equal to the total price of a checkout with taxation (price3), the program will just list 0.00 as change and not repeat user input as if the user's payment is less than the price. However, when payment equals price3 (payment - price3 == 0), the program goes to the else-if statement. How do I fix this?
Example: price3 == 28, payment == 28, the output after payment input is "You still owe..." and so on instead of "Your change is $0.00".
I think it is skipping the first if-statement in the while loop, but I have no idea why. I already tried moving around the if-statements in the while-loop to no avail.
There are no error messages.
Note: I am still trying to learn Java. Just started recently.
The program code which my question references is displayed below:
import java.util.Scanner;
public class Checkout
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many items are you purchasing?");
int count = input.nextInt();
double price1 = 0;
double price2 = 0;
String userItem = "";
for(int i = 1; i<=count; i++)
{
System.out.println("Please enter the name of the item:");
input.nextLine();
userItem = input.nextLine();
System.out.println("Please enter the price of the item:");
price1 = input.nextDouble();
System.out.println();
System.out.printf("Your item #" + i + " is " + userItem + " with a price of $" + "%.2f", price1);
System.out.println();
price2 = price2 + price1;
}
System.out.println();
System.out.printf("Your total amount is: $" + "%.2f", price2);
double price3 = price2 + (price2 * 0.06);
System.out.println();
System.out.printf("Your total amount with tax is: $" + "%.2f", price3);
System.out.println();
System.out.println("I need a payment!");
double payment = input.nextDouble();
boolean condition = false;
while(condition == false)
{
if(payment - price3 == 0)
{
condition = true;
}
else if(payment < price3)
{
System.out.println();
System.out.printf("You still owe " + "%.2f", (price3-payment));
System.out.println();
System.out.println("I need a better payment!");
payment = input.nextDouble();
}
else
{
condition = true;
}
}
double change = payment - price3;
System.out.println();
System.out.printf("Your change is: $" + "%.2f", change);
}
}
The core of your problem lies in (1) expecting exact equality of floating-point value, and (2) displaying quantities to 2 decimal places.
Given the user is told the amount to pay (price3) using 2 places of decimals, even if he enters that exact same value as payment, it may not match the true value of price3.
Ideally you should do all calculation in pennies (or whatever the smaller unit of this currency is). Failing that, your criterion for having paid the right amount should be something like the difference between price and payment is less than 0.01.
In the stated case
Example: price3 == 28, payment == 28, the output after payment input
is "You still owe..." and so on instead of "Your change is $0.00".
if the price before tax is 26.415 it makes the price after tax 27.9999, which displays as 28.00 but is not equal to 28.00. Neither 26.41 nor 26.42 get you to an after-tax displayed price of 28.00.
that is happening because of price3=price2+(price2*0.06). So, when it is comparing payment with price3, it is always less. See below

Ask the user to enter a String to indicate he has more data to enter, or if he is done

Everything is working properly but I need assistance with making a loop that enables a user to input values for all any and food. Also, some codes weren't able to be posted here so i took a screenshot of it.
https://prnt.sc/r6nptj
System.out.println("Are you male or female? (M/F)");
gender = kboard.next();
System.out.println("Enter your weight in lbs.");
weight = kboard.nextDouble();
System.out.println("Enter your height in inches.");
height = kboard.nextDouble();
System.out.println("Enter your age in years.");
age = kboard.nextDouble();
BMRw = 655+(4.35 * weight)+(4.7 * height)-(4.7 * age);
BMRm = 665+(6.23 * weight)+(12.7 * height)-(6.8 * age);
boolean isMale = gender.startsWith("M");
if (isMale == true) {
BMRm = 665+(6.23 * weight)+(12.7 * height)-(6.8 * age);
System.out.println(" Your Basal Metabolism Rate is " + BMRm);
double noExercise = (BMRm * 1.2);
System.out.println("Your Basal Metabolism Rate when you don't engange in exercise is " + noExercise);
double lightExercise = (BMRm * 1.375);
System.out.println("Your Basal Metabolism Rate when you engange in light exercises one to three days a week " + lightExercise);
double intensely = (BMRm * 1.725);
System.out.println(" Your Basal Metabolism Rate when you exercise intensely six to seven days a week " + intensely);
double activeJob = (BMRm * 1.9);
System.out.println("Your Basal Metabolism Rate when you exercise intensely six to seven days a week while having a physically active job " + activeJob);
}
else {
BMRw = 655+(4.35 * weight)+(4.7 * height)-(4.7 * age);
System.out.println(" Your Basal Metabolism Rate is " + BMRw);
double noExercise = (BMRw * 1.2);
System.out.println("Your Basal Metabolism Rate when you don't engange in exercise is " + noExercise);
double lightExercise = (BMRw * 1.375);
System.out.println("Your Basal Metabolism Rate when you engange in light exercises one to three days a week " + lightExercise);
double moderateExercise = (BMRw * 1.55);
System.out.println(" Your Basal Metabolism Rate when you exercise moderately three to five times a week " + moderateExercise);
double intensely = (BMRw * 1.725);
System.out.println(" Your Basal Metabolism Rate when you exercise intensely six to seven days a week " + intensely);
double activeJob = (BMRw * 1.9);
System.out.println("Your Basal Metabolism Rate when you exercise intensely six to seven days a week while having a physically active job " + activeJob);
}
}
}
You can use make a loop by using while or for
In your case, I suggest you can use while
for example
Scanner myScanner = new Scanner(System.in);
String name;
int age;
int x = 1;
while(x != 0)
{
System.out.print("Enter name : ");
name = myScanner.next();
System.out.print("Enter age : ");
age = myScanner.next();
System.out.print("Do you want to continue?? 1 for yes || 0 for no : ");
x = myScanner.next(); //if x = 0 then it will break the loop
}
try to run this code!
more information about while loop,
check this out:
https://www.w3schools.com/JAVA/java_while_loop.asp
Okay, so I am also new, but what I have learned is that you can put a do...while loop around your code.
do
{
//put all your code you want in the loop here
//Then, add this:
System.out.print("Would you like to enter more data? (Y/N)");
char answer1 = Expo.enterChar(); //The expo class is a separate class that you will
//need to download/import. You can also look at the
//Expo.html file that I will attach the link for at
//the end to see if you can do it in a different way.
}
while(answer1 == 'N')
{
System.out.println("\nThank you for your input.");
break;
}
Now, that might work, but let me know if it doesn't.
Okay, I cannot find the link, but here is the information on the Expo.enterChar() that you might need:
enterChar()
Allows input of a char from the keyboard in a text window.
Example:
System.out.print("What is your middle initial? --> ");
char middleInitial = Expo.enterChar();
Retrieves the first character entered at the keyboard and stores it in the char variable middleInitial.

No idea whats wrong... (change machine)

I just started coding in java and I am working on a change machine-esk program. I know It can be condensed but Its part of the constraints.
It keeps out putting random change owed and quarter count...
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
double costVar, paidVar, amountOwed;//user defined
//defining the vale of US coins
final double quarterCoin = 0.25;
final double dimeCoin = 0.10;
final double nickelCoin = 0.05;
final double pennyCoin = 0.01;
//Variable for math stuff
double quarterAmountdec, dimeAmountdec, nickelAmountdec, pennyAmountdec;
short quarterAmountfin, dimeAmountfin, nickelAmountfin, pennyAmountfin;
Scanner keyboard = new Scanner(System.in);
//ask the user to input costs and amount payed (assuming the amount paid is > or = the cost of the item)
System.out.println("Enter Item Cost: ");
costVar=keyboard.nextDouble();
System.out.println("Enter Amount Paid: ");
paidVar=keyboard.nextDouble();
amountOwed = paidVar - costVar;//math for the changed owed
System.out.println("\nChange Owed: $" +amountOwed++);//displaying how much change the machine owes
//math to calculate the coins owed (involves intentional loss of accuracy
quarterAmountdec = amountOwed / quarterCoin;
quarterAmountfin = (short)quarterAmountdec;
//outputs coins owed
System.out.println("Quarters: " +quarterAmountfin++ );
}
}
Output:
Enter Item Cost:
2.34
Enter Amount Paid:
6.89
Change Owed: $4.55
Quarters: 22
The following line alters the amount owed after printing
System.out.println("\nChange Owed: $" +amountOwed++);
Thus when printing the amount owed looks fine, but internally the value is changed. I am personally unsure of the behaviour of calling ++ on a double, however I recommend removing the ++ and re-running your code.

Is this the correct syntax for inputing a string to an if statement or am i completely off?

package travelCost;
import java.util.Scanner;
public class travelCost {
public static void main(String[] args) {
//Scanner function
Scanner in = new Scanner(System.in);
//define problem variables
//first
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
//Here i want the user to input a string and then based upon the answer //section into the for loop
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec"))
{
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance/milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ", totalCostElec);
} else if (type.equals("gas: ")
{
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance/mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
}else
{
System.out.println("Please resubmit entry");
}
System.out.println();
}
}
After the corrections which mentioned by Paul, here is the complete code:
travelCost.java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance / milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ",
totalCostElec);
} else if (type.equals("gas")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance / mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
} else {
System.out.println("Please resubmit entry");
}
System.out.println();
}
Input:
elec 100 10 2
Output:
The trip is going to cost $20.00:
make it
else if (type.equals("gas"))
There are 4 problems with this:
The line } else if (type.equals("gas: ") needs another ) at the end.
In the "gas" case, you are using the variable distance but you do not give it a value.
While if (type.equals("elec")) is the correct syntax (answering your question), it is usually better to write if ("elec".equals(type)) because this will not throw a NullPointerException if type == null.
It should be "gas", not "gas: ".
As Paul mentions, your if statement syntax is correct, but it is good practice to start with the hard coded strings ("elec" and "gas") in order to avoid NullPointerExceptions. As mentioned in the other answers, the if else should be using "gas" instead of "gas: ". To help avoid those kinds of errors, you might consider making "elec" and "gas" into static final String constants. If you use constants, you'll know that they are the same throughout your program. You might also want to call type.toLowerCase() in the event that the user enters the response in uppercase.

I am stuck on homework assignment Commission Calculation

I need to compare the total annual sales of at least three people. I need my app to calculate the additional amount that each must achieve to match or exceed the highest earner. I figured out most of it and know how to do it if there were only two people in the scenario, but getting third into the equation is throwing me for a loop! Any help is appreciated and thanks in advance! Here's what I have so far, but obviously at the end where the calculations are not going to be right.
package Commission3;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
// Create a new object AnnualCompensation
Commission3 salesPerson[] = new Commission3[2];
// creat two object
salesPerson[0] = new Commission3();
salesPerson[1] = new Commission3();
salesPerson[2] = new Commission3();
//new scanner input
Scanner keyboard = new Scanner(System.in);
//get salesperson1 name
System.out.println("What is your first salesperson's name?");
salesPerson[0].name = keyboard.nextLine();
//get salesperson1 sales total
System.out.println("Enter annual sales of first salesperson: ");
double val = keyboard.nextDouble();
salesPerson[0].setAnnualSales(val);
//get salesperson2 name
System.out.println("What is your second salesperson's name?");
salesPerson[1].name = keyboard.next();
//get salesperson2 sales total
System.out.println("Enter annual sales of second salesperson: ");
val = keyboard.nextDouble();
salesPerson[1].setAnnualSales(val);
//get salesperson3 name
System.out.println("What is your third salesperson's name?");
salesPerson[2].name = keyboard.next();
//get salesperson3 sales total
System.out.println("Enter annual sales of third salesperson: ");
val = keyboard.nextDouble();
salesPerson[2].setAnnualSales(val);
double total1, total2, total3;
total1 = salesPerson[0].getTotalSales();
System.out.println("Total sales of " + salesPerson[0].name +" is: $" + total1);
total2 = salesPerson[1].getTotalSales();
System.out.println("Total sales of " + salesPerson[1].name +" is: $" + total2);
total3 = salesPerson[2].getTotalSales();
System.out.println("Total sales of " + salesPerson[2].name +" is: $" + total3);
if (total1 > total2) {
System.out.print("Salesperson " + salesPerson[2].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[0].name);
System.out.println(" $" + (total1 - total2));
} else if (total2 > total1) {
System.out.print("Salesperson " + salesPerson[0].name + "'s additional amount
of sales that he must " + " achieve to match or exceed the higher of the
salesperson " + salesPerson[1].name);
System.out.println(" $" + (total2 - total1));
} else {
System.out.println("Both have same compensation $" + total1);
}
}
}
When you take the input from the user, keep track of the highest sales thus far, and the name of the salesperson with the most sales.
Then, instead of checking total1 and total2, you can loop through all three, and compare them to the max. If the current total is less than the max, then calculate the difference. Otherwise, the current total is equal to the max, and you don't need to do the calculation.
I'll leave the actual code for you to figure out.

Categories