Using One Object in Multiple Classes - java

I'm trying to use a setter/getter class in multiple classes to modify a single variable. I understand that I have to use the same object in order for this to work, but I'm unsure on how to make a single object accessible to multiple classes.
public class accountbalance {
private double balance;
//getter
public double getBalance() {
return balance;
}
//Setter
public void setBalance(double newBalance) {
this.balance = newBalance;
}
}
This is where I'm trying to use it first:
public class CreateAccount {
String name;
double social;
int pin;
public CreateAccount()
{
name = "null";
social = 0;
pin = 0;
}
public CreateAccount(String enteredName, double enteredSocial,int enteredPin, double value)
{
name = enteredName;
social = enteredSocial;
pin = enteredPin;
double accountnum = 87495;
accountbalance a1 = new accountbalance();
a1.setBalance(value);
System.out.println(name);
System.out.println(social);
System.out.println("Your new PIN is " + pin);
System.out.println("Your new account balance is " + (a1.getBalance()));
}
}
And then I'm trying to use it again here:
public class deposit {
double enteredAmt;
double amt;
public void deposit() {
System.out.println("Enter an amount to desposit: ");
Scanner in = new Scanner(System.in);
enteredAmt = in.nextDouble();
accountbalance ab1 = new accountbalance();
System.out.println("current balence: " + ab1.getBalance());
amt = ab1.getBalance() + enteredAmt;
ab1.setBalance(amt);
System.out.println("Your new balance is " + (ab1.getBalance()));
}
}

I believe what you're trying to do is use the Command Design Pattern.
If you changed your classes to look more like this, things might work a tad bit better.
public class Account {
// Please do not use SS for an identifier.
private String identifier;
private String name;
// Money needs to be stored in it's lowest common denominator.
// Which in the united states, is pennies.
private long balance;
public Account(String identifier, String name) {
this.identifier = identifier;
this.name = name;
this.balance = 0L;
}
public String getIdentifier() {
return this.identifier;
}
public String getName() {
return this.name;
}
public long getBalance() {
return balance;
}
public void credit(long amount) {
balance =+ amount;
}
public void debit(long amount) {
balance =- amount;
}
}
Then here would be your CreateAccountCommand. It is a bit anemic, but that is ok.
public class CreateAccountCommand {
private String identifier;
private String name;
public CreateAccount(String identifier, String name) {
// Identifier sould actually be generated by something else.
this.identifier = identifier;
name = name;
}
public Account execute() {
return new Account(identifier, name);
}
}
Here is your DepositCommand:
public class DepositCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.credit(amount);
}
}
WithdrawCommand:
public class WithdrawCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.debit(amount);
}
}
Then run everything:
public class Run {
public static void main(String... args) {
CreateAccountCommand createAccountCommand = new CreateAccountCommand("12345678", "First_Name Last_Name");
Account account = createAccountCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Deposit $100.00
DepositCommand depositCommand = new DepositCommand(account, 10000);
depositCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Withdraw $75.00
WithdrawCommand withdrawCommand = new WithdrawCommand(account, 7500);
withdrawCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
}
}

Related

Linking Credit Card and Debit Card classes to a Bank Account Class

I'm learning Java, and one of my assignments is to create Credit and Debit Cards classes so that you can create new cards linked to a new individual account when one is created. The credit card should store purchases, and when the user makes a payment (total or partial), substract the amount from the account (plus 3% interest). The debit card immediately substracts the purchase's amount from the account.
I have written everything and made it work, but only as nested classes within the Account class. Is there a way to have Account, Credit and Debit as three separate classes and make it so that every time that you create a new account, you can optionally create cards linked to each new individual account?
Disclaimer: I'm trimming some of the code because it's all in spanish so I don't have to translate it all (mainly booleans to check for positive amounts and stuff like that), but the code is still functional. Thanks a lot in advance!
package accounts;
public class Account {
protected static double balance;
protected static String accountNumber;
public Account() {
}
public Account(String accountNumber, double balance) {
Account.accountNumber = accountNumber;
Account.balance = balance;
}
public double getBalance() {
return balance;
}
public String getAccountNumber() {
return accountNumber;
}
public void deposit(double depositAmount) {
Account.balance += depositAmount;
}
public void extraction(double extractionAmount) {
Account.balance -= extractionAmount;
}
public void showBalance() {
System.out.println("Your current balance is: " + getBalance());
}
protected static class DebitCard {
private String userName;
private int cardNumber;
public DebitCard () {
}
public DebitCard (String userName, int cardNumber) {
this.userName = userName;
this.cardNumber = cardNumber;
}
public String getUserName() {
return userName;
}
public int getCardNumber() {
return cardNumber;
}
public void debitPurchase(double purchaseAmount) {
Account.balance -= purchaseAmount;
}
}
protected static class CreditCard {
private String userName;
private int cardNumber;
private double creditCardDebt;
private double limit;
public CreditCard () {
}
public CreditCard(String userName, int cardNumber, double limit) {
this.userName = userName;
this.cardNumber = cardNumber;
this.limit = limit;
}
public String getUserName() {
return userName;
}
public int getCardNumber() {
return cardNumber;
}
public double getLimit() {
return limit;
}
public double getCrediCardDebt() {
return creditCardDebt;
}
public void creditCardPurchase(double purchaseAmount) {
if (this.creditCardDebt + purchaseAmount > this.limit) {
Error notEnoughLimit = new Error("There's not enough limit to make this purchase");
throw notEnoughLimit ;
} else {
this.creditCardDebt += purchaseAmount + (purchaseAmount * 0.03);
this.limit -= purchaseAmount;
this.creditCardDebt += purchaseAmount + (purchaseAmount* 0.03);
this.limit -= purchaseAmount;
}
}
public void payCard(double payAmount) {
Account.balance -= payAmount;
this.creditCardDebt = this.creditCardDebt - payAmount;
}
}
}
Yes it is possible. But before you do that, you should solve the problem caused by declaring balance and accountNumber as static variables. By doing that, you have made every Account instance share one account number and one balance.
Those variables should also be private so that other classes can't access or change them directly.
Once you have fixed that, you should then change the constructors for Credit and Debit to take an instance of Account as a parameter. They store this in a private field, and then perform operations to add and remove money from the Account ... via operations on the Account object.

Wrong output when creating an account (Object)

I'm having issues with my program which is a subclass of another program I wrote called account. I create an account (george) and set values to it, a string for name, int id, and double balance. I'm not getting any errors but the only correct value is the string for name. I think it has to do something with my Overridden toString() method in the account class not grabbing the correct values.
My output:
Account holder name: George
Account id: 0
Annual interest: 1.5
Monthly Interest Rate: 0.00125
Balance 109.0
Transaction:
Correct ouput:
Account holder name: George
Account id: 1122
Annual interest: 0.015
Monthly Interest Rate: 0.013862499999999998
balance: 1109.0
Transaction:
type: d amount: 30.0 balance: 1030.0 deposit
type: d amount: 40.0 balance: 1070.0 deposit
type: d amount: 50.0 balance: 1120.0 deposit
type: w amount: 5.0 balance: 1115.0 withdrawal
type: w amount: 4.0 balance: 1111.0 withdrawal
type: w amount: 2.0 balance: 1109.0 withdrawal
CustomerAccount.class :
public class CustomerAccount extends Account {
public static String name;
public static void main(String[] args) {
// TODO Auto-generated method stub
CustomerAccount george = new CustomerAccount("George", 1122, 1000.0);
george.setannualInterest(1.5);
Account c1 = george;
george.deposit(30);
george.deposit(40);
george.deposit(50);
george.withdraw(5);
george.withdraw(4);
george.withdraw(2);
System.out.println(c1.toString());
CustomerAccount john = new CustomerAccount("John", 1123, 500);
john.setannualInterest(2.5);
Account c2 = john;
ArrayList<CustomerAccount> sort = new ArrayList<CustomerAccount>();
//sort.add(c1);
//sort.addAll(c2);
}
CustomerAccount(String name, int id, double balance) {
this.name = name;
id = getId();
balance = getBalance();
}
ArrayList<Transaction> transactions = new ArrayList<Transaction>();
}
Transaction class:
class Transaction extends Account {
private java.util.Date dateCreated;
private char type;
private double amount;
private double balance;
private String description;
private double transaction;
Transaction() {
}
Transaction(char type, double amount, double balance, String description) {
dateCreated = new java.util.Date();
this.type = type;
this.amount = amount;
this.balance = balance;
this.description = description;
}
public String getDateCreated() {
return dateCreated.toString();
}
public char getType() {
return type;
}
public double getAmount() {
return amount;
}
public double getBalance() {
return balance;
}
public String getDescription() {
return description;
}
public double getTransaction() {
return this.transaction;
}
public void setType(char type) {
this.type = type;
}
public void setAmount(double amount) {
this.amount = amount;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setDescription(String description) {
this.description = description;
}
public void setTransaction(double amount) {
this.transaction = amount;
}
}
Account.class :
class Account {
private int id = 0;
private double balance = 0.0;
private double annualInterestRate = 0.0;
private java.util.Date dateCreated;
// set dateCreated for the time and date the account was created
Account() {
dateCreated = new java.util.Date();
}
// Set accounts id and balance equal to this objects
Account(int id, double balance){
this();
this.id = id;
this.balance = balance;
}
// Getters and Setters manipulating variables to be set to the created account
// Setters have no return value and set itself equal to the variable and getters
// grab the variables and return them.
public int getId() {
return this.id;
}
public double getBalance() {
return this.balance;
}
public double getannualInterestRate() {
return this.annualInterestRate;
}
public String getDateCreated() {
return this.dateCreated.toString();
}
public void setId(int id) {
this.id = id;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setannualInterest(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMonthlyInterestRate() {
return (annualInterestRate / 100) / 12;
}
public double getMonthlyInterest() {
return balance * getMonthlyInterestRate();
}
// set balance of withdraw to balance - amount = balance
public void withdraw (double amount) {
if(amount < balance) {
balance -= amount;
}
}
// set balance of deposit to balance + amount = balance
public void deposit(double amount) {
balance += amount;
//Transaction.add(new Transaction('D', amount, balance, "Deposit to account"));
}
#Override
public String toString() {
return "Account holder name: " + CustomerAccount.name +
"\nAccount id: " + id +
"\nAnnual interest: " + this.getannualInterestRate() +
"\nMonthly Interest Rate: " + this.getMonthlyInterestRate() +
"\nBalance " + this.getBalance() +
"\nTransaction: ";
}
}
To set the values in the Account class, you need to call
super(id, balance)
in the CustomerAccount constructor to call the constructor for Account
Try that

System.out.printIn() not working on my code

it is showing me "cannot find symbol method printIn(java.lang.string)
please what is the error, i have used 3 different IDES.
whats wrong with the System.out.printIn()
public class Account
{
private String owner;
private int balance;
public Account (String name)
{
owner = name;
balance = 0;
}
public void deposit(int anAmount)
{
balance += anAmount;
}
public int withdraw(int anAmount)
{
int amountWithdrawn;
if (anAmount <= balance )
amountWithdrawn = anAmount;
else
amountWithdrawn = balance;
balance -= amountWithdrawn;
return amountWithdrawn;
}
public void print()
{
System.out.printIn("Owner =" + owner +" Balance=" + balance);
}
}
That is not printIn(). You typed letter I for Ikea
That is println() you had to use letter l for lima

Overdraft method for bank account

I'm trying to apply a method that will check if the account has went over the OVERDRAFT_LIMIT. I have tried several things but haven't succeeded.
This was something I did but did not know how to apply it:
public void testForOverdraft(double balancE)
{
if(balancE <= 0 && balancE >= OVERDRAFT_LIMIT)
{
withdraw(10);
System.out.println("The account is overdrawn.");
}
else if(balancE <= 0 && balancE <= OVERDRAFT_LIMIT)
{
withdraw(20);
System.out.println("The account is locked until a deposit is made to bring the account up to a positive value.");
}
}
Account:
import java.util.Date;
public class Account
{
private int id;
private double balance;
private double annualInterestRate;
private Date dateCreated;
private double monthlyInterestRate;
public Account()
{
id = 0;
balance = 0;
annualInterestRate = 0;
}
public Account(int iD, double balancE)
{
id = iD;
balance = balancE;
}
public void setID(int iD)
{
id = iD;
}
public int getID()
{
return(id);
}
public void setBalance(double balancE)
{
balance = balancE;
}
public double getBalance()
{
return(balance);
}
public void setAnnualInterestRate(double AIR)
{
annualInterestRate = AIR;
}
public double getAnnualInterestRate()
{
return(annualInterestRate);
}
public void setDateCreated(Date dateCreated)
{
this.dateCreated = dateCreated;
}
public double getMonthlyInterestRate()
{
return((annualInterestRate / 100) / 12);
}
public double getMonthlyInterest()
{
return(balance * monthlyInterestRate);
}
public void withdraw(double ammount)
{
balance = balance - ammount;
setBalance(balance);
}
public void deposit(double ammount) {
balance = balance + ammount;
setBalance(balance);
}
}
CheckingAccount:
public class CheckingAccount extends Account
{
final static double OVERDRAFT_LIMIT = -50.00;
private double annualInterest;
public CheckingAccount()
{
super();
}
public CheckingAccount(int iD, double balancE)
{
super(iD, balancE);
}
public double getAnnualInterest()
{
return((getBalance() * getAnnualInterestRate()) / 100);
}
}
Test:
public class Test extends CheckingAccount
{
public static void main(String [] args)
{
CheckingAccount a1 = new CheckingAccount(1122, 15.00);
a1.withdraw(5.00);
a1.deposit(00.00);
a1.setAnnualInterestRate(4.5);
Date dat = new Date();
System.out.println("Balance: " +
"\nMonthly Interest: " + a1.getMonthlyInterest() +
"\nDate Created: " + dat);
}
}
Check the new balance before assinging it in the withdraw method
The withdraw method will return true if it was success full
public boolean withdraw(double ammount)
{
boolean success ;
double aux ;
aux = balance - ammount ;
if(aux < OVERDRAFT_LIMIT)
{
success = false ;
}
else
{
setBalance(aux);
success = true ;
}
return success ;
}
Then to use it just go like this
if(!withdraw(60))
{
System.out.println("The account is locked until a deposit is made to bring the account up to a positive value.");
}

Output not displaying anything [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I have an assignment in Advanced Inheritance for Java and have the code pretty much hammered out but am having issues finishing it off and making it actually display the output. The program was split into 4 different parts and I have them listed below.
Account.java
public abstract class Account
{
protected long accountNumber;
protected double accountBalance;
public long getAccountNumber()
{
return accountNumber;
}
public double getAccountBalance()
{
return accountBalance;
}
public void setAccountNumber(long number)
{
number = accountNumber;
}
public void setAccountBalance(double balance)
{
balance = accountBalance;
}
public void setUpAccount(long number, double balance) //look up constructors
{
number = accountNumber;
balance = accountBalance;
}
public String toString()
{
return "Account Number: " + accountNumber + " Account Balance: " + accountBalance;
}
public abstract double computeInterest(int intPeriod);
}
Checkings.java
public class Checking extends Account
{
public String toString()
{
String info = "Checking\nAccount Number: " + accountNumber +
"\nAccount Balance: " + accountBalance ;
return info;
}
public Checking(long number)
{
number = accountNumber;
}
public double computeInterest(int intPeriod)
{
double total = ((accountBalance - 700) * .02) * 3;
return total;
}
}
Savings.java
public class Savings extends Account
{
private double interestRate;
public double getInterest()
{
return interestRate;
}
public void setInterest(double inter)
{
inter = interestRate;
}
public String toString()
{
String info = "Savings\nAccount Number: " + accountNumber + " \nAccount Balance: "
+ accountBalance + " \nInterest Rate: " + interestRate;
return info;
}
public Savings(long number, double interest)
{
number = accountNumber;
interest = interestRate;
}
public double computeInterest(int intPeriod)
{
double total = Math.pow((1 + interestRate), intPeriod) * accountBalance - accountBalance;
return total;
}
}
AccountArray.java
public class AccountArray
{
public static void main(String[] args)
{
Account[] refAccount = new Account[10];
/*refAccount[0] = new Checking(100);
refAccount[1] = new Checking(101);
refAccount[2] = new Checking(102);
refAccount[3] = new Checking(103);
refAccount[4] = new Checking(104);
refAccount[5] = new Savings(105, .02);
refAccount[6] = new Savings(106, .02);
refAccount[7] = new Savings(107, .02);
refAccount[8] = new Savings(108, .02);
refAccount[9] = new Savings(109, .02);
refAccount[0].setAccountBalance(1000.0);
refAccount[1].setAccountBalance(2000.0);
refAccount[2].setAccountBalance(3000.0);
refAccount[3].setAccountBalance(4000.0);
refAccount[4].setAccountBalance(5000.0);
refAccount[5].setAccountBalance(6000.0);
refAccount[6].setAccountBalance(7000.0);
refAccount[7].setAccountBalance(8000.0);
refAccount[8].setAccountBalance(9000.0);
refAccount[9].setAccountBalance(10000.0);*/
for(int inc = 0; inc < 10; inc++ )
{
refAccount[0] = new Checking(100);
refAccount[1] = new Checking(101);
refAccount[2] = new Checking(102);
refAccount[3] = new Checking(103);
refAccount[4] = new Checking(104);
refAccount[5] = new Savings(105, .02);
refAccount[6] = new Savings(106, .02);
refAccount[7] = new Savings(107, .02);
refAccount[8] = new Savings(108, .02);
refAccount[9] = new Savings(109, .02);
refAccount[0].setAccountBalance(1000.0);
refAccount[1].setAccountBalance(2000.0);
refAccount[2].setAccountBalance(3000.0);
refAccount[3].setAccountBalance(4000.0);
refAccount[4].setAccountBalance(5000.0);
refAccount[5].setAccountBalance(6000.0);
refAccount[6].setAccountBalance(7000.0);
refAccount[7].setAccountBalance(8000.0);
refAccount[8].setAccountBalance(9000.0);
refAccount[9].setAccountBalance(10000.0);
}
for(int ctr = 0; ctr < 10; ctr++)
{
System.out.println(refAccount[ctr].toString());
}
}
}
Is there something I'm like really obviously missing? It all compiles just fine but the output just displays 0s instead of the Account Numbers, Balance or Interest.
Any help would be very much appreciated since I'm running out of time.
All of your setter methods look the wrong way round, you've got them as...
public void setAccountNumber(long number)
{
number = accountNumber;
}
public void setAccountBalance(double balance)
{
balance = accountBalance;
}
All you're doing there is setting the parameter value, they should be...
public void setAccountNumber(long number)
{
accountNumber= number;
}
public void setAccountBalance(double balance)
{
accountBalance= balance;
}
You can make sure this doesn't happen my making your parameters final
Have a look at your constructors and setters You inverse your variable attribution
Ex
public void setAccountNumber(long number)
{
number = accountNumber;
}
should be
public void setAccountNumber(long number)
{
accountNumber = number;
}
same for all your setters and constructors

Categories