2013-10-27 47 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。

相關問題