So, I have developed a class that is suppose to be used by another class. The class I developed is as follows:
public class Car
{
private double milesPerGallon;
private double gas;
//Constructs a car with a given fuel efficiency
public Car(double milesPerGallon)
{
gas = 0.0;
}
//Increases the amount of gas in the gas tank
public void addGas(double amount)
{
gas = gas + amount;
}
//Decreases the amount of gas in the gas tank (due to driving and therefore consuming gas)
public void drive(double distance)
{
gas = gas - (distance / milesPerGallon);
}
//Calculates range, the number of miles the car can travel until the gas tank is empty
public double range()
{
double range;
range = gas * milesPerGallon;
return range;
}
}
The class that is suppose to use the class I developed is:
public class CarTester
{
/**
* main() method
*/
public static void main(String[] args)
{
Car honda = new Car(30.0); // 30 miles per gallon
honda.addGas(9.0); // add 9 more gallons
honda.drive(210.0); // drive 210 miles
// print range remaining
System.out.println("Honda range remaining: " + honda.range());
Car toyota = new Car(26.0); // 26 miles per gallon
toyota.addGas(4.5); // add 4.5 more gallons
toyota.drive(150.0); // drive 150 miles
// print range remaining
System.out.println("Toyota range remaining: " + toyota.range());
}
}
Both classes compile successfully, however when the program is run I get the output "NaN," which stands for "Not a Number." I looked this up and supposedly it occurs when there is a mathematical process that attempts to divide by zero or something similar. I am not, I repeat, not looking for the answer, but a nudge in the right direction about where I might be making my mistake would be much appreciated (I'm sure it's a very small and stupid mistake). Thanks!
save your milesPerGallon variable at constructor:
public Car(double milesPerGallon)
{
this.milesPerGallon = milesPerGallon;
gas = 0.0;
}
milesPerGallon needs to be initialized to the constructor parameter.
Constructor:
public Car(double milesPerGallon)
{
this.milesPerGallon = milesPerGallon;
gas = 0.0;
}
milesPerGallon is used later but never initialized.
It seems as though you did not initialize milesPerGallon. The variable you accept in the constructor is different than the private variable you initialized at the top of your class. Typically people like to use something like public car(aMilesPerGallon) to make sure they know the difference. Or as the answer that was posted while I was typing says, this.milesPerGallon references the variable at the top of the class.
You aren't setting milesPerGallon in your constructor, thus it is initialized to 0.0. Are you dividing something by that variable somewhere?
You are not initializing milesPerGallon in your Car constructor. So it is taking 0.0 as default value. And when a number is divided by 0.0 you're getting NaN.
Related
I'm extremely new to Java, and I'm trying to understand why an output of the main method of the Magic class for this code is "TT". Our professor said we don't have to understand the meaning of this method, but just answer the output.
The code is this.
public class Magic
{
public static void main(String[] args)
{
final String MSG = "Good Restaurant Seattle";
Stock stock = new Stock("HR.S");
double price = stock.getPrice();
int cent = (int) Math.rint(price);
System.out.println(MSG.substring(cent, cent+2).toUpperCase());
}
}
I understand where it took the letters from and how all variables such as cent and price are connected, but I don't understand what "HR.S" is and how it's connected to the output.
In order for MSG.substring(cent, cent+2).toUpperCase() to return TT, the value of cent has to be 20.
....:....1....:....2...
Good Restaurant Seattle
^^
In order for cent to be 20, the value of price must be 19.5 <= price <= 20.5.
Which means that stock.getPrice() returned a value between 19.5 and 20.5 (inclusive).
Not knowing what class Stock does, we cannot say how it figured out that input "HR.S" should have such a price.
So I created Saving class, created also setters and getters. Now I need u method, which will calculate the total amount of deposits.
public class Saving {
private double deposits;
private double totalAmountOfDeposits;
public double getDeposits()
{
return deposits;
}
public void setDeposits(double deposits)
{
this.deposits = deposits + deposits;
}
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
}
When I use this class in the program I got a wrong calculation. The program just add first value of deposit to the first value.
import java.util.Scanner;
public class SavingDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Saving save = new Saving();
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
}
}
And here is the output:
Deposit amount
12
Deposit amount
34
Deposit amount
56
The total amount has been deposited is 24.0
As you can see its just added 12 to 12. Just want to mention that I'm totally new in programming. Les than a month.
I see two problems in your code. Take a look at the commented line. The reason you are seeing 12 + 12 is because that is exactly what you are instructing the JVM to do.
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
Secondly, it looks like you may have a design flaw in your implementation of the Saving class.
You'll want to brush up on variable scope
If you take a look at your implementation on your total:
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
You have the total starting at 0 every time this method getTotalAmountOfDeposits() is called. the total variable in this method is local to it's method. So what you currently have is a method variable
You'll want to do some research into class variable. This will maintain that the instance of the object will have this variable assigned through the life cycle of the instantiated object.
When you have variables of the same name, you can get the instance variable with this keyword.
So when dealing with your setter
public void setSomething(double something) {
this.something // class variable
something // method variable
}
If you want your object to maintain state, you can set it on your object itself, and have your set deposit modify that state. Some pseudo code to get you moving forward.
public class Saving {
private double totalAmountOfDeposits; // you can modify this value with public methods
public void setDeposit(_) {
// Setter implementation
// increment totalAmountOfDeposits;
public double getTotalAmountOfDeposits(_)
// return totalAmountOfDeposits;
}
You should write a method
public void addDeposits(double deposits)
{
this.deposits = this.deposits + deposits;
}
and change setDeposits to
public void setDeposits(double deposits)
{
this.deposits = deposits;
}
after this call addDeposits to add deposits
To eliminate confusion within the Saving Class change the argument name for the setDeposits() method to double newDeposit instead of double deposits which is also a class field name. Although the construct is legal it does make it a wee bit confusing. Inside the setDeposits() method use:
this.deposit+= newDeposit;
As a matter of fact, you can get rid of the deposits field altogether since you also have the field named totalAmountOfDeposits. Use that instead:
this.totalAmountOfDeposits+= newDeposit;
You might also want a clearDeposits() method in your Saving Class:
public void clearDeposits() {
this.totalAmountOfDeposits = 0.0;
}
Your getTotalAmountOfDeposits() method within the Saving Class doesn't really make any sense either. Since you are always summing deposits anyways you can just return what is held within the totalAmountOfDeposits field:
public double getTotalAmountOfDeposits() {
return totalAmountOfDeposits;
}
The above method is would now of course be very mush the same as the getDeposits() method which could be changed to getTotalDeposits(). You can then change the getTotalAmountOfDeposits() method name to getTotalNumberOfDeposits() and add a additional class field named numberOfDeposits:
private double totalAmountOfDeposits;
private int numberOfDeposits = 0;
public double getTotalDeposits() {
return totalAmountOfDeposits;
}
public int getTotalNumberOfDeposits() {
return numberOfDeposits;
}
and in your setDeposits() method add the code line:
numberOfDeposits++;
So that it would look something like:
public void setDeposits(double newDeposit) {
totalAmountOfDeposits+= newDeposit;
numberOfDeposits++;
}
If you do add a clearDeposits() method to your Saving Class then don't forget to add the code line: numberOfDeposits = 0; into that method as well. It might now look something like:
public void clearDeposits() {
totalAmountOfDeposits = 0.0;
numberOfDeposits = 0;
}
You also have some issues within your main() method of your SavingDemo Class. Take a real close look at each call you make to the setDeposits() method for each value the User supplies. Each User supplied value goes into a specific double type variable name. Is that what you are passing to the setDeposits() method? ;)
Once you've got all that taken care of you can display to console:
System.out.println("The total amount has been deposited is " +
save.getTotalDeposits() + " by making " +
save.getTotalNumberOfDeposits() + " deposits.");
I calculate an integer and assign it into an array using a method inside a for loop, then the next method in that for loop needs the previous integer calculated as a parameter I declared it as an double which fixed that problem but now I need to print the result and I have the same problem, what do i put in the method parameters when printing because the variable was wiped after every loop in the first loop.
This is the main method class :
public class AnnualFuelTester {
public static void main(String args[]) {
//declaration of variables
int endMiles, startMiles;
double gallonsUsed, pricePerGallon;
//initialization of an array of objects
AnnualFuelUse[] fillUps = {
new AnnualFuelUse(45023, 45231, 10.00, 2.95),
new AnnualFuelUse(45231, 45480, 11.70, 2.99),
new AnnualFuelUse(45480, 45659, 9.30, 3.03),
new AnnualFuelUse(45659, 45961, 14.90, 3.05)
};
//call methods
for (int index = 0; index < fillUps.length; index++) {
double distance = fillUps[index].calcDistance();
fillUps[index].calcMPG(distance);
fillUps[index].getStartMiles();
fillUps[index].getEndMiles();
fillUps[index].getGallons();
fillUps[index].totalCost(distance);
}
//print results
System.out.printf(" %15s %15s %15s %15s %15s %15s %15s %15s %15s", "Fill Up", "Days", "Start Miles", "End Miles", "Distance", "Gallons", "Miles/Gal", "Gallons/Miles", "Price", "Total Cost\n");
for (int index = 0; index < fillUps.length; index++) {
System.out.printf("%15i %15i %15s %15s %15d %15d %15d %15d %15d", index, index, fillUps[index].getStartMiles(), fillUps[index].getEndMiles(), fillUps[index].calcDistance(), fillUps[index].getGallons(), fillUps[index].calcMPG(distance), fillUps[index].totalCost(distance), "\n");
}
}
}
This is the Class with the methods:
public class AnnualFuelUse {
//private instance variables
private int myEndMiles, myStartMiles;
private double myGallonsUsed, myPricePerGallon;
AnnualFuelUse(int sm, int em, double gu, double ppg) {
myEndMiles = em;
myStartMiles = sm;
myGallonsUsed = gu;
myPricePerGallon = ppg;
}
//distance driven
public double calcDistance() {
return myEndMiles - myStartMiles;
}
//calculate miles per gallon
public double calcMPG(double distance) {
return distance / myGallonsUsed;
}
//calculate gallons per mile
public double calcGPM(double distance) {
return (distance / myGallonsUsed) / 100;
}
//calculate total cost
public double totalCost(double distance) {
return myPricePerGallon * distance;
}
//getter start miles
public int getStartMiles() {
return myStartMiles;
}
//getter end miles
public int getEndMiles() {
return myEndMiles;
}
//getter gallons used
public double getGallons() {
return myGallonsUsed;
}
//getter price per gallon
public double getPricePerGallon() {
return myPricePerGallon;
}
}
The instructions for this program are
If you have not yet created the 8.08 Annual Fuel Use project in the Mod08
Assignments folder, please do so now.
Be sure to save a copy of these instructions in the Mod08 Documents folder.
Print a copy for your notebook.
Read the instructions carefully before you attempt the assignment.
Create two classes called
AnnualFuelUseTester and AnnualFuelUse
in the newly created project folder.
Use the fill up data you have been collecting
for your car (or the family car) and calculate
the total distance, gallons used, and cost of
gas.
Determine the minimum and maximum
values for distance, miles per gallon and
price. (Recall the Integer class constancies
MIN_VALUE and MAX_VALUE. The
Double class also has class constants of the
same name.)
Calculate annual projections for distance,
gallons used, miles per gallon, and cost
based on the data you collected.
Each fill up should be considered an object and your program design should be
based on an array of objects. Use the demo program in this lesson as a model for
how to create and process an array of objects.
If you are basically expecting the value calculated in .calcDistance() method, Have your method .calcDistance() return a value (the one you require).
Store it in a variable or directly pass that to the second called function .clacMPG()
As you are already returning a value from .calcDistance() you can do something like
int dist = fillUps[index].calcDistance();
and now you can use this dist value in any other method calls you make, like
fillUps[index].calcMPG(dist);
you can basically use one variable which will get overwritten every time the loop runs.
Use another variable:
int dist=fillUps[index].calcDistance();
//or double, depands on the method's returning value
fillUps[index].calcMPG(dist);
Assuming that AnnualFuelUse constructor arguments are: start miles (odometer), end miles, gallonsUsed and pricePerGallon.
One way to do this is returning the distance and passing as argument to the next:
int distance = fillUps[index].calcDistance();
fillUps[index].calcMPG(distance);
I can't see in your code how you are consolidating data and how you're projecting future data.
**Ok. Based on your "edit", now I know that you don't have a question, You want someone to do your homework for you!!! **
I found this Java exercise :
Create a class Sales that has TotalSales (double) , Commission (double),
Commissi onRate (double), and NoOfItems (integer).
write a java application that asks the user to enter the Total Sales and the number of items then calculates the commission and prints it out.
The commission rate should be as following:
Condition :
Less than 500, commissionRate is 0
Greater than or equal 500 or Number of Items >= 5, commission rate is 5%.
Grater than or equal 1000 or Number of items >=10, commission rate is 10%
..
I wrote this code:
Main Class :
import java.util.Scanner;
public class testSales {
public static void main(String[] args) {
Sales s1 = new Sales();
Scanner get = new Scanner(System.in);
System.out.println("Enter total Sales");
s1.totalSale = get.nextDouble();
System.out.println("Enter number of Items");
s1.NoOfItems = get.nextInt();
if(s1.totalSale < 500){
s1.commission = s1.commissionRate = 0;
}
else if(s1.totalSale >= 500 && s1.totalSale <= 999 || s1.NoOfItems >= 5 && s1.NoOfItems <=9){
s1.commission = s1.commissionRate = s1.totalSale * 5 / 100;
}else if(s1.totalSale >= 1000 || s1.NoOfItems >=10) {
s1.commission = s1.commissionRate = s1.totalSale *10/100;
}
System.out.println(s1.commission);
}
}
One problem in your code is the case where NoOfItems > 5 but totalSale < 500. For this case, the commission will incorrectly be set to 0 because the first if statement eats it.
Please try to be more specific with your question. "this doesn't work and I don't know why" is not easy to help with.
Aside from the point brought up by HedonicHedgehog, there are a few other things to consider:
The sales class only has two global variables, which corresponds to the information entered by the user. The other two fields, commission and commissionRate, are calculated values. Therefore, there is no need to create variables for them. Just add to the sales class accessor methods (getters) that return these values. For example, below is my getCommission() method:
public double getCommission()
{
return totalSales * getCommissionRate();
}
Of course, you can see this method is dependent upon the getCommissionRate() method. Because there is a gap on your requirements with total items, I am ignoring it for now:
public double getCommissionRate()
{
if (totalSales < 500)
return 0;
if(totalSales < 1000)
return .05;
else
return 0.1;
}
Alternatively, you could create a LOCAL commission variable, and set the value before returning it. It is a good programming practice to limit the scope of your variables. In this case, there is not a good reason to have a global commission or commissionRate variables.
Lastly, your test class is simplified because all you need to do is to prompt the user for the two needed fields, and it simply spits out the output because the Sales class provides the calculation needed to figure out the rest:
public static void main(String[] args)
{
Sales s1 = new Sales();
Scanner input = new Scanner(System.in);
System.out.print("Enter total Sales");
s1.setTotalSales(input.nextDouble());
System.out.print("Enter number of Items: ");
s1.setNumOfItems(input.nextInt());
System.out.printf("$%.2f", s1.getCommission());
input.close();
}
I used the printf() method to format the output string. The following is a sample run:
Enter total Sales: 503.45
Enter number of Items: 5
$25.17
Enter total Sales: 1003.67
Enter number of Items: 19
$100.37
Enter total Sales: 45.00
Enter number of Items: 19
$0.00
Remember that this example ignores the number of items because of the reasons already mentioned. Once you figure out what needs to be done to cover of the gap in the requirements, you can modify this code to do the rest. Also remember that your Sales class only requires two fields: totalSales and numOfItems. The other to components (commission, and commissionRate) are calculated; therefore, no global variable or setter methods needed. Just the two getter methods I provided.
the error is in the CarUser class, required: double; found: no arguments; reason: actual and formal argument lists differ in length.
i do not understand how to return a range method from this code i made. i have the psuedocode for it, but i do not know how to turn it into a legit code. Also, can someone double check my other methods as well?
/**
* Class to determine Car's range of miles.
*
* #author Kelvynn Cayanan
* #version 2/2/2014
*/
public class Car
{
// instance variables -
private double miles;
private double gallons;
private double gas;
/**
* Constructor for objects of class Car
*/
public Car()
{
}
public Car(double initialGas)
{
gas = initialGas;
}
public void addGas(double gas)
{
// Increases amount of gas in gas tank.
gallons = gallons + gas;
}
public void drive(double drive)
{
// Decreases amount of gas in gas tank.
double newdrive = (drive/miles) - gas;
drive = newdrive;
}
public double range(double range)
{
//**calculates range, the number of miles the car can travel until the gas tank is empty */
double newrange = miles * gas;
range = newrange;
return range;
}
}
here is a class that i am supposed to implement with the class i made above.
/**
* Uses Cars.
*
* #author Anthony W. Smith
* #version 6/15/2009
*/
public class CarUser
{
/**
* Constructor for objects of class CarUser
*/
public CarUser()
{
Car honda = new Car(30.0); // 30 miles per gallon
honda.addGas(9.0); // add 9 more gallons
honda.drive(210.0); // drive 210 miles
// print range remaining
System.out.println("Honda range remaining: " + honda.range());
Car toyota = new Car(26.0); // 26 miles per gallon
toyota.addGas(4.5); // add 4.5 more gallons
toyota.drive(150.0); // drive 150 miles
// print range remaining
System.out.println("Toyota range remaining: " + toyota.range());
}
}
You're over-complicating things. Change the range method definition in the Car class, as it shouldn't have a parameter. Its signature and body should be nothing but:
public double range() {
return miles * gas;
}
What Hovercraft Full of Eels wrote was correct to a certain extent.
Here are some tips that I think will help you out in your planning process.
First Tip:
Think of your CarUser class as your guide towards creating an algorithm for the Car class.
You can think of an algorithm as a basic formula that your machine applies to specific input values in order to "Do something".
As an example:public double range() is a method whose job is to return a value back to the user. What does the user want returned regarding range? Is it range in gallons of gasoline or is it in miles?
(Hint: the one that requires less thinking)
First write on a piece of paper the information CarUser gives you using honda or toyota:
(Honda)Miles Per Gallon: 30.0
Starting Gas in Tank: 3.5 Gal
Amount of Gas Added: 9.0 Gal
Total Gas After Added: 12.5 Gal
There needs to be some type of formula we can apply in order to find this "Range"...it involves a little bit of multiplication and subtraction..
Another Tip that will help you out: Compile and Run each method in your new Car class in BlueJ before moving on to the next method. If you run Car by itself, it should probably prompt you to enter a Value which you can then Inspect (to see if the program is responding how you'd like it to).
A Third Tip: After compiling your Car class, try compiling your CarUser class and
BlueJ should point out your problems.
A Final Tip: YOUR VARIABLE NAMES AND METHODS SHOULD HAVE CLEAR & MEANINGFUL NAMES AND INCLUDED COMMENTS so when another programmer is looking at your work, they can tell what each method and variable is and does. That is one of the few reasons why addGas is used instead of aG.
Good Luck!