-5

in my account class

line 2 is where its throwing the null pointer exception, baArray is an object of my banking class shown below. I also have a Checking and Savings class that extends my Bankaccount class, if you look at the very bottom of my bank class I am using those methods to set the value of balance contained within those classes.

Here is my main class

package edu.umsl;

    import java.io.*;
    import java.util.*;
    import java.text.*;


private double balance;
private Bankaccount baArray[];
private int accountid;
public int arrayId;
public boolean accountType;

// Initial Constructor
// Once called the Account1 constructor presents a menu for users to make
// a deposit, withdrawal, check balance or exit.
// The menu is a loop that based on the selection will call either the
// deposit method, withdrawal method or exit the program.
public Account(double begin_balance) {
    balance = begin_balance;

} // End Initial Constructor

public void accountCheck() throws IOException {
    String yesno;
    int oldaccount;
    int newaccount;
    loadAccounts();
    System.out.println("Welcome to RIPOFF Bank, do you have an account with us? (yes or no)");
    yesno = KbdInput.readString();
    if (yesno.equalsIgnoreCase("yes")) {
        System.out.println("Please enter your account ID:");
        oldaccount = KbdInput.readInt();

        accountid = oldaccount;
        for (arrayId = 0; arrayId <= 2; arrayId++) {
            if (baArray[arrayId].getID() == accountid) {
                break;
            }
        }
    } else if (yesno.equalsIgnoreCase("no")) {
        System.out.println("Please choose an account id(integers only):");
        newaccount = KbdInput.readInt();
        accountid = newaccount;
        for (arrayId = 0; arrayId <= 2; arrayId++) {

            if (baArray[arrayId] == null) {
                baArray[arrayId] = new Bankaccount();
                baArray[arrayId].setID(accountid);

            }
            if (baArray[arrayId].getID() == accountid) {

                saveAccount();
                break;
            }
        }
    }
}

public void menu() throws IOException {
    System.out.println("Today you are opening an account, please enter the date");
    baArray[arrayId].getDate1();
    char mychar = 'z';
    while (mychar != 'e') {
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println("*********************************");
        System.out.println("*    WELCOME TO RIPUOFF BANK    *");
        System.out.println("*                               *");
        System.out.println("*     Come in and check out     *");
        System.out.println("*          our low 30%          *");
        System.out.println("*      interest rate loans      *");
        System.out.println("*                               *");
        System.out.println("*********************************");
        System.out.println();
        System.out.println("What would you like to do with your " + baArray[arrayId].accountWord(accountType) + " account (account# " + baArray[arrayId].getID() + "):");
        System.out.println("Deposit(d)");
        System.out.println("Withdraw(w)");
        System.out.println("CheckBalance(c)");
        System.out.println("Exit(e)");
        BufferedReader br;
        String input;
        int index = 0;
        br = new BufferedReader(new InputStreamReader(System.in));

        input = br.readLine();

        mychar = input.charAt(index);

        if (mychar == 'd' || mychar == 'D') {
            System.out.println("Your current balance in checking is:" + baArray[arrayId].getCheckingBalance());
            //if (dateflag == true)
            //{
            baArray[arrayId].getDate2();
            baArray[arrayId].getInterest(accountType);
            baArray[arrayId].deposit(accountType);
            //}

            //else
            //{
            //getDate1();
            //deposit();
            //}

        } else if (mychar == 'w' || mychar == 'W') {
            System.out.println("Your current balance is: " + baArray[arrayId].getCheckingBalance());
            //if (dateflag == true)
            //{
            baArray[arrayId].getDate2();
            baArray[arrayId].getInterest(accountType);
            baArray[arrayId].withdraw(accountType);
            //}
            //else
            //{
            //        getDate1();
            //        withdraw();
            //}
        } else if (mychar == 'c' || mychar == 'C') {
            if(accountType==true){
            System.out.println("Your current balance is: " + baArray[arrayId].getBalance(baArray[arrayId].getCheckingBalance()));
            }else{
                System.out.println("Your current balance is: " + baArray[arrayId].getBalance(baArray[arrayId].getSavingsBalance()));

            }
            }

    }
}

//Main method instantiates the initial account balance of 100 hundred dollars
//Then creates the account and lets the Account class take over from there.
public void loadAccounts() {
    try {
        FileInputStream inStream = new FileInputStream("file.out");
        ObjectInputStream is = new ObjectInputStream(inStream);
        baArray = (Bankaccount[]) is.readObject();
    } catch (Exception e) {
        baArray = new Bankaccount[3];
    }

}

public void saveAccount() {
    try {
        FileOutputStream outStream = new FileOutputStream("file.out");
        ObjectOutputStream os = new ObjectOutputStream(outStream);
        os.writeObject(baArray);
        os.flush();
        outStream.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

public static void main(String[] args) throws IOException {
    double init_amount = 100.00;
    Account ac = new Account(init_amount);

    ac.accountCheck();
   ac.accountType();
    ac.menu();
}
public void accountType(){

    System.out.println("Checking 1:");
    System.out.println("Savings 2:");
    System.out.println("Please select one of your accounts");
    int input = KbdInput.readInt();
    if(input==1){
        accountType = true;
        baArray[arrayId].setAccountType(accountType);
    }else if(input==2){
        accountType = false;
        baArray[arrayId].setAccountType(accountType);
    }else{
        System.out.println("Invalid Input");
    }

here is my BankAccount class

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.text.NumberFormat;
    import java.text.ParsePosition;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.Locale;

    public class Bankaccount implements java.io.Serializable {

private int ID;
private double amt;
private int firstdate;
private int seconddate;
private Calendar cal1 = new GregorianCalendar();
private Calendar cal2 = new GregorianCalendar();
private boolean dateflag = false;
private double rate;
private Checking checking;
private Savings savings;
private boolean accountType;

public Bankaccount() {
}

public Bankaccount(int ID, double amt) {
    this.ID = ID;
    this.amt = amt;
}

public String getBalance(double balance) {

    NumberFormat currencyFormatter = null;
    String currencyOut;

    currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
    currencyOut = currencyFormatter.format(balance);

    return currencyOut;

}

// This method prompts the user for the deposit and then adds it to the
// balance field.
public void deposit(boolean chsv) throws IOException {
    BufferedReader br;
    String entered_amount;
    boolean accountType = chsv;

    System.out.print("How much would you like to deposit? :");
    br = new BufferedReader(new InputStreamReader(System.in));
    entered_amount = br.readLine();
    double amount = Double.valueOf(entered_amount).doubleValue();
   if(accountType==true){

    double balance = getCheckingBalance();
    balance = balance + amount;
    setCheckingBalance(balance);
   } else{

    double balance = getSavingsBalance();
    balance = balance + amount;
    setSavingsBalance(balance);
   }

    if (accountType == true) {
        System.out.println("Your checking balance is: " + getCheckingBalance());
    } else {
        System.out.println("Your savings balance is: " + getSavingsBalance());


}
}

// This method prompts the user for the withdraw amount and then subtracts
// it from the balance field.
public void withdraw(boolean chsv) throws IOException {
    boolean accountType;
    accountType = chsv;
    BufferedReader br;
    String entered_amount;

    System.out.print("How much would you like to withdraw? :");
    br = new BufferedReader(new InputStreamReader(System.in));
    entered_amount = br.readLine();
    double amount = Double.valueOf(entered_amount).doubleValue();
    if (accountType == true) {
        if (getCheckingBalance() < amount) {
            System.out.println("Insufficient funds.");
        } else {
            double balance = getCheckingBalance();
            balance = balance - amount;
            setCheckingBalance(balance);
        }
    } else {
        if (getSavingsBalance() < amount) {
            System.out.println("Insufficient funds.");
        } else {
            double balance = getSavingsBalance();
            balance = balance - amount;
            setSavingsBalance(balance);
        }
    }
    if (accountType == true) {
        System.out.println("Your balance is: " + getCheckingBalance());
    } else {
        System.out.println("Your balance is: " + getSavingsBalance());

    }
}

// This function is only called on the first transaction after the
// account has been initialized to set the first time a transaction
// occurs for the account for the current year.
public void getDate1() throws IOException {

    System.out.print("Enter todays date(mm/dd/yyyy): ");
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    String inputText = br.readLine();
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    ParsePosition pos = new ParsePosition(0);
    //Date date= new Date();
    Date date = formatter.parse(inputText, pos);

    cal1.setTime(date);

    firstdate = cal1.get(cal1.DAY_OF_YEAR);
    dateflag = true;

}

// This method is called for every date entered after the first date.
// The previous second date is passed to the first date to keep track of
// time.
public void getDate2() throws IOException {

    System.out.print("Enter todays date(mm/dd/yyyy): ");
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    String inputText = br.readLine();
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    ParsePosition pos = new ParsePosition(0);
    Date date = new Date();
    date = formatter.parse(inputText, pos);

    cal2.setTime(date);

    seconddate = cal2.get(cal2.DAY_OF_YEAR);

    if (firstdate > seconddate) {
        System.out.println("You must enter a future date.");
        getDate2();
    }

}

// This method calulates the interest based on the previous date and the
// current date
public void getInterest(boolean chsv) {
    boolean accountType;
    accountType = chsv;
    int datediff = seconddate - firstdate;       
    rate = .05 / 365;
    double ratetime = Math.pow(1 + rate, datediff);
   if (accountType==true){
     double balance = getCheckingBalance();
    balance = balance * ratetime;
    setCheckingBalance(balance);
    firstdate = seconddate;
   }else {
       double balance = getSavingsBalance();
    balance = balance * ratetime;
    setSavingsBalance(balance);
    firstdate = seconddate;
   }

}

/**
 * @return the ID
 */
public int getID() {
    return ID;
}

/**
 * @param ID the ID to set
 */
public void setID(int ID) {
    this.ID = ID;
}

/**
 * @return the amt
 */
public double getAmt() {
    return amt;
}

/**
 * @param amt the amt to set
 */
public void setAmt(double amt) {
    this.amt = amt;
}

public void setCheckingBalance(double balance) {
    checking.setBalance(balance);
}

public double getCheckingBalance() {
    return checking.getBalance();
}

public void setSavingsBalance(double balance) {
    savings.setBalance(balance);
}

public double getSavingsBalance() {
    return savings.getBalance();
}

public String accountWord(boolean accountType) {
    boolean x = accountType;
    String s = "savings";
    if (x == true) {
        return "checking";
    } else if (x == false) {
        return "savings";
    }
    return null;
}

/**
 * @return the accountType
 */
public boolean isAccountType() {
    return accountType;
}

/**
 * @param accountType the accountType to set
 */
public void setAccountType(boolean accountType) {
    this.accountType = accountType;
}

}

The exception i'm getting is.

    Exception in thread "main" java.lang.NullPointerException
at edu.umsl.Bankaccount.getCheckingBalance(Bankaccount.java:226)
at edu.umsl.Account.menu(Account.java:106)
at edu.umsl.Account.main(Account.java:176)

Java Result: 1

2 Answers2

3

Usually an error of this sort is due to your creating an object array but not creating the items in the array. The solution is to fill your array with objects before trying to use it.

For instance, say you have code like:

BankAccount[] baArray = new BankAccount[3];

This will create an array of BankAccount of size 3, but the array will hold nothing but null references. To use the array, you must first fill it with objects:

for (int i = 0; i < baArray.length; i++) {
  baArray[i] = new BankAccount();
}

Edit
Regarding your latest code post:

  • I see you name your class Bankaccount. You'll want to change it to BankAccount to comply with Java standards.
  • If your code goes into the catch block, you in fact create an array of size 3, but neglect to fill the array with objects. This will lead to the NPE that you've posted.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • if you look at the in my checkAccount() method it assigns the array to an object – user2733862 Oct 27 '13 at 18:42
  • 1
    @user2733862: 1) what `checkAccount()` method? and 2) we're not talking about assigning the array to anything but about putting objects *into* the array items. Also consider using a debugger to check the program flow and the state of the program while it runs. – Hovercraft Full Of Eels Oct 27 '13 at 18:45
  • 1) im sorry I ment accountCheck(), at the top of the last block of code I posted. In there you will see I have a for loop with baArray[arrayId] = new Bankaccount(); – user2733862 Oct 27 '13 at 18:48
0

When the function

public void setCheckingBalance(double balance) {
    checking.setBalance(balance);
}

runs, you have checking instance set to null.

Gangnus
  • 24,044
  • 16
  • 90
  • 149