How to make calculation inside class field in Java? - java

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.");

Related

Why Are the Instance Variables Declared in the Main Method?

I'm learning Java on Codecademy and recently completed a project that calculates monthly payments for a car loan. The problem is that I don't understand the solution, and no one has responded to my question about it on the Codecademy forum.
Why are the instance variables created in the main method scope instead of just after the class has been declared? We haven’t seen any examples of this prior to this project and I don’t understand.
Here is the code:
//Calculates monthly car payment
public class CarLoan {
//Why aren't the variables created here rather than in the main method?
public static void main(String[] args) {
int carLoan = 10000;
int loanLength = 3;
int interestRate = 5;
int downPayment = 2000;
if (loanLength <=0 || interestRate <=0) {
System.out.println("Error! You must take out a valid car loan.");
} else if (downPayment >= carLoan) {
System.out.println("The car can be paid in full.");
} else {
int remainingBalance = carLoan - downPayment;
int months = loanLength * 12;
int monthlyBalance = remainingBalance / months;
int interest = (monthlyBalance * interestRate) / 100;
int monthlyPayment = monthlyBalance + interest;
System.out.println(monthlyPayment);
}
}
}
Variables defined within a method are local variables, they belong to an invocation of the method, not to an instance of an object.
The intent seems to be to provide an example that is understandable to beginners who haven't been introduced to constructors, instance variables, and methods. They want to teach local variable declaration, some simple calculating and if-statements, and printing to the console before getting into that other stuff.
As an exercise it would be fine for you to change the CarLoan class to give it instance variables, just to see another way to do it. Keep the variable values hard-coded, make an instance method that calculates the monthly payment, and have the main method print the result to the console.

Convert Height to Inches (Java)

I am having issues with the output of my code. Seems I am missing something in my method that I created... I had instructions to return the total number of inches. I places totInches after return and get an error stating that totInches is not a variable. Not certain what is missing here as I am only supposed to be creating a method. Most of this code was written and the only portion I was supposed to created was the second convertToInches method.. Any advice?
import java.util.Scanner;
public class FunctionOverloadToInches {
public static double convertToInches(double numFeet) {
return numFeet * 12.0;
}
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
public static void main (String [] args) {
double totInches = 0.0;
totInches = convertToInches(4.0, 6.0);
System.out.println("4.0, 6.0 yields " + totInches);
totInches = convertToInches(5.9);
System.out.println("5.9 yields " + totInches);
return;
}
}
The variable totInches is not defined in the scope of your function:
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
The only variables you can use in this function are the ones you create and the ones defined as formal parameters: numFeet and numInches. So you have to come up with an equation that takes numFeet and converts it to inches, taking into account the additional inches provided in numInches.
You declared the double variable "totInches" inside of your main method, but you are trying to access it inside of your "convertToInches" method. When declaring a variable in a particular method, that variable is ONLY accessible by that method. Your "convertToInches" knows of only two variables: numFeet and numInches, which you passed to it in the parameter. It then looks at your return statement, sees "totInches" and has no idea what it is.
I also don't understand what this is trying to do...
public static double convertToInches(double numFeet, double numInches) {
return totInches * 12.0;
}
Why are you passing it the double variables numFeet and numInches? The function isn't using them. I also don't understand why you need both the number of feet AND the number of inches if the method, by its name, is trying to convert something into inches.
public static double convertToInches(double numFeet, double numInches) {
return (numFeet * 12) + numInches;
This takes into account any variable amount entered by user for height of 5 feet 7 inches or 6 feet even

Output is "NaN"

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.

Abstract Concept Assignment [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So my questions are geared directly to my homework. Before you ask, yes I've looked at other questions and I have looked at the java docs to try and help me but I only understand so much..
You have become a restaurant mogul. You own several fast food chains. However, you now need to set a standard that all of your fast food chain must follow in order to have your software be uniform across the board. There will be some rules that will be the same for all restaurants.
Create an Abstract Class named Restaurant
Create a function/method that will print the name of the restaurant when called.
Create an abstract function/method named total price
Create an abstract function/method named menu items
Create an abstract function/method name location
Create a Class called McDonalds that extends Restaurant
Implement all abstract methods
Add logic so that the total price method/function will give the total price of the meal including a 6% tax
Add a method that returns a Boolean named hasPlayPlace. Which returns true when this location has a playplace
Create a Constructor that will set the name of the Mcdonalds, location, and hasPlayPlace
public class McDonalds extends Restaurant {
private String name;
private String location;
private boolean hasPlayPlace;
Scanner input = new Scanner(System.in);
public McDonalds (String name, String location, boolean hasPlayPlace) {
setName(name);
setLocation(location);
setHasPlayPlace(hasPlayPlace);
}
McDonalds location1 = new McDonalds("McDonalds", "Kirkman", false);
McDonalds location2 = new McDonalds("McDonalds 2", "International Dr.", true);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location){
this.location = location;
}
public boolean isHasPlayPlace() {
return hasPlayPlace;
}
public void setHasPlayPlace(boolean hasPlayPlace) {
this.hasPlayPlace = hasPlayPlace;
}
public void totalPrice() {
double totalPrice = 0;
double tax = 0.06;
totalPrice += (totalPrice * tax);
}
public void menuItems() {
//some syntax is wrong in this method
double mcChicken = 1;
double fries = 1.25;
System.out.println("1. Mc Chicken $1");
System.out.println("2. Fries $1.25");
int choice = input.nextInt();
switch (choice){
case 1: mcChicken *= tax;
case 2: fries *= tax;
}
}
public void location() {
//Don't know what's supposed to go in here.
//But I've implemented the method as I was supposed to.
}
}
Does it all make sense is basically what i'm asking.
What should go in the location method?
What's the use of getters and setters within this class and did I do it right?
1) Your constructor is structured fine, but you should use Strings instead of chars for the name and location. A char will only hold one character.
2) You can create multiple instances of a class:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
McDonalds location2 = new McDonalds("McDonald2", "Kirkman", false);
3) You should add the tax to the price as a percentage, not a sum: price * 1.06. Be careful not to change the price w/o tax when you print the total price.
Name and location should be String not char.
I like the style of calling setters from within the constructor, because its a form of code reuse, especially if there are special checks being made on those values, such as not being null - calling he setter means you only check this in one place.
Your code won't compile, but you're close:
McDonalds location1 = new McDonalds("Some name", "Kirkman", true);
Your calculation is a little off too:
double tax = 0.06;
totalPrice *= (tax + 1);
However, this is dangerous because if called twice, it will add the tax twice. It would be better to have a method return the tax included price which calculates it every time. Having a getter with side effects is a design error. Ie have thus:
public double getTaxIncPrice() {
double tax = 0.06;
return totalPrice * (1 + tax);
}
In addition to the problem that Bohemian pointed out (name and location should be String, not char):
Your constructor call will need quotes on the String parameters:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
and your tax calculation is incorrect - you will need to multiply the total amount by the tax percentage, and you will have to wait until you actually have a total to do the calculation.
Just editted my code and provided the question. Your guys inputs helped so far.
public String TacoBellSauce(String fire, String hot, String mild) {
System.out.println("What sauce would you like to have?");
System.out.println("1. Fire");
System.out.println("2. Hot");
System.out.println("3. Mild");
int choice = input.nextInt();
switch(choice) {
case 1:
return fire;
case 2:
return hot;
case 3:
return mild;
}
return null;
}
Here is also my method for the TacoBell class. How would I return it in the Test class? It says to make a method within TacoBell that returns a string of what hot sauce I would like. But then it says within the test class to call hotsauce and return hot. I haven't created that class yet cause I'm focused on correcting everything with McDonalds and TacoBell.

Do While Loop skipping statements

In my do while loop, the body works fine initially, but when it loops, it prints the first two statements like it should but it does not allow me to enter the name instead it goes straight to enter pin and whatever I enter it skips the rest and asks me if I want another transaction.
I have an array object partially filed. The variables in the object are name, pin, account number and balance. When I add a new object and set the balance, the new balance I enter causes the balance for the previous objects to change as well. I think it has something to do with the balance variable being declared as static but I don't make it static, i can the error "Cannot make a static reference to the non-static method withdraw(double) from the type CustomerRecord". (SOLVED) Thank you.
public class BankCustomers
{
public static void main(String[] args)
//------------------------------------------------
//Part4: Find a customer record from anotherArray
//to do transaction(s) and update the record's balance
char repeat; // User control to repeat or quit
Scanner keyboard = new Scanner(System.in); //creating the scanner
String aName;
int aPin;
double aWithdraw;
double aDeposit;
do{
//Read customer information before search
System.out.println();
System.out.println("Lets make a transaction");
System.out.println("Enter customer full name");
aName = keyboard.nextLine( );
System.out.println("Enter Pin");
aPin = keyboard.nextInt();
//Search an Array for equal aName and aPin
for (int i = 0; i < index; i++)
{
CustomerRecord cRecord = anotherArray[i];
if((cRecord.getName().equalsIgnoreCase(aName)) && (cRecord.getPin() ==(aPin)))
{
System.out.println(cRecord);
System.out.println("Enter Withdraw Amount");
aWithdraw = keyboard.nextDouble();
CustomerRecord.withdraw(aWithdraw);
System.out.println("Enter Deposite Amount");
aDeposit = keyboard.nextDouble();
CustomerRecord.deposit(aDeposit);
System.out.println(cRecord);
}
}
System.out.println("\nAnother Transaction? (y for yes)");
repeat = keyboard.next().charAt(0);
}while(repeat == 'y' || repeat == 'Y');
//Print the records on screen
for (int i = 0; i < index; i++)
System.out.print(anotherArray[i]);
}
Remove the static from
private static double balance
and
public static void deposit(double aDeposit)
and
public static void withdraw(double aWithdraw)
you don't want them to be static as you are going to call these methods directly from the objects you created, so they will be specific to each CustomerRecord.
Then in your code, change these lines:
CustomerRecord.deposit(aDeposit);
CustomerRecord.withdraw(aDeposit);
by:
cRecord.deposit(aDeposit);
cRecord.withdraw(aDeposit);
The modifications made now will be applied to each CustomerRecord balance variable and not to a single balance variable (unique for the whole program) as it was the case when it was static.
public class CustomerRecord implements Serializable
{
private String name;
private int pin;
private int account;
private double balance;
}
public void deposit(double aDeposit)
{
balance = balance + aDeposit;
}
public void withdraw(double aWithdraw)
{
if (balance >= aWithdraw) balance = balance - aWithdraw;
else System.out.println("Withdraw cannot be negativeegative");
}
Make balance non-static, as you mentioned. This will fix the bug.
Make the CustomerRecord#deposit() and #withdraw() methods non-static as well. This will fix the compile error caused by #1.
You're correct that the problem is that you made things static. None of balance, deposit, withdraw should be static because all of them are things that apply to a particular customer record rather than to all customer records simultaneously.
The fact that your code doesn't work when you don't make them static is related to the way in which you're calling the withdraw method: CustomerRecord.withdraw(aWithdraw). Can you see what's wrong with that, now that your attention is drawn to it?
In your instance variables for CustomerRecord you have balance declared as a static variable.
This means that anytime you change balance in one instance of the class that it will change in all instances. For example, the deposit and withdraw methods.
I assume you needed to make balance static in order for these two methods to work, but you should just take the static declaration out of all three. Then, you need to change all calls from
CustomerRecord.withdraw();
CustomerRecord.deposit();
to use an instance of a class rather than just the static class. So,
// Whatever values you want here, you seem to have 4 already declared so you can use those
CustomerRecord c = new CustomerRecord("", 0, 0, 0);
c.withdraw();
c.deposit();
Your problem is twofold:
First, balance istatic, which means it is associated with the class, not any of its instances (objects), or in other terms it is shared between all instances of that class.
Second, as you pointed it out, your static method withdraw is accessing balance. The consideration about static applies here just as well -- the method is associated with the class, and cannot access memebers that are non-static.
To solve the second problem, remove static from the withdraw declaration (and remove static from balance as well. Thyis will make your code CustomerRecord.withdraw() not compile, becuase withdraw is now not associated with the class itself, but an instance of it. So you need to use an instance and call withdraw on that
cRecord.withdraw(aWithdraw);
Similarly for deposit

Categories

Resources