I'm having a bit of trouble setting up a basic bank account in Java. I'm trying to create a transfer method that I can call to transfer funds from one account to another. The problem is that the method I have created has an unnecessary step where I have to declare the name of the object twice. To execute the transfer
method, my current code requires me to write michael.acc.transfer(michael, max);
if I want to transfer funds from michael
to max
. Any ideas on how I can simplify this a bit?
For example: michael.acc.transfer(max);
Here is the class I created with the methods that I can execute to an account:
public class Account {
static double balance;
String accountId;
static int nextId = 0;
static final int ROUTING_NUMBER = 12345;
String bankName;
{
if (ROUTING_NUMBER == 12345) {
bankName = "USA Bank";
}
else {
bankName = "Other bank";
}
}
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
balance = balance - amount;
}
public void transfer (Customer c1, Customer c2) {
double transferAmount;
int routingNumber;
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter transfer amount: ");
transferAmount = input.nextDouble();
System.out.println("Please enter recipient's routing number: ");
routingNumber = input.nextInt();
if (routingNumber == ROUTING_NUMBER) {
System.out.println("Your funds will transfer instantly, you and your recipient share the same bank!");
System.out.println("Bank name: " + bankName);
} else {
System.out.println("Your funds will transfer in 2-3 business days.");
}
}
c1.customerBalance -= transferAmount;
c2.customerBalance += transferAmount;
}
public static String getNextId() {
return "ACCT #" + nextId++;
}
The next class is the one I created with methods to create the customer:
public class Customer {
public String firstName;
public String lastName;
public Account acc;
public double customerBalance = acc.balance;
int defaultBalance = 100;
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Customer() {
firstName = "John";
lastName = "Doe";
}
public void addAccount(double initialBalance) {
acc = new Account();
acc.accountId = "ACCT ID: " + Account.getNextId();
customerBalance = initialBalance;
}
public void addAccount() {
addAccount(100);
}
}
The following are the two accounts that I created to transfer funds from one to the other:
public class Bank {
public static void main(String[] args) {
Customer max = new Customer("Max", "Doe");
max.addAccount(1500);
Customer michael = new Customer("Michael", "Smith");
michael.addAccount(3000);
}
}
static
keyword. The other alternative is to replacec1
withthis
. You should reread about instances, classes and objects :) \$\endgroup\$