adding static attribute to constructor attribute - java

The problem is the following:
(Savings Account Class) Create class SavingsAccount. Use a static
variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has
on deposit. Provide method calculateMonthlyInterest to calculate the
monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12—this interest should be added to
savings- Balance. Provide a static method modifyInterestRate that sets
the annualInterestRate to a new value. Write a program to test class
SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with balances of $2000.00 and $3000.00, respectively. Set
annualInterestRate to 4%, then calculate the monthly interest for each
of 12 months and print the new balances for both savers. Next, set the
annualInterestRate to 5%, calculate the next month’s interest and
print the new balances for both savers.
I solved it all, but the balance is not incrementing -- it is staying the same. It should increment with every change in annual interest rate (at least, that's what I understood).
class SavingsAccount
{
static double annualInterestRate;
private double savingsBalance;
public SavingsAccount(double balance)
{
savingsBalance = balance;
}
public double calculateMonthlyInterest()
{
return (savingsBalance*annualInterestRate)/12;
}
public static void modifyInterestRate(double rate)
{
annualInterestRate = rate;
}
public static double getannualInterestRate(){return annualInterestRate;}
public double getsavingsBalance(){return savingsBalance;}
}
public class SavingsTest
{
public static void main(String args[])
{
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.modifyInterestRate(4);
System.out.printf("Balance for Saver1 = %.2f\nBalance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance()+saver1.calculateMonthlyInterest(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
SavingsAccount.modifyInterestRate(5);
System.out.printf("New Balance for Saver1 = %.2f\nNew Balance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
}
}

You are not modifying the value of savingsBalance in this code.

public double addMonthlyInterest() {
savingsBalance += (savingsBalance*annualInterestRate)/12;
return savingBalance;
}
This will return the new balance and 'increment'

In your first print statement, for the first argument you are calculating the balance after calculating the monthly interest and adding them together and didn't set the new value as the value of the class member savingsBalance.
In your second print statement, since you did not set the calculated value back to the class member through a setter, it is simply printing out the original value that the classes were instantiated with.
On a side note, don't do inline calculations in print statements. They are confusing and not easy to read for anyone. A good way is to initialize local members in the method and using them for calculations and printing the local members.

Just wanted to share my answer.
public class SavingsAccount {
private static float annualInterestRate = 0f;
private float savingsBalance;
public SavingsAccount(float balance) {
savingsBalance = balance;
}
public static void setAnnualInterestRate(float t) {
if (t >= 0 && t <= 1)
annualInterestRate = t;
else
throw new IllegalArgumentException("Annual interest rate should be between 0 and 1");
}
private float calculateMonthlyInterest() {
return savingsBalance * annualInterestRate / 12;
}
public float getSavingsBalance() {
return savingsBalance + calculateMonthlyInterest();
}
public float getAnnualInterestRate(){
return annualInterestRate;
}
public String toString() {
return String.format("Balance: %.2f", getSavingsBalance());
}
}
in main
SavingsAccount s1 = new SavingsAccount(2000);
SavingsAccount s2 = new SavingsAccount(3000);
SavingsAccount.setAnnualInterestRate(0.04f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);
SavingsAccount.setAnnualInterestRate(0.05f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);

Related

How to call methods from an extended class?

public class Account {
double currentBalance;
Account(double currentBalance) {
this.currentBalance = currentBalance;
}
double getBalance() {
return(this.currentBalance);
}
void deposit(double amount) {
this.currentBalance += amount;
}
void withdraw(double amount) {
this.currentBalance -= amount;
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance);
}
}
public class SavingsAccount extends Account {
double interestRate;
SavingsAccount(double interestRate, double amount) {
super(amount);
this.interestRate = interestRate;
}
void addInterest(double interestRate) {
this.currentBalance = this.currentBalance + (this.currentBalance * (interestRate / 100));
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance + ". Your interest rate is: " + this.interestRate + "%");
}
}
public class AccountTester {
public static void main(String[] args) {
System.out.println("Welcome to the COMP 251 BANK");
Account[] acc = new Account[10];
acc[0] = new Account (100000); // initial amount of 100k
System.out.println(acc[0].toString());
acc[0].deposit(50000); //deposit 50k
System.out.println("Current balance after depositing is: " + "$" + acc[0].getBalance());
acc[0].withdraw(10000);
System.out.println("Current balance after withdrawing is: " + "$" + acc[0].getBalance());
System.out.println();
System.out.println("CHECKING ACCOUNT");
acc[1] = new CheckingAccount(10000,50000); //overdraft limit of 1000, initial amount of 50k
System.out.println(acc[1].toString());
acc[1].deposit(20000); //I dont know what to do about the chequeDeposit
System.out.println("Current balance after depositing is: " + "$" + acc[1].getBalance());
System.out.println();
System.out.println("SAVINGS ACCOUNT");
acc[2] = new SavingsAccount(10, 50000);
System.out.println(acc[2].toString());
acc[2].deposit(10000);
System.out.println("Current balance after depositing is: " + "$" + acc[2].getBalance());
acc[2].addInterest();
}
}
I'm still new to this so I'm sorry if this is a bad question but I tried playing around with each class and I still can't figure out how to use the addInterest method I created in the SavingsAccount class that extends the Account class. I tried SavingsAccount.addInterest but I get a static reference error. I thought acc[2].addInterest would work but it says its undefined for the type Account.
You need to cast acc[2] to SavingsAccount before calling the method.
((SavingsAccount) acc[2]).addInterest();
It is called downcasting and here is an explanation of it.
You're trying to invoke a child class' method, addInterest from a base class reference.
In fact, your array has been declared as an array of Account objects
Account[] acc = new Account[10];
This class does not offer the addIntereset method, even though your arr[2] contains a SavingAccount instance, Java in fact will only be able to know this at run-time. At compile time, your syntax must be compliant with the declared type (Account).
To work around this problem you have two solutions: creating a generic addInterest method in your base class which your child classes will override or cast your arr[2] to a SavingAccount instance.
With the first approach, you're offering an addInterest method from the base class, so whatever instance is going to call the method (an actual Account or a subtype), it will always be able to invoke it.
public class Account {
public void addInterest(double interest){
//Account implementation
}
}
public class SavingAccount {
#Overrride
public void addInterest(double interest){
//SavingAccount implementation
}
}
So, in your main you could type with no errors:
Account[] arr = new Account[10];
arr[0] = new Account();
arr[0].addInterest(5); //No error, dynamic dispatch will call Account's implementation
arr[1] = new SavingAccount();
arr[1].addInterest(10); //No error, dynamic dispatch will call SavingAccount's implementation
With the second approach instead, you need to make sure that what you're downcasting corresponds to the subtype of your casting.
//Randomly assigning to acc an Account instance or a SavingAccount instance
Account acc = Math.round(Math.random()) == 0 ? new Account() : new SavingAccount();
//Making sure to downcast acc to SavingAccount with the instanceof operator
if (acc instanceof SavingAccount){
SavingAccount savAcc = (SavingAccount) acc;
savAcc.addInterest(5);
}

How can I use a variable from all similar objects in an if statement (Java)?

I am a beginner in Java and I hit a small snag.
I'm writing some code for an imaginary bank, and I want to include all the accounts' balance into one if statement. I made a double called accountBalance that I use for each account.
For example, Josie.accountBalance = 1200. Josie is an object for the BankAccounts type I created.
I want to make an if statement, so that if the account balance is above 1000, the bank sends a message warning the account about this issue, and it refunds everything above 1000$.
I could just do an if statement for every account I create, and write my code there, but I was wondering if there was a way to write an if statement that applied to all the BankAccounts type, without having to specify the names.
Thanks.
Here's the code that I wrote.
package learnJavaNew;
import java.util.ArrayList;
public class BankAccounts {
final static double defaultBalance = 50;
final static double maxBalance = 1000;
static double oldBalance;
static int employees;
static double bankMoney;
static double accountBalance;
static double newBalance;
public static void main(String[] args) {
// Josie's Bank Account
BankAccounts Josie = new BankAccounts();
Josie.depositMoney(0);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
Josie.withdrawMoney(25.64);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
// Dan's Bank Account
BankAccounts Dan = new BankAccounts();
Dan.depositMoney(1000);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
Dan.withdrawMoney(5);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
// Accounts List
ArrayList<BankAccounts> accounts = new ArrayList<BankAccounts>();
accounts.add(Josie);
accounts.add(Dan);
System.out.println(accounts);
// Max Balance
if(accountBalance >= maxBalance) {
System.out.println("You have reached the maximum balance for your bank account, which is " + maxBalance + "$.");
System.out.println("You cannot deposit more money into this account.");
oldBalance = accountBalance;
accountBalance = 1000;
System.out.println("You have been refunded " + (oldBalance - accountBalance));
}
// New Balance
System.out.println(Dan.accountBalance);
System.out.println(Josie.accountBalance);
}
public void depositMoney(double depositedMoney) {
newBalance = depositedMoney;
}
public void withdrawMoney(double withdrawnMoney) {
newBalance = newBalance - withdrawnMoney;
}
}
This kind of depends on the result you want. If the above code gives you the right result, then it's fine. However I would probably do something like this, and omit the loop and the list entirely.
public void depositMoney(double depositedMoney) {
if( depositedMoney + accountBalance > 1000 )
System.out.println( "Maximum exceeded, not processed" );
else
accountBalance += depositedMoney;
}
Notice here that I've changed the previous operation of depositedMoney, including the fact that the method never updated accountBalance.
To refund money over an amount, you might return a value indicating the amount refunded.
public double depositMoney(double depositedMoney) {
double refund = 0;
if( depositedMoney + accountBalance > 1000 ) {
refund = depositedMoney + accountBalance - 1000;
accountBalance = 1000;
System.out.println( "Maximum exceeded, refund " + refund );
}
else
accountBalance += depositedMoney;
return refund;
}
Also, you really should be using instance variables. Remove the static keyword.
double bankMoney;
double accountBalance;
double newBalance;
This might be made clearer by a different object model.
I would propose a BankAccount class (not "a BankAccounts class" -- that would mean that an object is "a BankAccounts", a jarring concept) and a Bank class.
class BankAccount {
private String owner;
private double balance;
BankAccount(String s, double b) { owner = s; balance = b; }
String owner() { return owner; }
double balance() { return balance; }
void deposit(double amount) { … like before … }
void withdraw(double amount) { … like before … }
}
and
class Bank {
static List<BankAccount> accounts = new ArrayList<>();
public static void main(String[] args) {
// set up some accounts
BankAccount josie = new BankAccount("Josie", 0);
accounts.add(josie);
BankAccount dan = new BankAccount("Dan", 1000);
accounts.add(dan);
:
etc
:
// print them all
double total = 0;
for (BankAccount acnt : accounts) {
System.out.printf("Account %s : balance %s %n",
acnt.owner(), acnt.balance());
total += acnt.balance();
}
System.out.printf("Total value of accounts: %s %n", total);
}
}
The benefit of this approach is that it makes it clearer what operations are for a single account and what operations are on "all accounts".

Java inheritance: Why this program gives 0.0 in output

I have written this code. The output should calculate the interest of the Bank but it gives 0.0 as output. I have created a class named as Bank and extended it in ICICI class.
import java.util.Scanner;
public class Bank
{
static double rate;
// n = number of years
public double calculateInterest( double PrincipalAmount, double n)
{
double interest;
interest = (PrincipalAmount * n*rate) /100; // interest formula
return interest;
}
public static void main(String[] args)
{
Scanner s1 = new Scanner(System.in);
System.out.print("Enter PrincipalAmount :" );
double PrincipalAmount = s1.nextDouble();
Scanner s2 = new Scanner(System.in);
System.out.print("Enter Number of Years :" );
double n = s2.nextDouble();
ICICI ic;
ic = new ICICI();// new object created of ICICI Class
ic.rate = rate; // object call by reference
System.out.print("Interest of ICICI is " + ic.calculateInterest( PrincipalAmount,n));
}
}
public class ICICI extends Bank
{
double rate = 4;
}
you are doing following:
ic.rate = rate;
and rate is not initialized....
so ic.rate = 0.0;
you should by the way take a look at this:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
What does the 'static' keyword do in a class?
and this
http://www.oracle.com/technetwork/java/codeconventions-135099.html
calculateInterest method is using static rate variable not instance rate , inheritance does not apply on variable , it does not override variable. so default value of static rate will be 0.0 and hence calculateInterest will give 0.0 (because it is double)answer.
You have mistakenly altered the assignment statement:
ic.rate = rate;
Instead, it should be :
rate= ic.rate;
Thanks!

Problems using constructors and getting methods for another class

So i keep getting errors when i try to run the user class saying double is required an no arguments are found. I'm getting errors on lines 17, 40, 42, 44, 46 and 48. They're all errors which say doubles are required. Answers in plain English would be appreciated.
My main class:
import java.util.Scanner;
public class ElectricityCalculatorUser {
//Main method
public static void main (String [] args) {
ElectricityCalculator myCalculator = new ElectricityCalculator();
Scanner input = new Scanner (System.in);
//Input the initial reading
double initialReading;
System.out.print ("What is the inital reading on your electricity meter in kwH? ");
initialReading = input.nextDouble ();
//Input the final reading
double finalReading;
System.out.print ("What is the final reading on your electricity meter in kwH? ");
finalReading = input.nextDouble ();
//Input the number of days
//between readings
double numberOfDays;
System.out.print ("How many days have passed between your initial and final reading? ");
numberOfDays = input.nextDouble ();
//Calculations
double totalElectricityUsed = myCalculator.totalElectricityUsed();
System.out.print ("Total electricity used = " + totalElectricityUsed);
double costOfElectricity = myCalculator.costOfElectricity();
System.out.print ("Cost of electricity = " + costOfElectricity);
double standingCharge = myCalculator.standingCharge();
System.out.print ("Standing charge = " + standingCharge);
double costBeforeVAT = myCalculator.costBeforeVAT();
System.out.print ("Cost before VAT is added = " + costBeforeVAT);
double VAT = myCalculator.VAT();
System.out.print ("Cost of VAT = " + VAT);
double totalCost = myCalculator.totalCost();
System.out.print ("Total cost = " + totalCost);
}
}
My class with all the methods:
public class ElectricityCalculator {
//Attributes
private double initialReading;
private double finalReading;
private double numberOfDays;
//Constructors
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
//Calculating total electricity used
public double totalElectricityUsed () {
return finalReading - initialReading;
}
//Calculating cost of electricity
public double costOfElectricity () {
return totalElectricityUsed * 0.175;
}
//Calculating standing charge
public double standingCharge (double numberOfDays) {
return numberOfDays * 0.25;
}
//Calculating cost before VAT is added
public double costBeforeVAT (double costOfElectricity, double standingCharge) {
return costOfElectricity + standingCharge;
}
//Cost of VAT
public double VAT (double costBeforeVAT) {
return costBeforeVAT * 0.05;
}
//Total cost of electricity used
//including VAT
public double totalCost (double costBeforeVAT, double VAT) {
return costBeforeVAT + VAT;
}
}
In java, if you don't write a constructor, a default constructor will be added automatically for you, and this constructor would be public and takes no argument.
Something like the following:
public ElectricityCalculator () {
}
However, when you define any constructors, the default constructor will be removed. And hence, the only constructor that you have in your class is
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
And therefore
ElectricityCalculator myCalculator = new ElectricityCalculator();
Doesn't match any constructors.
you can simply create the instance after getting the values required to construct the object
ElectricityCalculator myCalculator = new ElectricityCalculator(initialReading, finalReading, numberOfDays);
In addition to Sleiman Jneidi answer, you are calling functions, but dont provide any parameters, as the method definition demands:
double standingCharge = myCalculator.standingCharge();
need to be changed to:
double standingCharge = myCalculator.standingCharge(10.0); //example for 10 days
same problem in the lines 42, 44, 46, 48 of your code
public ElectricityCalculator (double ir, double fr, double nod);
public double standingCharge (double numberOfDays);
public double costBeforeVAT (double costOfElectricity, double standingCharge);
public double VAT (double costBeforeVAT);
public double totalCost (double costBeforeVAT, double VAT);
The constructor and these methods take arguments but you are trying to call them as if they did not.
For the constructor, you can simply move this line
ElectricityCalculator myCalculator = new ElectricityCalculator();
to after you take input from the user so you can pass in the arguments.
// pass arguments here
// v v v
... = new ElectricityCalculator( initialReading , finalReading , numberOfDays );
For the other methods you need to be passing in the results of interim calculations. For example VAT(...) takes a costBeforeVAT which I assume should be the return value of costBeforeVAT(... , ...).
double costBeforeVAT = ...;
// pass argument here
// v
double VAT = myCalculator.VAT( costBeforeVAT );
Note that in some cases you probably do not need these methods to have certain parameters, for example
public double standingCharge () {
return numberOfDays * 0.25;
}
because numberOfDays was already a member of the class ElectricityCalculator and
public double costBeforeVAT () {
return costOfElectricity() + standingCharge();
}
because these methods can be called directly instead of asking for their results to be passed in.
Related: "Passing Information to a Method or a Constructor".

Java - add value to it to a variable from another class

My problem is how do I add a value to a variable from another class, for example:
private int balance;
then later in the methods in the same class, I add values to the balance with no problem using:
balance += 50;
but when I go to another class, and type the object then the setter for the balance:
myObject.setBalance(50);
but the problem strikes here, when I go to the first class and return the balance from there, i get nothing (or the old value of balance) in other words, the NEW value of balance is not being added. Any ideas why? I've been stuck at this point for the last couple of hours
Here's my code:
public class Zoo
{
private int balance;
public void setBalance(int balance)
{
this.balance = balance;
}
public int getBalance()
{
return this.balance;
}
}
MY SECOND CLASS:
public class RandomEvents
{
private Zoo ZooBalance = new Zoo();
public void callEventSix()
{
System.out.println("A local group has raised money to your Zoo");
System.out.println("Would you like to accept the money? (y) or (n)");
Scanner readerEventThree = new Scanner(System.in);
String readerTwo = readerEventThree.next();
if ( readerTwo.equals("y") )
{
ZooBalance.setBalance(166);
System.out.println("You have accepted the gift");
System.out.println("Your new balance is " + ZooBalance.getBalance());
} else if ( readerTwo.equals("n") )
{
System.out.println("You have refused the gift");
}
}
}
In your case
Replace this line:
ZooBalance.setBalance(166);
with:
ZooBalance.setBalance(ZooBalance.getBalance() + 166);
Sytem.out.println(ZooBalance.getBalance()); // 166
You need to make a setter for that class. Assuming the name of the class is TestClass.
class TestClass {
private int balance = 50;
};
public int getBalance() {
return this.balance;
};
public void setBalance(int newBalance) {
this.balance = newBalance;
};
And then in another class:
TestClass test = new TestClass();
test.setBalance(test.getBalance() + 50);
System.out.println(test.getBalance);// 100
I'm pretty sure there's a difference between adding 50 to a value and setting a value to 50.
myObject.setBalance(50); will not add 50, it will change the value to 50. To add 50, you'd have to do something along the lines of myObject.setBalance(myObject.getBalance() + 50);
generally there are two ways to this.
First. Use getter and setter:
Zoo zoo = new Zoo();
zoo.setBalance(zoo.getBalance() + 50);
Second. Add an adder method:
public void addToBalance(int addend) {
balance += addend;
}
Zoo zoo = new Zoo();
zoo.addToBalance(50);

Categories