2013-10-27 44 views
-5

在我的账户类我得到一个NullPointerException,我不明白为什么

2号线就是它抛出空指针异常,baArray如下所示我的银行类的对象。我还有一个检查和储蓄课程,可以扩展我的Bankaccount课程,如果您看看我的银行课程的最底部,我正在使用这些方法来设置这些课程中包含的余额值。

这是我的主类

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

这里是我的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

+1

我没有看到任何声明或初始化baArray变量的代码。您可能想要展示这一点。 –

+0

尝试阅读有关调试Java的内容。这太微不足道了,甚至被问到。 – MightyPork

+0

@HovercraftFullOfEels我在编辑中添加了该代码 – user2733862

回答

2

通常这种错误是由于您创建一个对象数组,而不是创建阵列中的项目。解决方案是在尝试使用它之前先用对象填充你的数组。

举例来说,假设你有这样的代码:

BankAccount[] baArray = new BankAccount[3]; 

这将创建一个大小为3的BankAccount的数组,但数组将举行什么,但空引用。使用数组,您必须首先使用对象填充:

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

编辑
关于你最新的代码后:

  • 我看到你的名字你的类的BankAccount。您需要将其更改为BankAccount以符合Java标准。
  • 如果您的代码进入catch块,您实际上会创建一个大小为3的数组,但忽略用对象填充数组。这将导致您发布的NPE。
+0

如果你看看我的checkAccount()方法,它将该数组赋给一个对象 – user2733862

+1

@ user2733862:1)什么'checkAccount()'方法?2)我们不是在讨论将数组赋给任何东西,而是将对象*放入数组项中。同时考虑在运行时使用调试器来检查程序流程和程序的状态。 –

+0

1)我很抱歉,我在账户最后一块代码的顶部填入了accountCheck()。在那里你会看到我有一个for循环baArray [arrayId] = new Bankaccount(); – user2733862

0

当函数

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

运行时,你已经checking例如设置为null。

相关问题