How to use the constructor? java - java

package aprilchap3;
/**
*
* #author ericaross
*/
public class SavingsAccount {
double interest;
double balance;
public SavingsAccount() {
balance = 0;
interest = 0.1;
}
public void addInterest() {
balance = interest*balance + balance;
}
public void deposit(double amount) {
balance= balance + amount;
}
public void getBalance(){
return balance;
}
}
``and this is the SavingsAccountTester class:
package aprilchap3;
/**
*
* #author ericaross
*/
public class SavingAccountTester {
public static void main(String[] args) {
SavingsAccount erica = new SavingsAccount();
erica.deposit(1000);
erica.addInterest();
Double ericaBalance = erica.getBalance() ;
System.out.println(ericaBalance + "this is how much you owe. ");`
}
}
So the problem is that I want to use the constructor to set the value instead of depositing, but when I try to do it an error shows up in Savings Account declaration.
here is where I want to put it SavingsAccount erica = new SavingsAccount(); but an error shows up every time can any one show me the best way to set constructor to work?

public SavingsAccount() {
balance = 0;
interest = 0.1;
}
You don't need this. You could have made those the initial values of the variables. What you need is
public SavingsAccount(double balance, double interest) {
this.balance = balance;
this.interest = interest;
}
and you then use it via new SavingsAcccount(balance, interest).
NB I hope and trust this is homework. You should never ever ever use floating-point datatypes for money.

Related

Cannot make a static reference to the non-static field message ..int randomNumber=r.nextInt(message.length); [duplicate]

I apologize ahead of time if this code isn't formatted correctly, trying to paste instead of retyping each line. If it isn't right, can someone tell me an easy way to paste multiple lines of code at once?
My main question is that I keep getting an error message stating: Cannot make a static reference to the non-static field balance.
I have tried making the methods static, with no result, and making the main method non-static by removing "static" from the header, but then I get the message: java.lang.NoSuchMethodError: main Exception in thread "main"
Does anyone have any ideas? Any help is appreciated.
public class Account {
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
System.out.println("The account was created " + account.getDateCreated());
}
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public java.util.Date dateCreated;
public Account() {
}
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public void setId(int i) {
id = i;
}
public int getID() {
return id;
}
public void setBalance(double b){
balance = b;
}
public double getBalance() {
return balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double interest) {
annualInterestRate = interest;
}
public java.util.Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(java.util.Date dateCreated) {
this.dateCreated = dateCreated;
}
public static double withdraw(double balance, double withdrawAmount) {
double newBalance = balance - withdrawAmount;
return newBalance;
}
public static double deposit(double balance, double depositAmount) {
double newBalance = balance + depositAmount;
return newBalance;
}
}
main is a static method. It cannot refer to balance, which is an attribute (non-static variable). balance has meaning only when it is referred through an object reference (such as myAccount.balance or yourAccount.balance). But it doesn't have any meaning when it is referred through class (such as Account.balance (whose balance is that?))
I made some changes to your code so that it compiles.
public static void main(String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(2500);
account.deposit(3000);
and:
public void withdraw(double withdrawAmount) {
balance -= withdrawAmount;
}
public void deposit(double depositAmount) {
balance += depositAmount;
}
the lines
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
you might want to make withdraw and deposit non-static and let it modify the balance
public void withdraw(double withdrawAmount) {
balance = balance - withdrawAmount;
}
public void deposit(double depositAmount) {
balance = balance + depositAmount;
}
and remove the balance parameter from the call
You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.
The static calls to withdraw and deposit are your problem.
account.withdraw(balance, 2500);
This line can't work , since "balance" is an instance variable of Account. The code doesn't make much sense anyway, wouldn't withdraw/deposit be encapsulated inside the Account object itself? so the withdraw should be more like
public void withdraw(double withdrawAmount)
{
balance -= withdrawAmount;
}
Of course depending on your problem you could do additional validation here to prevent negative balance etc.
Just write:
private static double balance = 0;
and you could also write those like that:
private static int id = 0;
private static double annualInterestRate = 0;
public static java.util.Date dateCreated;
To access instance variables it is a must to create an object, these are not available in the memory, before instantiation.
Therefore, you cannot make static reference to non-static fields(variables) in Java. If you still, try to do so a compile time error is generated saying “non-static variable math cannot be referenced from a static context”.
you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below.
sb = starting balance and eB = ending balance.
Account account = new Account(1122, 20000, 4.5);
double sB = Account.withdraw(account.getBalance(), 2500);
double eB = Account.deposit(sB, 3000);
System.out.println("Balance is " + eB);
System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
account.setDateCreated(new Date());
System.out.println("The account was created " + account.getDateCreated());

Sorting an ArrayList of various objects having in common instace variable being a double

I've been playing around with interfaces lately and was able to successfully implement Comparable and sort an ArrayList of BankAccount objects by their amount.
But what if the ArrayList contained objects of type BankAccount and Country having instance variable "area" (double). They both have value of type double which can be compared and sorted.
So my first question is-
How to sort ArrayList containing various objects having a double as instance variable?
Here is my code:
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount implements Measurable, Comparable<BankAccount>
{
private Double balance;
/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
balance = 0.0;
}
/**
Constructs a bank account with a given balance.
#param initialBalance the initial balance
*/
public BankAccount(Double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into the bank account.
#param amount the amount to deposit
*/
public void deposit(Double amount)
{
balance = balance + amount;
}
/**
Withdraws money from the bank account.
#param amount the amount to withdraw
*/
public void withdraw(Double amount)
{
balance = balance - amount;
}
/**
Gets the current balance of the bank account.
#return the current balance
*/
public double getBalance()
{
return balance;
}
public double getMeasure()
{
return balance;
}
public int compareTo(BankAccount o)
{
return this.balance.compareTo(o.getBalance());
}
}
/**
A country with a name and area.
*/
public class Country implements Measurable
{
private String name;
private double area;
/**
Constructs a country.
#param aName the name of the country
#param anArea the area of the country
*/
public Country(String aName, double anArea)
{
name = aName;
area = anArea;
}
/**
Gets the country name.
#return the name
*/
public String getName()
{
return name;
}
/**
Gets the area of the country.
#return the area
*/
public double getArea()
{
return area;
}
public double getMeasure()
{
return area;
}
}
public interface Measurable
{
double getMeasure(); // An abstract method
}
import java.util.*;
public class MeasurableTester
{
public static void main(String[] args)
{
// Calling the average method with an array of BankAccount objects
BankAccount b=new BankAccount(10.0);
BankAccount c = new BankAccount(2000.0);
List<BankAccount> accounts = new ArrayList<BankAccount>();
accounts.add(b);
accounts.add(c);
BankAccount x= Collections.max(accounts);
System.out.println(x.getBalance());
}
}
You should use List of Measurables and use comparator:
List<Measurable> measurableList = new ArrayList<>();
measurableList.add(new BankAccount(10.0));
measurableList.add(new Country("name", 44.5));
measurableList = Collections.max(measurableList, Comparator.comparingDouble(Measurable::getMeasure));

Completed code wondering whether I need to make any corrections

This is my completed code I was wondering whether it needs a correction
This is my first class
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=Math.pow(balance*(1+rate),n/12);
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
This is my second class
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(500, 0.1);//0.10);
Account acc2 = new Account(400, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
acc1.deposit(500);
acc1.withdraw(300);
acc1.computeInterest(12);
System.out.println(acc1.computeInterest(12));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(200);
acc2.deposit(800);
acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
Can anyone see whether I would be able to make the code more compact and is the way that I have coded perfectly valid. The code is about an Accounts class with a test account class for the second class it is supposed to calculate the compute interest of 12 months for the first one and for the second one is supposed to be about 24 months.
The Account class looks fine, except I don't understand why setIntrest() doesn't set the interest, but instead changes the balance. Maybe that's by design, maybe not, but I found that to be a bit surprising.
If you want to print the 24 month computeIntrest a bit more cleanly, take a look at this question.
These types of questions don't belong on StackOverflow. Here, we mostly (try to) solve problems. Suggesting improvements to working code is this way.

Account Class Java OOP

I have created an account class but the after the first calculation the it continues and doubles the second line. Have I missed anything in the code.
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=Math.pow(balance*(1+rate),n/12);
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(500, 0.1);//0.10);
Account acc2 = new Account(400, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
acc1.deposit(500);
acc1.withdraw(300);
acc1.computeInterest(12);
acc1.computeInterest(24);
System.out.println(acc1.computeInterest(12));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(200);
acc2.deposit(800);
acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
I don't know whether I have missed out something or that I have wrote the code wrong.
acc1.computeInterest(12);
acc1.computeInterest(24);
It looks to me that what you want is that calling these functions only return the computed interest but it shouldn't change your balance variable.
Just return the computed value without saving it in #balance variable.
This is my interpretation of your question, you were a little bit vague.
You have used the method computeinterest(int n) twice for the object acc1. the first time when you have used acc1.computeInterest(12) you get a value for it, but as you have used acc1.computeInterest(24) after that you are getting the answer incorrect.

Bank Account Program Logic Error

I create a very basic bank account program for homework and I keep getting a logic error. Instead of the program giving the total balance after the depositing, withdrawing, and adding interest it just outputs the amount deposited - withdrawn.I appreciate the help, thanks!
public class BankAccount
{
public BankAccount(double initBalance, double initInterest)
{
balance = 0;
interest = 0;
}
public void deposit(double amtDep)
{
balance = balance + amtDep;
}
public void withdraw(double amtWd)
{
balance = balance - amtWd;
}
public void addInterest()
{
balance = balance + balance * interest;
}
public double checkBal()
{
return balance;
}
private double balance;
private double interest;
}
Test Class
public class BankTester
{
public static void main(String[] args)
{
BankAccount account1 = new BankAccount(500, .01);
account1.deposit(100);
account1.withdraw(50);
account1.addInterest();
System.out.println(account1.checkBal());
//Outputs 50 instead of 555.5
}
}
I believe the problem is in your constructor:
public BankAccount(double initBalance, double initInterest)
{
balance = 0; // try balance = initBalance
interest = 0; // try interest = initInterest
}
Change your constructor as
public BankAccount(double initBalance, double initInterest)
{
balance = initBalance;
interest = initInterest;
}
You are not assigning the value you are passing to the constructor to the instance variables
In the constructor you are by default assigning the values as 0 for balance and interest, instead assign the method parameters. Replace the below code
public BankAccount(double initBalance, double initInterest)
{
balance = 0;
interest = 0;
}
public BankAccount(double initBalance, double initInterest)
{
this.balance = initBalance;
this.interest = initInterest;
}

Categories

Resources