Reputation: 1
I am taking an intro to Java programming and I have the below assignment. I think my code is correct but I get the wrong answer. I need to find the total cost for each car, and "buy" the cheaper one. Suppose that I am traveling 50000 miles:
gas cost = (Miles driven / Mpg) * Fuel cost
total cost = Purchase price + gas cost
and here is my code:
public class Test
{
public static void main(String[] args)
{
int milesDriven = 50000;
int mpg1 = 10;
int mpg2 = 50;
int pricePerGallon = 4;
int purchasePrice1 = 15000;
int purchasePrice2 = 30000;
int gasCost4Car1 = (milesDriven / mpg1) * pricePerGallon;
int gasCost4Car2 = (milesDriven / mpg2) * pricePerGallon;
int total4Car1 = (purchasePrice1 + gasCost4Car1);
int total4Car2 = (purchasePrice2 + gasCost4Car2);
if(total4Car1 < total4Car2)
{
System.out.println(total4Car1 + gasCost4Car1);
}
else
{
System.out.println(purchasePrice2 + gasCost4Car2);
}
System.out.println(purchasePrice2 + gasCost4Car2); // just to see the output for car 2
}
}
The output I get is 34000 and I believe that for car 1 the output should be 35000 and the output for car 2 should be 34000 I don't understand I am getting the wrong answer. Note: I can't post pictures (for reputation reasons) nor videos, but I am willing to provide that information if needed. Thank you.
Upvotes: 0
Views: 112
Reputation: 1541
Cleaned up a little bit, gives correct results:
public static void main(String[] args) {
int milesDriven = 50000;
int mpg1 = 10;
int mpg2 = 50;
int pricePerGallon = 4;
int purchasePrice1 = 15000;
int purchasePrice2 = 30000;
int gasCost4Car1 = milesDriven / mpg1 * pricePerGallon;
int gasCost4Car2 = milesDriven / mpg2 * pricePerGallon;
int total4Car1 = purchasePrice1 + gasCost4Car1;
int total4Car2 = purchasePrice2 + gasCost4Car2;
System.out.println("Total car 1: " + total4Car1);
System.out.println("Total car 2: " + total4Car2);
if (total4Car1 < total4Car2) {
System.out.println("Car 1 is cheaper: " + total4Car1);
} else {
System.out.println("Car 2 is cheaper: " + total4Car2);
}
}
Upvotes: 0
Reputation:
total4car1 is not less than total4car2, so it prints the total for car 2 i.e. purchaseprice2 + gascost4car2
, and then it prints it again in System.out.println(purchasePrice2 + gasCost4Car2); // just to see the output for car 2
. What should be output?
Upvotes: 0
Reputation: 726599
The problem is on this line:
System.out.println(total4Car1 + gasCost4Car1);
total4Car1
already includes gasCost4Car1
.
Here is a demo on ideone printing 34000
.
Upvotes: 1