0

Trying to create a bank management app. Not able to execute Login method after creating a new user. Feel something is wrong with the object creation for populating the Perons and Account arrays. Please help.

/Account class to hold account details/

public class Account extends Persons {

    int accountNum;
    int pin;
    float checkingBal;
    float savingBal;

    float withDrawAmount;
    float depositAmmount;
    float transferAmount;

    public  Account(){ }
    public Account(int accountNum, float checkingBal, float savingBal, int pin ){
        this.accountNum = accountNum;
        this.checkingBal = checkingBal;
        this.savingBal = savingBal;
        this.pin = pin;
    }

    public void setAccountNum(int accountNum){
        this.accountNum = accountNum;
    }

    public void setPin(int pin){
        this.pin = pin;
    }

    public int getAccountNum(){
        return accountNum;
    }

    public int getPin(){
        return pin;
    }


    public void withDraw(float withDrawAmount){

        this.savingBal = this.savingBal - withDrawAmount;
    }

    public void deposit(float depositAmmount){

        this.checkingBal = this.checkingBal + depositAmmount;
    }

    public void transfer(float transferAmount, String fromAccount, String toAccount){

        if(fromAccount == "Checking" && toAccount == "Savings"){

            this.checkingBal = this.checkingBal - transferAmount;
            this.savingBal = this.savingBal + transferAmount;
        }else if(fromAccount == "Savings" && toAccount == "Checking"){

            this.savingBal = this.savingBal - transferAmount;
            this.checkingBal = this.checkingBal + transferAmount;
        }

        System.out.print("Your New Checking Balance Is: "+this.checkingBal);
        System.out.print("Your New Savings Balance Is: "+this.savingBal);
    }

    public float checkBalance(int accountNum){
        float totalBalance = 0;
        if(this.accountNum == accountNum){
            totalBalance = this.checkingBal + this.savingBal;
        }
        return totalBalance;

    }
}

/*******************************************************************************************************/

/Persons class to hold all the people having account./

import java.util.Date;

public class Persons {

    String fname;
    String lname;
    int age;
    String dob;
    String address;
    float yearlyIncome;
    int accountNum;


    public Persons(){}
        public Persons(String fname, String lname, int age, String dob, String address, float yearlyIncome, int accountNum){
            this.fname = fname;
            this.lname = lname;
            this.age = age;
            this.dob = dob;
            this.address = address;
            this.yearlyIncome = yearlyIncome;
            this.accountNum = accountNum;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setYearlyIncome(float yearlyIncome) {
        this.yearlyIncome = yearlyIncome;
    }

    public void setAccountNum(int accountNum){
        this.accountNum = accountNum;
    }

    public String getFname() {
        return fname;
    }

    public String getLname() {
        return lname;
    }

    public int getAge() {
        return age;
    }

    public String getDob() {
        return dob;
    }

    public String getAddress() {
        return address;
    }

    public float getYearlyIncome() {
        return yearlyIncome;
    }

    public int getAccountNum(){
        return accountNum;
    }

}

/*****************************************************************************************************/

/Java Main Class/

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.Scanner;
import java.util.Date;

public class Main {

    public static void main(String[] args) {

        Scanner scanf = new Scanner(System.in);
        Persons people[] = new Persons[3];
        Account personAccount[] = new Account[3];


        float withdrawAmount;
        float depositAmount;
        float transferAmount;
        int mainChoice;
        int choice;
        int counter = 0;
        int userId = 0;
        int loopBreak = 0;
        int loginSuccess = -1;

        while(loopBreak != -1){
            System.out.println("================================================================================================");
            System.out.println("Welcome To The California Bank :)");
            System.out.println("1. Login..");
            System.out.println("2. Create A New Customer.");
            System.out.println("3. Done With Transactions.");


            mainChoice = scanf.nextInt();

            switch (mainChoice) {
                case 1:
                    System.out.println("Please Enter Your Account Number:");
                    int accountNum = scanf.nextInt();
                    System.out.println("Please Enter Your Pin:");
                    int pin = scanf.nextInt();

                    for (int i = 0; i <= counter; i++) {
                        if (personAccount[i].getAccountNum() == accountNum && personAccount[i].getPin() == pin) {
                            System.out.println(personAccount[i].getAccountNum());
                            System.out.println(personAccount[i].getPin());
                            System.out.println("Customer Logged In and Validated.");
                            userId = i;
                            loginSuccess = 0;
                        } else {
                            System.out.println("Sorry You Are Not A Current Customer!");
                            loginSuccess = -1;
                        }
                    }
                    if(loginSuccess == 0){
                        System.out.println("======================================================================================");
                        System.out.println("What Else Would You Like To Do Today?");
                        System.out.println("1. Deposit.");
                        System.out.println("2. Withdraw.");
                        System.out.println("3. Transfer Money.");
                        System.out.println("4. Check Balance.");
                        choice = scanf.nextInt();

                        switch (choice) {
                            case 1:
                                System.out.println("How Much Money Would You Like To Deposit?");
                                depositAmount = scanf.nextFloat();
                                personAccount[userId].deposit(depositAmount);
                                break;

                            case 2:
                                System.out.println("How Much Money Would You Like To Withdraw Today?");
                                withdrawAmount = scanf.nextFloat();
                                personAccount[userId].withDraw(withdrawAmount);
                                break;

                            case 3:
                                System.out.println("How Much Money Would You Like To Withdraw Today?");
                                transferAmount = scanf.nextFloat();
                                System.out.println("1. Press 1 To Transfer From Checking to Savings.");
                                System.out.println("2. Press 2 To Transfer From Savings To Checking.");
                                int transferChoice;
                                transferChoice = scanf.nextInt();
                                if (transferChoice == 1) {
                                    personAccount[userId].transfer(transferAmount, "Checking", "Savings");
                                } else {
                                    personAccount[userId].transfer(transferAmount, "Savings", "Checking");
                                }
                            case 4:
                                System.out.println("Here Is Your Total Account Balance");
                                personAccount[userId].checkBalance(people[counter].accountNum);
                                break;
                        }

                    }
                    break;
                case 2:
                    people[counter] = new Persons();
                    personAccount[counter] = new Account();
                    System.out.println("Please Enter Your First Name For The Account Creation:");
                    scanf.next();
                    String fName = scanf.nextLine();
                    System.out.println("Please Enter Your Last Name For The Account Creation:");
                    scanf.next();
                    String lName = scanf.nextLine();
                    people[counter].setFname(fName);
                    people[counter].setLname(lName);
                    System.out.println("Please Enter Your Age:");
                    int age = scanf.nextInt();
                    people[counter].setAge(age);
                    System.out.println("Please Enter Your Date Of Birth:");
                    String dob = scanf.next();
                    people[counter].setDob(dob);
                    System.out.println("Please Enter Your Address:");
                    scanf.next();
                    String address = scanf.nextLine();
                    people[counter].setAddress(address);
                    System.out.println("Please Enter Your Yearly Income:");
                    float annualIncome = scanf.nextFloat();
                    people[counter].setYearlyIncome(annualIncome);
                    System.out.println("Generating Your Account Number.....");
                    Random rand = new Random();
                    accountNum = rand.nextInt(100000);
                    people[counter].setAccountNum(accountNum);
                    personAccount[counter].setAccountNum(accountNum);
                    System.out.println("Your New Account Number Is: "+accountNum);
                    System.out.println("Please Enter A 4 Digit Pin");
                    pin = scanf.nextInt();
                    personAccount[counter].setPin(pin);

                    System.out.println("New Customer Created:");
                    counter++;
                    break;

                case 3:
                    System.out.println("Thanks For Using The California Banking System. Goodbye!");
                    loopBreak = -1;
                    break;

              }

            }

        }

    }

Below is the error I am Getting after creating a user:

  1. Login..
  2. Create A New Customer.
  3. Done With Transactions. 1 Please Enter Your Account Number: 90806 Please Enter Your Pin: 3333 90806 3333 Customer Logged In and Validated. Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Account.getAccountNum()" because "personAccount[i]" is null at Main.main(Main.java:48)
Karthik S
  • 9
  • 2
  • 1
    What exactly do you mean by not being able to execute the Login method? Do you have some error or is it not functioning as expected. Please be more specific. – Adrian Russo Jan 07 '21 at 20:52
  • https://stackoverflow.com/help/how-to-ask – Scb Jan 07 '21 at 20:56
  • http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Scb Jan 07 '21 at 20:57
  • @AdrianRusso - Below is the error - 1. Login.. 2. Create A New Customer. 3. Done With Transactions. 1 Please Enter Your Account Number: 90806 Please Enter Your Pin: 3333 90806 3333 Customer Logged In and Validated. Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Account.getAccountNum()" because "personAccount[i]" is null at Main.main(Main.java:48) – Karthik S Jan 07 '21 at 21:01
  • I copied your code and I am working on it, please dont delete this question, there are so many things to improve, belive me. I think your code is NullPointerException but you didnt specify it in question. – MrFisherman Jan 07 '21 at 21:03
  • Thank you friends, I feel I am creating the new person and account object in switch case 2 but it not getting stored in the main global arrays – Karthik S Jan 07 '21 at 21:05
  • First of all i debuged it and its about: you add only 1 person but you declared your array as 3 elements so 2 and 3 element (index 1 and 2) are empty, thats why it throws this exception. You shouldn't use array here I think. It throws null pointer because: loop get 0 index element and its new created account, then iterate next and get 1 index element which is empty and throw null pointer because cant call method on null element. – MrFisherman Jan 07 '21 at 21:09
  • @MrFisherman - Thank you for your effort but I do not think it is because of declaring 3 arrays. Atleast the for loop should execute once for the newly added person/account at index 0. – Karthik S Jan 07 '21 at 21:14
  • Man you are not declaring 3 arrays but 1 with 3 elements. Account accounts = new Account[3] means there should be 3 Accounts in array. – MrFisherman Jan 07 '21 at 21:18
  • Sorry my bad- what I meant was 3 array objects. It shouldn't fail with null pointer as array at index 0 is populated. – Karthik S Jan 07 '21 at 21:20
  • Yes It don't, It thorws it after 0 index, account is normally added, you can check it in debug mode. Try to change = new Account[3] to new Account[1] for a while and check if it is throwning exception? – MrFisherman Jan 07 '21 at 21:23
  • When I change it to new Account[1], getting the below error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at Main.main(Main.java:48) – Karthik S Jan 07 '21 at 21:27
  • wait a second I will give you solution, I am working on it. – MrFisherman Jan 07 '21 at 21:29
  • Look at the value of i when the exception is thrown. – tgdavies Jan 07 '21 at 21:31
  • Oh yes this throws ArrayIndexOutOfBound because you use <= counter, should be just < without =, array's indexes are count from 0 so you cant get index 1 of 1 element array. – MrFisherman Jan 07 '21 at 21:32
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) I know you don’t have an OOB exception, but read the answers and look at your code. – tgdavies Jan 07 '21 at 21:34
  • Okay. let me try. But do you thin the new objects created in switch 2 people[counter] = new Persons(); personAccount[counter] = new Account(); will be accessible in switch 1? – Karthik S Jan 07 '21 at 21:34
  • You are right @MrFisherman. It did work when I used – Karthik S Jan 07 '21 at 21:36
  • Also is it okay to make the Account class extend the Persons class? – Karthik S Jan 07 '21 at 21:38
  • How can I create multiple Persons and Accounts if it is always going to be Account[1], Persons[1] ? – Karthik S Jan 07 '21 at 21:40
  • I will show you it just wait I am writing the code :D it will show you everything – MrFisherman Jan 07 '21 at 21:42
  • @MrFisherman - Thank you so much brother :) – Karthik S Jan 07 '21 at 21:42

1 Answers1

0

There are so many things about your code, but first its explanation about your bug which is NullPointerException.

This exception is thrown when you for example try to call some methods on null elements. In your case you declared array as 3 elements and add only one Account (newly created). Then you iterate on array which have null elements (2nd and 3rd are null). You should get rid of this for loop or initialize array as 1 element sized = new Account[1] and then each time copy your new accounts to new array with bigger size. But it would be terrible solution. Another way (much better

Arrays are not size dynamic so you should use one of Collections https://www.javatpoint.com/collections-in-java for example List (ArrayList would be enough). I will show you how to improve your code, hope you will learn something from it.

Ok so here is the code:

Person (not persons, shouldn't be), don't use float for money, use BigDecimal, mark your fields as private or protected (read about encapsulation), descript your fields better, not like dob - write dateOfBirth, I use LocalDate here, dont use old Time api, better look at new Java Time Api, also you can count age of user by: currentDate - dateOfBirth

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

public class Person {

    private String firstName;
    private String lastName;
    private int age;
    private LocalDate dateOfBirth;
    private String address;
    private BigDecimal yearlyIncome;
    private int accountNumber;

    public Person() { }

    public Person(String firstName, String lastName, int age, LocalDate dateOfBirth, String address, BigDecimal yearlyIncome, int accountNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.dateOfBirth = dateOfBirth;
        this.address = address;
        this.yearlyIncome = yearlyIncome;
        this.accountNumber = accountNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public BigDecimal getYearlyIncome() {
        return yearlyIncome;
    }

    public void setYearlyIncome(BigDecimal yearlyIncome) {
        this.yearlyIncome = yearlyIncome;
    }

    public int getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(int accountNumber) {
        this.accountNumber = accountNumber;
    }
}

Ok, next Account You should read about super() keyword to call methods or constructors from parent class, I used it here just to show you how to do it, you give it to parent and set account class fields

import java.math.BigDecimal;

public class Account extends Person {

    private int accountNumber;
    private int pin;
    private BigDecimal checkingBalance = BigDecimal.ZERO;
    private BigDecimal savingBalance = BigDecimal.ZERO;

    public Account() { }

    public Account(int accountNumber, int pin, BigDecimal checkingBalance, BigDecimal savingBalance){
        this.accountNumber = accountNumber;
        this.checkingBalance = checkingBalance;
        this.savingBalance = savingBalance;
        this.pin = pin;
    }

    public int getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(int accountNumber) {
        this.accountNumber = accountNumber;
    }

    public int getPin() {
        return pin;
    }

    public void setPin(int pin) {
        this.pin = pin;
    }

    public void withDraw(BigDecimal withDrawAmount){
        this.savingBalance = this.savingBalance.subtract(withDrawAmount);
    }

    public void deposit(BigDecimal depositAmmount){
        this.checkingBalance = this.checkingBalance.subtract(depositAmmount);
    }

    public void transfer(BigDecimal transferAmount, String fromAccount, String toAccount){

        if(fromAccount.equals("Checking") && toAccount.equals("Savings")){
            this.checkingBalance = this.checkingBalance.subtract(transferAmount);
            this.savingBalance = this.savingBalance.add(transferAmount);
        }else if(fromAccount.equals("Savings") && toAccount.equals("Checking")){
            this.savingBalance = this.savingBalance.subtract(transferAmount);
            this.checkingBalance = this.checkingBalance.add(transferAmount);
        }

        System.out.print("Your New Checking Balance Is: " + this.checkingBalance);
        System.out.print("Your New Savings Balance Is: " + this.savingBalance);
    }

    public BigDecimal checkBalance(){
        return this.checkingBalance.add(this.savingBalance);
    }
}

Main

I improve a little Main class, you can see that I use List personsAccount, Collections are dynamic you can add as many elements as you want, means that you use collection of type account, you can do it like List too but read about inheritance and generics first. I add 5th option to back to main menu, also use do while option, 1 list is enough, you don't need persons and accounts arrays.

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class Main {

    private static final Scanner scanner = new Scanner(System.in);
    //if you use java 8 or above you can just do it like = new ArrayList<>();
    //static is here just because of example, you should reconsider it
    private static final List<Account> personsAccounts = new ArrayList<Account>();

    public static void main(String[] args) {
        BigDecimal withdrawAmount;
        BigDecimal depositAmount;
        BigDecimal transferAmount;

        int mainChoice;
        int choice;
        boolean session = true;
        Account currentLoggedAccount = new Account();
        int loginSuccess = -1;

        while (session) {
            System.out.println("================================================================================================");
            System.out.println("Welcome To The California Bank :)");
            System.out.println("1. Login..");
            System.out.println("2. Create A New Customer.");
            System.out.println("3. Done With Transactions.");

            mainChoice = scanner.nextInt();

            switch (mainChoice) {
                case 1:
                    System.out.println("Please Enter Your Account Number:");
                    int accountNumber = scanner.nextInt();

                    System.out.println("Please Enter Your Pin:");
                    int pin = scanner.nextInt();

                    for (int i = 0; i < personsAccounts.size(); i++) {
                        if (personsAccounts.get(i).getAccountNumber() == accountNumber && personsAccounts.get(i).getPin() == pin) {
                            System.out.println(personsAccounts.get(i).getAccountNumber());
                            System.out.println(personsAccounts.get(i).getPin());
                            System.out.println("Customer Logged In and Validated.");
                            currentLoggedAccount = personsAccounts.get(i);
                            loginSuccess = 0;
                        } else {
                            System.out.println("Sorry You Are Not A Current Customer!");
                            loginSuccess = -1;
                        }
                    }
                    if (loginSuccess == 0) {
                        do {
                            System.out.println("======================================================================================");
                            System.out.println("What Else Would You Like To Do Today?");
                            System.out.println("1. Deposit.");
                            System.out.println("2. Withdraw.");
                            System.out.println("3. Transfer Money.");
                            System.out.println("4. Check Balance.");
                            System.out.println("5. Back to main menu");
                            choice = scanner.nextInt();
                            switch (choice) {
                                case 1:
                                    System.out.println("How Much Money Would You Like To Deposit?");
                                    depositAmount = scanner.nextBigDecimal();
                                    currentLoggedAccount.deposit(depositAmount);
                                    break;
                                // is case 2 and 3 is the same?
                                case 2:
                                    System.out.println("How Much Money Would You Like To Withdraw Today?");
                                    withdrawAmount = scanner.nextBigDecimal();
                                    currentLoggedAccount.withDraw(withdrawAmount);
                                    break;
                                case 3:
                                    System.out.println("How Much Money Would You Like To Withdraw Today?");
                                    transferAmount = scanner.nextBigDecimal();
                                    System.out.println("1. Press 1 To Transfer From Checking to Savings.");
                                    System.out.println("2. Press 2 To Transfer From Savings To Checking.");
                                    int transferChoice;
                                    transferChoice = scanner.nextInt();
                                    if (transferChoice == 1) {
                                        currentLoggedAccount.transfer(transferAmount, "Checking", "Savings");
                                    } else {
                                        currentLoggedAccount.transfer(transferAmount, "Savings", "Checking");
                                    }
                                    break;
                                case 4:
                                    System.out.println("Here Is Your Total Account Balance");
                                    currentLoggedAccount.checkBalance();
                                    break;
                                default:
                                    System.out.println("There is no option :(");
                                    break;
                            }
                        }
                        while (choice != 5);
                    }
                    break;
                case 2:
                    Account accountToAdd = new Account();

                    System.out.println("Please Enter Your First Name For The Account Creation:");
                    scanner.next();
                    String firstName = scanner.nextLine();
                    accountToAdd.setFirstName(firstName);

                    System.out.println("Please Enter Your Last Name For The Account Creation:");
                    scanner.next();
                    String lastName = scanner.nextLine();
                    accountToAdd.setLastName(lastName);

                    System.out.println("Please Enter Your Age:");
                    int age = scanner.nextInt();
                    accountToAdd.setAge(age);

                    System.out.println("Please Enter Your Date Of Birth:");
                    String date = scanner.next();
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy");
                    accountToAdd.setDateOfBirth(LocalDate.parse(date, dtf));

                    System.out.println("Please Enter Your Address:");
                    scanner.next();
                    String address = scanner.nextLine();
                    accountToAdd.setAddress(address);

                    System.out.println("Please Enter Your Yearly Income:");
                    BigDecimal annualIncome = scanner.nextBigDecimal();
                    accountToAdd.setYearlyIncome(annualIncome);

                    System.out.println("Generating Your Account Number.....");
                    Random rand = new Random();
                    //that is some kind of weir because what if somebody have this number yet? :D
                    int newAccountNumber = rand.nextInt(100000);

                    accountToAdd.setAccountNumber(newAccountNumber);
                    System.out.println("Your New Account Number Is: " + newAccountNumber);
                    System.out.println("Please Enter A 4 Digit Pin");
                    pin = scanner.nextInt();
                    accountToAdd.setPin(pin);

                    //adding new account to list
                    personsAccounts.add(accountToAdd);
                    System.out.println("New Customer Created:");
                    break;
                case 3:
                    System.out.println("Thanks For Using The California Banking System. Goodbye!");
                    session = false;
                    break;
                default:
                    System.out.println("There is no option :(");
                    break;
            }
        }
    }
}

This code isn't perfect but it's working and its clearer, it can be improved by you as you wish. Hope you will learn something, read about java.Collections, java.Time, java Generics, you can also exchange normal for to for each loop like for(Account account : personsAccounts) {}. Cheers!

MrFisherman
  • 720
  • 1
  • 7
  • 27