I get this Exception when I try to create a new customer in my bank account program:
Exception in thread "main" java.lang.NullPointerException
at bank.program.Customer.addAccount(Customer.java:18)
at bank.program.BankProgram.main(BankProgram.java:24)
Java Result: 1
What does it mean, and what do I need to change to get rid of it?
Bank class:
public class Bank {
String bankName;
private ArrayList<Customer> customers = new ArrayList<Customer>();
Bank(String bankName) {
this.bankName = bankName;
}
public void addCustomer(Customer newCustomer) {
customers.add(newCustomer);
}
}
Account class:
public abstract class Account {
protected double balance = 0;
protected String accountId;
public Account() {} //Defaultkonstruktor
public Account(double bal, String id) { //Konstruktor
if (balance >= 0) {
balance = bal;
}
else {
balance = 0;
}
accountId = id;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
public abstract double getBalance();
public abstract String getAccountId();
public void transfer(double amount, Account account) {
account.deposit(amount);
balance -= amount;
}
}
SavingsAccount class:
public class SavingsAccount extends Account {
private double interest = 2.9;
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id) {
super(bal, id);
}
#Override
public void deposit(double amount) {
}
#Override
public void withdraw(double amount) {
}
#Override
public double getBalance() {
}
#Override
public String getAccountId() {
}
}
Customer class:
public class Customer {
private String firstName;
private String lastName;
private String number;
private ArrayList<Account> accounts;
Customer(String firstName, String lastName, String number) {
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
}
public void addAccount(SavingsAccount account) {
accounts.add(account);
}
public ArrayList<Account> getAccounts() {
return accounts;
}
}
Bank program class:
public class BankProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfCustomers = 0;
Bank bank = new Bank("Bank name");
System.out.print("Enter amount to deposit: ");
double amount = input.nextDouble();
System.out.println("Account number: " + numberOfCustomers);
System.out.print("First name: ");
String firstName = input.next();
System.out.print("Last name: ");
String lastName = input.next();
System.out.print("Customer number: ");
String pnumber = input.next();
Customer newCustomer = new Customer(firstName, lastName, pnumber);
SavingsAccount savingsAccount = new SavingsAccount(amount, "11");
newCustomer.addAccount(savingsAccount);
bank.addCustomer(newCustomer);
}
}
You're trying to add an account without initializing the ArrayList in which they're stored. Add this to your Customer constructor.
this.accounts = new ArrayList<Account>();
In your Customer class, you declare an ArrayList accounts. Then, you have a method called addAccount, but it seems as though this accounts was never initialized.
Somewhere where you create your Customer object, you need to say:
newCustomer.accounts = new ArrayList<Account>();
Related
I have been stuck on this for more than 3 days now.
In my main class, ATM, in method verifyCustomer(). When signing in, I'm trying to find a way to ask for a customer ID first. Once verified, then the customers accounts will be listed. After that, the customer will then be prompted to choose which account they want to access, and from there they will be prompted to enter the account number and then the password.
I also have a Gold Account class in which only customers above a certain age "65" are allowed the option to open up. I am having trouble figuring out the logic on how to access that in the initialize() method as well.
I have 3 subclasses to the Account superclass which I didn't include due to there already being too much code.
Any tips?
ATM.java
public class ATM {
private InputReader reader;
private String accountNumber;
private String passcode;
private boolean customerVerified;
private String customerID;
private Bank theBank;
private Customer currentCustomer;
public ATM() {
super();
initialize();
run();
}
public static void main(String[] args) {
new ATM();
}
public void run() {
reader = new InputReader();
boolean exit = false;
while (!exit) {
System.out.println("Welcome to Bank");
System.out.println("Choose one of the following options");
System.out.println("1 - Sign In");
System.out.println("2 - Deposit");
System.out.println("3 - Withdraw");
System.out.println("4 - Display Account Info");
System.out.println("5 - Exit");
System.out.println(">");
int choice = reader.getIntInput();
switch (choice) {
case 1:
verifyCustomer();
break;
case 2:
transactDeposit();
break;
case 3:
transactWithdraw();
break;
case 4:
displayAccountInformation();
break;
case 5:
System.out.println("Thank you for banking at Bank");
System.exit(0);
}
}
}
public void initialize() {
Customer tom = new Customer("Tom", "Smith", "123",70,"A001");
Customer jane = new Customer("Jane", "Smith", "789",18,"A002");
Customer bob = new Customer("Bob", "Smith", "456",32,"A003");
Account tomChequing = new ChequingAccount("CH-123", 0.0,2);
Account tomSavings = new SavingsAccount("SA-123", 50.0);
Account tomGold = new GoldAccount("GL-123",50.0,2.0);
Account janeChequing = new ChequingAccount("CH-789",0.0,2);
Account janeSavings = new SavingsAccount("SA-789", 0.0);
Account bobChequings = new ChequingAccount("CH-456",0.0,5);
Account bobSavings = new SavingsAccount("SA-456", 100.0);
tom.addAccount(tomChequing);
tom.addAccount(tomSavings);
tom.addAccount(tomGold);
jane.addAccount(janeChequing);
jane.addAccount(janeSavings);
bob.addAccount(bobChequings);
bob.addAccount(bobSavings);
theBank = new Bank();
theBank.addCustomer(tom);
theBank.addCustomer(jane);
theBank.addCustomer(bob);
if(currentCustomer.getAge() >= 65) {
currentCustomer.
}
}
public void transactDeposit() {
if (customerVerified) {
System.out.println("Enter the amount to deposit: ");
currentCustomer.getAccountList().addToBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void transactWithdraw() {
if (customerVerified) {
System.out.println("Enter the amount to withdraw: ");
currentCustomer.getAccount().subtractFromBalance(reader.getDoubleInput());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a transaction.");
verifyCustomer();
}
}
public void displayAccountInformation() {
if (customerVerified) {
System.out.println("Here is your information.");
System.out.println(currentCustomer.toString());
} else {
System.out.println("ERROR: You must LOGIN before you can perform a trasnsaction.");
verifyCustomer();
}
}
public void verifyCustomer() {
System.out.println("Enter your Customer ID");
customerID = reader.getStringInput();
System.out.println("Which account do you want to access?");
System.out.println("Enter Account Number: ");
accountNumber = reader.getStringInput();
System.out.println("Enter your passcode");
passcode = reader.getStringInput();
currentCustomer = Bank.theBank.get(accountNumber);
if (currentCustomer != null) {
if (passcode.equals(currentCustomer.getPasscode()) && customerID.equals(currentCustomer.getCustomerID())) {
customerVerified = true;
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
} else {
System.out.println("ERROR: Either account number, customer id, or passcode is not correct.");
run();
}
}
}
Customer.java
import java.util.ArrayList;
public class Customer {
private String firstName;
private String lastName;
private String passcode;
private int age;
private String customerID;
private ArrayList<Account> accounts;
public Customer(String firstName, String lastName, String passcode, int age, String customerID) {
setFirstName(firstName);
setLastName(lastName);
setPasscode(passcode);
setAge(age);
setCustomerID(customerID);
accounts = new ArrayList<>();
}
public void addAccount(Account account) {
accounts.add(account);
}
public ArrayList<Account> getAccountList() {
return accounts;
}
public void setAccountList(ArrayList<Account> account) {
this.accounts = account;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
if (firstName != null && !firstName.trim().isEmpty()) {
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
if (lastName != null && !lastName.trim().isEmpty()) {
this.lastName = lastName;
}
}
public String getPasscode() {
return passcode;
}
public void setPasscode(String passcode) {
if (passcode != null && !passcode.trim().isEmpty()) {
this.passcode = passcode;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID){
this.customerID = customerID;
}
}
Account.java
import java.util.ArrayList;
public class Account {
private String accountNumber;
private double balance;
private boolean active;
protected ArrayList<String> transactionInfo;
public Account() {
super();
}
public Account(String accountNumber, double balance) {
super();
if(accountNumber != null) {
this.accountNumber = accountNumber;
}
setBalance(balance);
active = true;
transactionInfo = new ArrayList<String>();
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public boolean isActive() {
return active;
}
public void setBalance(double balance) {
if(balance >= 0){
this.balance = balance;
}
}
public void setActive(boolean active) {
this.active = active;
}
public void addToBalance(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void subtractFromBalance(double amount) {
if (amount > 0) {
balance -= amount;
}
}
public void addTransactionInfo(String info) {
if(info != null) {
transactionInfo.add(info);
}
}
public void displayAccountRecords() {
if(transactionInfo != null) {
for(String info: transactionInfo) {
System.out.println(info);
}
}
}
}
Bank.java
import java.util.HashMap;
public class Bank {
public static HashMap<String, Customer> theBank;
public Bank() {
super();
theBank = new HashMap<>();
}
public void addCustomer(Customer newCustomer) {
if (newCustomer != null) {
theBank.put(newCustomer.getCustomerID(), newCustomer);
}
}
// use the customerID to access their collection of accounts
public void closeAccount(String customerID, String accountNumber) {
Customer c = theBank.get(customerID);
if(c != null) {
for(Account a: c.getAccountList()) {
if(accountNumber.equals(a.getAccountNumber())) {
theBank.remove(accountNumber);
}
}
//if (theBank.containsKey(customerID)) {
//theBank.get(customerID).getAccountList().remove(accountNumber);
}
}
public static void displayCustomerInformation(Customer customer){
if(customer != null){
System.out.println(customer);
}
}
public static void displayAllCustomers(){
for(Customer customer : theBank.values()){
System.out.println(customer);
}
}
}
You have a HashMap in class Bank and the map key is customer ID. Just add a getCustomer(String) method in class Bank.
public Customer getCustomer(String id) {
return theBank.get(id);
}
**
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("********WELCOME TO CUSTOMER DETAIL**********");
System.out.println("");
BankAccount customerDetails = new BankAccount();
customerDetails.setAccountNumber(527553054);
System.out.println("Account Number : " + customerDetails.getAccountNumber());
customerDetails.setBalance(300000.00);
System.out.println("Balance : " + customerDetails.getBalance());
customerDetails.setCustomerName("Anish Shrestha");
System.out.println("Customer Name : " + customerDetails.getCustomerName());
customerDetails.setEmail("blah#gmail.com");
System.out.println("Email : " + customerDetails.getEmail());
customerDetails.setPhoneNumber(980709277);
System.out.println("Phone Number : "+ customerDetails.getPhoneNumber());
System.out.println("");
System.out.println("*********************");
BankAccount deposit = new BankAccount();
deposit.depositFunds(566);
}
}
package learnJava;
public class BankAccount {
public void depositFunds(double depositAmount) {
this.balance += depositAmount;
System.out.println("The total sum of money : " + this.balance);
}
private long accountNumber ;
private double balance;
private String customerName;
private String email;
private long phoneNumber;
//SETTER
public void setAccountNumber(long accountNumber) {
this.accountNumber = accountNumber;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public void setEmail(String email) {
this.email = email ;
}
public void setPhoneNumber(long phoneNumber) {
this.phoneNumber = phoneNumber ;
}
//GETTER
public long getAccountNumber() {
return this.accountNumber;
}
public double getBalance() {
return this.balance;
}
public String getCustomerName() {
return this.customerName;
}
public String getEmail() {
return this.email;
}
public long getPhoneNumber() {
return this.phoneNumber;
}
}
**
i could not add up deposit Amount to main balance
Is it due to the setter/getter or there is something wrong in my code......
I am beginner so help me out guysss.....
I am not able to access the data of getter
What could be the problem or is it a rule?
I have copy-paste your code, there is no problem. In comment, the output :
BankAccount deposit = new BankAccount();
deposit.depositFunds(100); // The total sum of money : 100.0
deposit.depositFunds(100); // The total sum of money : 200.0
System.out.println(deposit.getBalance()); // 200.0
I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
public String getStreetName() {
return streetName;
}
public void setStreetName (String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity (String city) {
this.city = city;
}
public int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class
In main I do this:
First I create a new customer with its first name, lastname and number.
Then I create two savingsAccounts, with its amount, id and interest rate.
I then add the two savingsAccounts to the new customer.
Finally I add the new customer to the bank.
Customer newCustomer = new Customer(firstName, lastName, pnumber);
SavingsAccount savingsAccount1 = new SavingsAccount(400, "1", 4); //400$ into account no.1, with interest 4%
SavingsAccount savingsAccount2 = new SavingsAccount(300, "2", 3);
newCustomer.addAccount(savingsAccount1);
newCustomer.addAccount(savingsAccount2);
bank.addCustomer(newCustomer);
Here is class Bank:
public class Bank {
String bankName;
private ArrayList<Customer> customers = new ArrayList<Customer>();
Bank(String bankName) {
this.bankName = bankName;
}
public void addCustomer(Customer newCustomer) {
customers.add(newCustomer);
}
}
Here is class Customer:
public class Customer {
private String firstName;
private String lastName;
private String number;
private ArrayList<Account> accounts;
Customer(String firstName, String lastName, String number) {
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
this.accounts = new ArrayList<Account>();
}
public void addAccount(SavingsAccount account) {
accounts.add(account);
}
public void addAccount(CreditAccount account) {
accounts.add(account);
}
public ArrayList<Account> getAccounts() {
return accounts;
}
}
Here is class SavingsAccount (that inherits class Account):
public class SavingsAccount extends Account {
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id, double inte) {
super(bal, id, inte);
}
#Override
public void deposit(String number, String id, double amount) {
}
#Override
public void withdraw(String number, String id, double amount) {
}
#Override
public void transfer(String number, String id, double amount) {
}
#Override
public double getBalance() {
}
#Override
public String getAccountId() {
return accountId;
}
#Override
public double getInterest(){
return interest;
}
}
My problem is:
How can I write code in class SavingsAccount to deposit, withdraw, transfer money for a certain customer, for a certain account?
Let's say I want to deposit 500 to customer no.2 on his account no.1.
That should be something like savingsAccount.deposit("2", "1", 500);
I just can't figure out how to access customer number 2, and his account number 1.
Can anyone help me please?
What you could do is have a method for that in the Bank class:
public class Bank {
// Your stuff
// new method:
public boolean transfer(Account accountFrom, double amount, String nameTo, int account) {
//check if the balance can be deposit from the account
if(amount <= accountFrom.getBalance()) {
//Check if the person exists in the bank
String name = nameTo.split(" "); // name[0] is the first name, name[1] last name
boolean success = false;
for(Customer c: customers) {
if(c.getFirstName().equalsIgnoreCase(name[0]) &&
c.getLastName().equalsIgnoreCase(name[1]) {
for(Account a : c.getAccounts()) {
if(a.getAccountId() == account) {
// Add it to the account
a.deposit(amount);
success = true;
break;
}
}
break;
}
}
// Deposit it from the account (That class should only keep track of money, so it
// only takes an argument to deposit or withdraw a value, the rest is done by the bank
// Only do this if money has been dsposited at the target account
if(success){
accountFrom.withdraw(amount);
return true;
}
}
return false;
}
}
For this to happen you have to structurely change your setup.
Have the accounts only manage money, those accounts get added to a customer. The customer is the person who communicates between the bank and himself. And finally the bank communicates with customers.
I hope this will help you in the direction
import java.text.DecimalFormat;
import java.util.ArrayList;
public class AccountOwner {
private Account account;
private String firstname;
private String lastname;
private String address;
private double currentBalance;
private ArrayList<Integer> withdrawAmount = new ArrayList<Integer>(5);
private ArrayList<Double> deposits = new ArrayList<Double>();
private ArrayList<Double> purchases = new ArrayList<Double>(5);
private DecimalFormat formatter = new DecimalFormat("##0.00");
public AccountOwner(String firstname, String lastname, String address) {
this.firstname = firstname;
this.lastname = lastname;
this.address = address;
}
public String getFirstName() {
return firstname;
}
public String getLatName() {
return lastname;
}
public String getAddress() {
return address;
}
public String checkBalance() {
for (Double deposit : deposits) {
this.currentBalance += deposit;
}
return formatter.format(currentBalance);
}
public void makeDeposit(double amount) {
deposits.add(amount);
}
public void viewAllDeposits() {
double allDeposits = 0.0;
System.out.println("All deposits till today:");
for (int i = 0; i < deposits.size(); i++) {
allDeposits = deposits.get(i);
System.out.print("\t"+"$"+allDeposits);
}
System.out.println();
}
public void withdrawMoney(int amount) {
withdrawAmount.add(amount);
currentBalance -= amount;
}
public String getActualBalance() {
return formatter.format(currentBalance);
}
public void withdrawAmounts(){
System.out.println("All Withdrawls till today");
for(int i = 0; i < withdrawAmount.size(); i++){
System.out.print("\t"+"$"+withdrawAmount.get(i));
}
System.out.println();
}
public void makePurchase(double itemPrice){
purchases.add(itemPrice);
this.currentBalance -= itemPrice;
}
public void viewAllmadePurchases() {
double purchase = 0.0;
System.out.println("All purchases made till today:");
for (int i = 0; i < purchases.size(); i++) {
purchase = purchases.get(i);
System.out.print("\t"+"$"+purchase);
}
}
public void viewMyPersonalInformation(){
System.out.println("Firstname:" + this.firstname);
System.out.println("LastName:" +this.lastname);
System.out.println("Address:" +this.address);
System.out.println("Balance:" +this.checkBalance());
viewAllDeposits();
withdrawAmounts();
viewAllmadePurchases();
}
public class Account {
private AccountOwner customer;
private int accountNumber;
public Account(){
customer = null;
accountNumber = 0000000;
}
public Account(int accountNumber, AccountOwner owner){
this.accountNumber = accountNumber;
customer = owner;
}
public int accountNumberIs(){
return accountNumber;
}
public class BankManager {
private Account account;
private AccountOwner accountOwner;
private int accountNumber;
public void createNewAccount(int accountNumber, AccountOwner owner){
account = new Account(accountNumber, owner);
this.accountNumber = accountNumber;
this.accountOwner = owner;
}
public int getaccountNumber(){
return accountNumber;
}
public void setAccountNumber(int newaccountnumber){
accountNumber = newaccountnumber;
}
public void customerInformation(){
accountOwner.viewMyPersonalInformation();
}
public class MainProgram {
/**
* #param args
*/
public static void main(String[] args) {
BankManager manager = new BankManager();
AccountOwner owner = new AccountOwner("Tom", "Smith", "208 W 119th St");
manager.createNewAccount(389745, owner);
Account acc = new Account();
owner.makeDeposit(550);
owner.makeDeposit(700);
owner.makeDeposit(122.93);
owner.makeDeposit(195.93);
owner.withdrawMoney(200);
owner.makePurchase(200);
owner.makeDeposit(100);
owner.makePurchase(1220);
owner.withdrawMoney(30);
owner.viewMyPersonalInformation();
System.out.println();
System.out.println();
System.out.println();
System.out.println(acc.accountNumberIs());
The problem that i have is i'm trying to access the account number from the accountowner without involving a reference to the bankmanager class.. how can i get it to work. I have
been trying to using the account class itself cause i created a constructor and assign those
paramaters to the fields in the account class but seems not to work
This code contains a bug :
public Account(int accountNumber, AccountOwner owner){
AccountOwner cstomer = owner;
int acctNumber = accountNumber;
accountNumber = acctNumber;
//System.out.println(accountNumber);
}
The accountNumber parameter you're passing into your constructor is taking precedence over your class's accountNumber field. your Account's accountNumber field is never actually getting set.
This is equivalent to :
public Account(int accountNumber, AccountOwner owner){
AccountOwner cstomer = owner;
accountNumber = accountNumber;
}
to make sure that you're accessing the field use the this keyword as in: this.accountNumber
public Account(int accountNumber, AccountOwner owner){
AccountOwner cstomer = owner;
this.accountNumber = accountNumber;
//System.out.println(accountNumber);
}
There is another bug, the Account.customer is not assigned :
public Account(int accountNumber, AccountOwner owner){
customer = owner;
this.accountNumber = accountNumber;
}
I recommend you to learn to use a debugger or still better write unit tests (first).
class AccountOwner {
//...
private Account account;
//...
public Integer getAccountNumber() {
return this.account != null ? this.account.accountNumberIs() : null;
}
}
You have set your accountNumber type to be int and set it to 0000000 (which is equal to just 0 for an int type) therefore you are getting 0 when you call getAccountNumber() method.
Instead, change accountNumber type to String and initialize it to '0000000'. You will see 0000000 being printed then.