-5

在我的帐户类

第 2 行是它抛出空指针异常的地方,baArray 是我的银行类的对象,如下所示。我还有一个 Checking and Savings 类,它扩展了我的 Bankaccount 类,如果您查看我的银行类的最底部,我正在使用这些方法来设置这些类中包含的余额值。

这是我的主要课程

包 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");
    }

这是我的 BankAccount 课程

    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;
}

}

我得到的例外是。

    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 结果:1

4

2 回答 2

3

通常这种错误是由于您创建了一个对象数组但没有在数组中创建项目。解决方案是在尝试使用之前用对象填充数组。

例如,假设您有如下代码:

BankAccount[] baArray = new BankAccount[3];

这将创建一个大小为 3 的 BankAccount 数组,但该数组将只包含空引用。要使用数组,您必须首先用对象填充它:

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

编辑
关于您最新的代码帖子:

  • 我看到你命名你的班级银行帐户。您需要将其更改为 BankAccount 以符合 Java 标准。
  • 如果您的代码进入 catch 块,您实际上创建了一个大小为 3 的数组,但忽略了用对象填充数组。这将导致您发布的 NPE。
于 2013-10-27T18:34:45.287 回答
0

当函数

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

运行,您将checking实例设置为空。

于 2014-01-09T11:12:06.697 回答