I must Implement a class Car with the following properties. A car has a certain fuel efficiency (measured in miles/gallon or liters/km—pick one) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor, and the initial fuel level is 0. Supply a method drive that simulates driving the car for a certain distance, reducing the amount of gasoline in the fuel tank. Also supply methods getGasInTank, returning the current amount of gasoline in the fuel tank, and addGas, to add gasoline to the fuel tank.
I have created a class for the car and a test program to plug some values in and when i run the program all i get returned is the addGas value that i put in. the computation for the miles per gallon will not run and i do not understand why. as you can probably tell i am VERY new at java and any help on the issue is much appreciated.
public class CarTest
{
public static void main(String[] args)
{
Car richCar = new Car(49);
richCar.addGas(15);
richCar.drive(150);
System.out.println(richCar.getGas());
}
}
/**
A car can drive and consume fuel
*/
public class Car
{
/**
Constructs a car with a given fuel efficiency
#param anEfficiency the fuel efficiency of the car
*/
public Car(double mpg)
{
milesPerGallon = mpg;
gas = 0;
drive = 0;
}
/** Adds gas to the tank.
#param amount the amount of fuel added
*/
public void addGas(double amount)
{
gas = gas + amount;
}
/**
Drives a certain amount, consuming gas
#param distance the distance driven
*/
public void drive(double distance)
{
drive = drive + distance;
}
/**
Gets the amount of gas left in the tank.
#return the amount of gas
*/
public double getGas()
{
double mpg;
double distance;
distance = drive;
mpg = gas * milesPerGallon / distance;
return gas;
}
private double drive;
private double gas;
private double milesPerGallon;
}
Combining some ideas...
/**
Drives a certain amount, consuming gas
#param distance the distance driven
*/
public void drive(double distance)
{
drive = drive + distance;
gas = gas - (distance / milesPerGallon);
}
/**
Gets the amount of gas left in the tank.
#return the amount of gas
*/
public double getGas()
{
return gas;
}
Your test program only calls three methods:
richCar.addGas(15);
richCar.drive(150);
System.out.println(richCar.getGas());
Let's take a look at what each one does.
addGas(15) modifies your gas instance variable.
drive(150) only executes the line drive = drive + distance;
getGas() seems to do a couple things, more than expected (one would expect it just returns gas but it also calculates and stores latest mpg value). But if you check the code of getGas() gas is never modified, only returned.
So you called three methods, and within those three executions gas is only modified once, when you set it to the value of 15 with richCar.addGas(15).
It would seem most simple if the drive(int) method modifys gas based on some set mpg value, instead of only keeping track of how many miles were driven, and then you could have drive() simply just return gas.
That means you would also get rid of modifying mpg in getGas(), which is good, because that value is needed no matter what to calculate how much gas is used. You could perhaps introduce a actualMpg value if you had some more logic that changed how much gas is used but you don't have that yet.
It's computing it just fine. Your method is only returning the one value for gas, though.
This could use some clean-up; I'd suggest getting rid of all of the cruft, and just returning the calculation.
public double calculateGas() {
return (gas * milesPerGallon) / drive;
}
From what it looks like your problem lies here
public double getGas()
{
double mpg;
double distance;
distance = drive;
mpg = gas * milesPerGallon / distance;
return gas;
}
you are doing a calculation to mpg however you are returning the gas property at the end.
It doesn't actually seem like you are changing the value of gas anywhere except for when you first add it.
Related
I'm new to programming and I am making an electronic store in java which requires a product class.
The function I'm struggling with:
double sellUnits(int amount) – simulates selling amount units. If there are
enough units in stock to meet the request, the quantity attributes must be
updated appropriately and the total revenue for selling (revenue = units *
price) should be returned. If there are not enough units in stock, no sale
should take place and 0.0 should be returned.
I'm not quite sure how to check if there are enough units in stock to meet the request. I'm selling desktops, laptops, and fridges, and all of them will be contained in a products array. What I have right now under the function is just a placeholder, I'm not sure how to approach this issue.
public class Product {
double price;
int stockQuantity;
int soldQuantity;
public Product(double p, int stkquantity){
price = p;
stockQuantity = stkquantity;
}
public double sellUnits(int amount){
if(balance <= amount){
amount -= balance;
return true;
}
return 0.0;
}
}
In your sell function you return to different types. That causes an error.
You also need to initiate the sold qunatitiy.
This should do it.
public class Product {
double price;
int stockQuantity;
int soldQuantity = 0;
public Product(double p, int stkquantity){
price = p;
stockQuantity = stkquantity;
}
public double sellUnits(int amount){
if(stockQuantity >= amount){
stockQuantity -= amount;
soldQuantity += amount;
return price * amount;
}
return 0.0;
}
}
Think about how you would do this manually. Imagine you owned a store, and you received an order. You want to know if you can actually perform the order.
Well, you either already know you have 10 laptops available, or you would go count them. It's easier to keep a post-it note near the register saying "10 left" and then replace it with "8 left" when two are sold, although you need to make sure you keep it up to date.
Your program is going to work the same way.
So using your class above, your sellUnits method needs to see if you're trying to sell more than you have. if (amount > stockQuantity) then someone is trying to buy more than you have. Return 0 because you want to say, "We can't sell that many, but we have 8 instead of 10". Or whatever.
But if you have enough, then you subtract from stockQuantity the number you just sold, increment the soldQuantity, and return quantity * price.
Almost always, when figuring out basic algorithms, you can reliably think, "How would I do this manually myself". That will clue you in quite a bit.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Create a class studentBilling() that includes three return overloaded calculateBill() methods as follows:
The first calculateBill() method will receive the tuition fees as single parameter. Add 14% tax to the tuition fees and return the total due.
The second calculateBill() method receives the tuition fees and the cost of textbooks. Add the two values and then add 14% tax and return the total due.
The third calculateBill() method receives the tuition fees, textbook costs and a coupon value. Add the tuition and cost of textbooks and subtract the coupon value. Add 14% tax and return the total due.
Write a program billTesting that tests all three overloaded methods.
Create a new studentBilling object.
Create a Scanner object to enter the tuition fees, textbook costs, and the coupon value.
Call the three methods and display the results.
my solution
package student;
import java.util.Scanner;
/**
*
* #author FASA
*/
public class Student {
double totalDue;
static Scanner fees = new Scanner(System.in);
double Student;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner fees = new Scanner(System.in);
System.out.println(CalculateBill1());
System.out.println(CalculateBill2());
System.out.println(CalculateBill3());
}
public static double CalculateBill1 (double totalDue, double tax, double fees) {
tax = 0.14;
return (totalDue);
}
public double CalculateBill2 (double fees, double textBookFees) {
double tax = 0.14;
Student = fees + textBookFees + tax;
return (totalDue);
}
public double CalculateBill3 (double tax, double fees, double textBookFees, double couponValue) {
Student = fees + textBookFees - couponValue + tax;
return (totalDue);
}
}
It wont print the bill, please help
I am not going to help you with the complete solution as it seems to be your homework ;)
You should get compilation error on lines System.out.println(CalculateBill1());
System.out.println(CalculateBill2());
System.out.println(CalculateBill3()); because there is no method with definition as void parameter.
you need to pass appropriate parameters to call these methods. For example to call method "CalculateBill1 (double totalDue, double tax, double fees)" you need to call it like below:
System.out.println(CalculateBill1(1.25,5.23,6.0));
Hope this help.
Running into a problem. I have two methods with for each loops that calculates executives pay either by percentage or base pay. In my Executive class I have my pay method that takes base pay rate and multiplies with bonus. This works if it's percentage but if its base pay and call this method doesn't work.
Do I have put a if statement in my executive class to see if it's percentage or base pay?
Staff Class
/**
* Assigns the specified flat value weekly bonus to the Executives.
*
* #param bonusValue
* as a double, i.e., $1,000 = 1000.0
*/
public void setExecutiveBonusFlatRate(double bonusValue) {
for (StaffMember executiveEmployee : staffList) {
if (executiveEmployee instanceof Executive) {
((Executive) executiveEmployee).setBonus(bonusValue);
}
}
}
/**
* Assigns the specified percentage weekly bonus to the Executives.
*
* #param bonus
* as a percentage, i.e., 20% = 0.2
*/
public void setExecutiveBonusPercentage(double bonusPercentage) {
for (StaffMember executiveEmployee : staffList) {
if (executiveEmployee instanceof Executive) {
((Executive) executiveEmployee).setBonus(bonusPercentage);
}
}
}
/**
* Pays all the staff members.
*/
public void payday() {
for (StaffMember allEmployee : staffList) {
allEmployee.toString();
System.out.println(allEmployee.pay());
System.out.println(allEmployee.toString());
}
}
From Executive class extended from Employee
/** #overide
* return the weekly payrate plus the bonus
*/
public double pay() {
double payment = payRate * bonus;
bonus = 0;
return payment;
We need to correct two things here:
setExecutiveBonusPercentage should set the bonus as base * percentage * 0.01 to be consistent with bonusValue set in setExecutiveBonusFlatRate as we have no way to know whether bonus is a value or percentage.
In pay() method, we are setting bonus to 0 (bonus = 0;) which needs to be removed as it resets the bonus value. Due to this, first call of pay() will return correct result whereas subsequent calls will return 0.
I am doing an assignment for class and we just started making our own methods and what I thought seemed easy enough has become extremely frustration and hoping you can help me wrap my head around it.
First things first and the assignment I am trying to complete is this: make a modular program to calculate monthly payments, seems easy but the few restrictions on this question is as follows
The main method should:
Ask the user for
the loan amount
the annual interest rate ( as a decimal, 7.5% is 0.075 )
the number of months
And
call a method to calculate and return the monthly interest rate (annual rate/12)
call a method to calculate and return the monthly payment
call a method to print a loan statement showing the amount borrowed, the annual interest rate, the number of months, and the monthly payment.
I have gotten to the end of just printing out the loan statement but cant for the life of me the proper way to call it, and make it show up once I run the program :/ so if you can help me understand how its done I would greatly appreciate it.
(I realize that there are probably other mistakes in my code but for right now I would rather just focus on what I need to get done)
import java.util.Scanner;
public class LoanPayment {
/**
* The main method declares the variables in program while getting the user
* info of amount loaned, interest rate of the loan, and the loans duration.
*
* The main method also calls other methods to calculate monthly interest
* monthly payments and the output of the loan statement
*/
public static void main(String[] args)
{
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
} // end main ()
/******************************************************************************/
// this class calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
/******************************************************************************/
// this class calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
/******************************************************************************/
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);
If // call method to print loan statement is all you have left to do, then this is what you need on the line below it:
loanStatement(principle, interest, time, mPayment);
And it should work fine.
Your other methods have non-void return types, so you put someVariable = yourMethod(yourArguments) in order to accept the return value. However, loanStatement has a void return type. You don't need to do this. You can call it simply as I showed above and it will execute the code in the method.
Though, my personal preference would be to change loanStatement to a String return type and put the print statement in main and print the return of loanStatement. Methods that return Strings almost as easily and are more flexible for future use (for example, if you wanted to allow your program to also write to file, you need two loanStatement methods, or to completely rework loanStatement).
Check out this solution ;)
public class LoanStatement{
public static void main(String []args){
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
loanStatement(principle,interest,time,mPayment);
}
// this method calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
// this method calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);
}
}
Iam doing a school assignment in Java, and I need some help to do some calculations in a method. Iam used to PHP, and I've appended a lot of my knowledge in the code, but this one I just cant figure out (I know how do do it without the function, but that requires much more lines of code which is stupid).
Here is some of my code:
public static void main (String[] args) {
// User inputs
calculate("Number of beers", 20, 1.50);
}
public static void calculate(String articleName, double numberOfX, double pricePerUnit) {
double subTotal = numberOfX * pricePerUnit;
System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal);
}
This prints out a nice bill of the things I've bought. Furthermore I would like this method to add the totalprice to a (global?) variable which eventually shows the final price of all items. In PHP i usually wrote a variable named totalDue += subTotal;
Is there any way to do this in java? I would be a shame to write an entire new function to do the math if I just could add the total price of each item into a variable.
Global variables don't exist in Java.
And this is not how it should be done. Rather than the method updating some variable, the method should just return the result of the computation, and the caller should be responsible of using the result as he wants to:
double total = 0D;
total += calculate("Number of beers", 20, 1.50);
total += calculate("Number of pizza", 10, 8);
// ...
This way, you won't have to change anything in the calculate method when you'll want to compute subtotals, or averages, or anything. One method = one responsibility.
This should be true for your PHP programs as well.
After this is done, you should encapsulate the article name, number of items, and unit price in a class, and add methods to the class, like toString (to display the bought item), and computePrice (to compute the price of this bought item).
public static void main (String[] args) {
// User inputs
double total = 0.0;
total += calculate("Number of beers", 20, 1.50);
}
public static double calculate(String articleName, double numberOfX, double pricePerUnit) {
double subTotal = numberOfX * pricePerUnit;
System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal);
return subTotal;
}