Java - A simple (to everyone but me) method - Inheritance - java

Ok, so I hope you can all help, I have been tasked whilst tying to learn the language with the age-old test of simple savings account and checking account using inheritence.
My problem is, I want to make the checking account incapable of going over its overdraft limit and the savings account incapable of going below 0 but cant work out how? my code so far is as follows:
SUPERCLASS (BankAccount):
public class BankAccount
{
protected String CustomerName;
protected String AccountNumber;
protected float Balance;
//Constructor Methods
public BankAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn)
{
CustomerName = CustomerNameIn;
AccountNumber = AccountNumberIn;
Balance = BalanceIn;
}
// Get name
public String getCustomerName()
{
return (CustomerName);
}
// Get account number
public String getAccountNumber()
{
return (AccountNumber);
}
public float getBalance()
{
return (Balance);
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else
Balance = Balance - WithdrawAmountIn;
}
public void Deposit(float DepositAmountIn)
{
if(DepositAmountIn < 0)
System.out.println("Sorry, you can not deposit a negative amount, if you wish to withdraw money please use the withdraw method");
else
Balance = Balance + DepositAmountIn;
}
} // End Class BankDetails
SUBCLASS (SavingsAccount):
public class SavingsAccount extends BankAccount
{
private float Interest;
public SavingsAccount(String CustomerNameIn, String AccountNumberIn, float InterestIn, float BalanceIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Interest = InterestIn;
}
public float getInterestAmount()
{
return (Interest);
}
public float newBalanceWithInterest()
{
Balance = (getBalance() + (getBalance() * Interest / 100) );
return (Balance);
}
public void SavingsOverdraft()
{
if( Balance < 0)
System.out.println("Sorry, this account is not permitted to have an overdraft facility");
}
}
SUBCLASS (CheckingAccount):
public class CheckingAccount extends BankAccount
{
private float Overdraft;
public CheckingAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn, float OverdraftIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Overdraft = OverdraftIn;
}
public float getOverdraftAmount()
{
return(Overdraft);
}
public void setOverdraft()
{
if (Balance < Overdraft)
System.out.println("Sorry, the overdraft facility on this account cannot exceed £100");
}
}
Thank you very very much for any advice and help!

Add getOverdraftAmount() to your base class:
public int getOverdraftAmount() {
return 0;
}
Then override that method in account subclasses that allow overdrafts. Then revise your logic for withdrawal to take into account that the overdraft limit might not be zero.
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (Balance - WithdrawAmountIn < -getOverdraftAmount()) {
System.out.println("Sorry, this withdrawal would exceed the overdraft limit");
else
Balance = Balance - WithdrawAmountIn;
}

To do this you will need to override the withdraw function in both the subclasses in order to change the functionality of each individually.
SUBCLASS (SavingsAccount):
public class SavingsAccount extends BankAccount
{
private float Interest;
public SavingsAccount(String CustomerNameIn, String AccountNumberIn, float InterestIn, float BalanceIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Interest = InterestIn;
}
public float getInterestAmount()
{
return (Interest);
}
public float newBalanceWithInterest()
{
Balance = (getBalance() + (getBalance() * Interest / 100) );
return (Balance);
}
public void SavingsOverdraft()
{
if( Balance < 0)
System.out.println("Sorry, this account is not permitted to have an overdraft facility");
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (WithdrawAmountIn>Balance)
System.out.println("Sorry, you don't have this much in your account.");
else
Balance = Balance - WithdrawAmountIn;
}
}
SUBCLASS (CheckingAccount):
public class CheckingAccount extends BankAccount
{
private float Overdraft;
public CheckingAccount(String CustomerNameIn, String AccountNumberIn, float BalanceIn, float OverdraftIn)
{
super (CustomerNameIn, AccountNumberIn, BalanceIn);
Overdraft = OverdraftIn;
}
public float getOverdraftAmount()
{
return(Overdraft);
}
public void setOverdraft()
{
if (Balance < Overdraft)
System.out.println("Sorry, the overdraft facility on this account cannot exceed £100");
}
public void Withdraw(float WithdrawAmountIn)
{
if(WithdrawAmountIn < 0)
System.out.println("Sorry, you can not withdraw a negative amount, if you wish to withdraw money please use the withdraw method");
else if (Balance-WithdrawAmountIn<getOverdraftAmount()
System.out.println("Sorry, you cannot withdraw this much");
else
Balance = Balance - WithdrawAmountIn;
}
}

Related

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;
}

Understanding inheritance and different classes

I'm messing around with inheritance and confused on how to do a few different things. Here is what I have:
Looking at the Account class and write a main method in a different class Bank to brief experiment with some instances of the Account class.
Using the Account class as a base class, write two derived classes called SavingsAccount and CheckingAccount. A SavingsAccount object, in addition to the attributes of an Account object, should have an interest variable and a method which adds interest to the account. A CheckingAccount object, in addition to the instance variables of an Account object, should have an overdraft limit variable. Ensure that you have overridden methods of the Account class as necessary in both derived classes.
Now create a Bank class, an object of which contains an array of Account objects. Accounts in the array could be instances of the Account class, the SavingsAccount class, or the CheckingAccount class. Create some test accounts (some of each type).
Write an update method in the bank class. It iterates through each account, updating it in the following ways: Savings accounts get interest added (via the method you already wrote); Checking Account get a letter sent if they are in overdraft.
public class Account {
private double balance;
private int acctNum;
public Account (int num)
{
balance = 0.0;
acctNum = num;
}
public void deposit (double amt)
{
if (amt >0)
balance +=amt;
else
System.out.println("Account.deposit(...): "
+"cannot deposit negative amount.");
}
public void withdraw (double amt)
{
if (amt>0)
balance -=amt;
else
System.err.println("Account.withdraw(...): "
+"cannot withdraw negative amount.");
}
public double getBalance()
{
return balance;
}
public double getAccountNumber()
{
return acctNum;
}
public String toString()
{
return "Acc " + acctNum + ": " + "balance = "+ balance;
}
public final void print()
{
System.out.println( toString());
}
}
Now the SavingsAccount
public class SavingsAccount extends Account {
private double interest;
public SavingsAccount(int acctNum, double interest) {
super(acctNum);
this.interest=interest;
}
public double getInterest() {
double x= getBalance() + getBalance()*interest;
return x;
// public void setInterest((interest))
// this.interest=interest;
}
public void AddInterest (double interest) {
double x = super.getBalance() * interest;
super.deposit(x);
}
public String toString() {
return super.toString()+" Interest : " + interest;
}
}
CheckingAccount
public class CheckingAccount extends Account {
private double limit;
public CheckingAccount(int acctNum, double limit) {
super(acctNum);
this.limit=limit;
}
public double getLimit() {
return this.limit;
}
public void setLimit(double limit) {
this.limit=limit;
}
public void withdraw (double limit) {
if (limit <= this.limit)
super.withdraw(limit);
else {
System.out.println(" Sorry, Limit Exceeded" );
}
}
public String toString() {
return super.toString() +"Limit : "+limit;
}
}
Bank class
public class Bank {
public static void main(String[] args) {
Account[] accounts = new Account[2];
accounts[0] = new SavingsAccount(2, 0.25);
accounts[1] = new CheckingAccount(23, 50);
for(int i=0; i<accounts.length;i++) {
if (accounts[0].equals(SavingsAccount)
System.out.println(accounts[0].getInterest());
}
}
So here is my problems that I am noticing.
In the SavingsAccount I'm not sure how to get the setInterest() to work. I have tried changing it to a int, but then that changes the Account class. How do I get that to work properly?
In the bank class - the for loop I have written. Its not working, I have tried if(accounts[i].equals so so, but does not seem to function properly. What is the correct way?
As well, I'm assuming everything is coming from my SavingsAccount class.
If I understand what you are trying to do in your for-loop you need to use instanceof to check classes, not equals().
So, for example
Account[] accounts = new Account[2];
accounts[0] = new SavingsAccount(2, 0.25);
accounts[1] = new CheckingAccount(23, 50);
for(int i=0; i<accounts.length;i++) {
if (accounts[i] instanceof SavingsAccount) {
// You must cast an Account to use any of the descendant's methods
SavingsAccount account = (SavingsAccount) accounts[i];
System.out.println(account.getInterest());
} else { // it's a CheckingAccount
}
}
Other than that, StackOverflow is not a place for you to dump homework requirements, so your question is overly broad to answer in completion.

How to call void method from driver

It seems like I can't call the withdraw method.. What did I do wrong?
public class BankAccount {
double balance;
BankAccount(double openingBalance){
balance=openingBalance;
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance += amount;
}
public void withdraw (double amount){
if (balance > amount){
balance -= amount;
}else if (amount > balance){
System.out.print("Error");
}else if (amount == balance){
balance = 0;
}
}
}
My driver class
public class Driver {
static BankAccount acc1;
public static void main (String[] args){
BankAccount acc1 = new BankAccount (1500);
acc1.deposit(1500);
acc1.withdraw(1000);
System.out.println("Withdrawl Amount: $" +acc1.withdraw(I GET AN ERROR) +"Deposit: $" +acc1.balance);
The problem is that you are invoking acc1.withdraw(...) and trying to append whatever it returns to a String. Since the withdraw method returns void, that is not valid syntax. It isn't clear what you really want but if you want to append the return value of withdraw to a String for some reason then withdraw needs to return something. Maybe you want something like this...
public class BankAccount {
double balance;
BankAccount(double openingBalance){
balance=openingBalance;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance += amount;
}
public double withdraw (double amount){
if (balance > amount){
balance -= amount;
}else if (amount > balance){
System.out.print("Error");
}else if (amount == balance){
balance = 0;
}
// you can return the amount, or the balance, or whatever you want here...
return amount;
}
}
One way to invoke the method...
public class Driver {
public static void main (String[] args){
BankAccount acc1 = new BankAccount (1500);
System.out.println("After Withdrawing Amount: $" +acc1.withdraw(50) +" The New Balance: $" +acc1.balance);
}
}

calling methods from classes in the main method

I am a bit stuck on this one. I am writing a java program with two classes, and then a test program to test the methods in the class. I am stuck on calling the two methods below in the main method. All of the class files (the test program class and the two other classes) are compiling and the IDE is not giving me any error messages, the calculation is just not occurring...
--Main Method Code:
//Call debit method
System.out.println("Please enter amount to be debited");
double amount=input.nextDouble();
account.debit(amount);
System.out.printf("%.2f%n",balance);
//Call credit method
System.out.println("Please enter amount to be credited");
amount=input.nextDouble();
account.credit(amount);
System.out.printf("%.2f%n",balance);
--Account Class Code:
//Method for crediting account balance
public void credit (double amount) {
double newBalance=this.balance+amount;
this.setBalance(newBalance);
}
//Method for debiting account balance
public void debit (double amount) {
if (amount<balance) {
double newBalance=this.balance-amount;
this.setBalance(newBalance);
} else {
System.out.println("Insufficient Funds!");
}
NOTE: the balance setter is working, as it is called earlier in the test program...
Any help much appreciated!!!
Complete Code for Account Class:
public class Account {
private int accountId;
private String accountName;
private String accountAddress;
private double balance;
private Bank bank;
//Default Constructor
public Account () {
}
//Getters
public int getAccountId () {
return accountId;
}
public String getAccountName () {
return accountName;
}
public String getAccountAddress () {
return accountAddress;
}
public double getBalance () {
return balance;
}
public Bank getBank () {
return bank;
}
//Setters
public void setAccountId (int accountId) {
if (accountId <=10000000 || accountId >=99999999) {
System.out.println("Invalid Account Id");
} else {
this.accountId=accountId;
}
}
public void setAccountName (String accountName) {
if (accountName.length()>=10) {
System.out.println("Too Long");
} else {
this.accountName=accountName;
}
}
public void setAccountAddress (String accountAddress) {
this.accountAddress=accountAddress;
}
public void setBalance (double balance) {
if (balance<0.0) {
System.out.println("Invalid Balance");
} else {
this.balance=balance;
}
}
public void setBank (Bank bank) {
this.bank=bank;
}
//Constructor to initialize accountId, accountName, accountAddress and Bank
public Account (int accountId, String accountName, String accountAddress, Bank bank) {
this.setAccountId(accountId);
this.setAccountName(accountName);
this.setAccountAddress(accountAddress);
this.setBank(bank);
}
//Method to print out account category based on balance
public void printAccountCategory () {
if (balance<100.0) {
System.out.println("Challenged Account");
} else if (balance>=100.0 && balance<999.9) {
System.out.println("Standard Account");
} else if (balance>=1000.0 && balance<9999.9) {
System.out.println("Promising Account");
} else if (balance>=10000.0 && balance<99999.9) {
System.out.println("Gold Star Account");
} else {
System.out.println("Super Duper Account");
}
}
//Method to project balance based on compound interest and the number of years required
//Note: I took the formula using n (number of times the interest is compounded per year) as 1
public double projectNewBalance (int numberYears) {
if (numberYears>0) {
double interest=1;
for (int i=1; i<=numberYears; i++) {
interest*=(1.0+bank.getInterestRate());
}
double newBalance=balance*interest;
return newBalance;
} else if (numberYears<0) {
System.out.println("Invalid Value");
} else {
return balance;
}
return balance;
}
//Method for crediting account balance
public void credit (double amount) {
double newBalance=this.balance+amount;
this.setBalance(newBalance);
}
//Method for debiting account balance
public void debit (double amount) {
if (amount<balance) {
double newBalance=this.balance-amount;
this.setBalance(newBalance);
} else {
System.out.println("Insufficient Funds!");
}
}
//toString method
public String toString () {
return "Account Id: "+accountId+", Account Name: " + accountName + ", Account Address: "+accountAddress+", Balance: "+balance+", Bank Details: "+bank.toString()+".";
}
}
Main Method Full Code:
import java.util.Scanner;
public class BankAccountTest {
public static void main (String [ ] args) {
//Create an instance of the Bank class
Bank bank = new Bank ("WIT Bank", "Paddy Snow", 0.045);
//Create instance of Scanner class
Scanner input=new Scanner(System.in);
//Prompt user to input data to create an account
System.out.println("Please enter an Account ID");
int accountId=input.nextInt();
System.out.println("Please enter an Account Name");
String accountName=input.next();
System.out.println("Please enter an Account Address");
String accountAddress=input.next();
//Create instance of the Account class
Account account = new Account (accountId, accountName, accountAddress, bank);
//Print out details of account class
System.out.println(account);
//Prompt user to enter balance for the account
System.out.println("Please enter account balance");
double balance=input.nextDouble();
account.setBalance(balance);
//Use printAccountCategory method
account.printAccountCategory();
//Call projectNewBalance method
// Note: Method tested with value of 10 years as mentioned in spec,
// but user input also included I think it is more appropriate for the functionality of the program
// int numberYears=10;
// double newBalance1=account.projectNewBalance(numberYears);
// System.out.println(""+newBalance1);
System.out.println("Please enter number of years");
int numberYears=input.nextInt();
double newBalance=account.projectNewBalance(numberYears);
System.out.printf("%.2f%n",newBalance);
//Call debit method
System.out.println("Please enter amount to be debited");
double amount=input.nextDouble();
account.debit(amount);
System.out.printf("%.2f%n",balance);
//Call credit method
System.out.println("Please enter amount to be credited");
amount=input.nextDouble();
account.credit(amount);
System.out.printf("%.2f%n",balance);
}
}
Your numbers might always look the same because the local variable is not being updated before printing it out.
Make sure you update the value of balance before your call to System.out.printf("%.2f%n",balance);.
Something like:
balance = account.getBalance();
Shouldn't it be printing the balance of the object you have created and not just "balance":
System.out.println(account.getBalance())?

Categories

Resources