Calculating Gas Mileage efficiency - java

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.

Related

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

Java compiler is telling me I have not initiated variable "interest" or "pmt"

I am trying to program an amortization calculator in which the user can enter a value for balance, a value for their interest rate in decimal form, and a value for monthly payment. With this information I want to output an interest amount in dollars, a principal amount, and a new balance. Here is my code:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner pmt, interest, balance = new Scanner(System.in);
System.out.println("What is your balance?");
double b = balance.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = interest.nextDouble();
System.out.println("What is your monthly payment?");
double p = pmt.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
You should not declare 3 scanners to read from the standard input. Declare one and just keep reading from it. Like this:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println("What is your balance?");
double b = input.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = input.nextDouble();
System.out.println("What is your monthly payment?");
double p = input.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
The main point here is that a scanner is the object that reads from an input stream, not the value being read. You don't need a new scanner for every value you want to read.
As #nhouser9 says, you don't need three scanners and answering your question the compiler says that the variables are not initialized because you are only initializing the last of them (balance). Multiple initializing in java won't functions as you expected (initialize all the variables with the same value).

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

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

monthly payment calculator

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

Categories

Resources