-4

我得到这个空指针异常:

java.lang.NullPointerException
    at ATM.isItValid(ATM.java:64)
    at ATM.displayGreeting(ATM.java:59)
    at Bank.runATM(Bank.java:90)
    at Bank.displayBank(Bank.java:109)
    at Bank.addAccount(Bank.java:52)
    at Bank.displayBank(Bank.java:105)
    at Bank.addAccount(Bank.java:52)
    at Bank.displayBank(Bank.java:105)
    at BankDriver.main(BankDriver.java:6)

从这段代码:

public void displayGreeting() {
    clearScreen();
    System.out.println("Welcome to Bob's Friendly Bank\n");
    do {
        System.out.print("Enter card number: ");
        currentCard = input.next();
        System.out.print("Enter PIN: ");
        currentPIN = input.next();
        System.out.println(currentCard + currentPIN);
    } while (!(isItValid()));
}
public boolean isItValid(){  
   boolean answer = false;
   if(theBank.validCard(currentCard, currentPIN))      //Exception thrown here.
       answer = true;
   return answer;    
}

怎么了?

4

5 回答 5

3

ATM.theBank 永远不会被设置,因此当您在 isItValid 中访问它时会生成空指针异常

于 2013-02-11T21:27:09.917 回答
2

当您调用其 validCard 方法时,theBank 有一个 null。在实例化它之前你不能使用它。

于 2013-02-11T21:25:28.223 回答
0

theBank为空ATM。这是一种初始化它的方法:

public Bank() {    
    theATM      = new ATM( this);
...


public class ATM {
   ...
   public ATM( Bank bank ) {
      theBank = bank;
      input = new Scanner(System.in);
      currentCard = "";
      currentPIN = "";
   }
于 2013-02-11T21:32:31.310 回答
0

theBank类中的变量ATM未初始化。您是否缺少一些代码?

于 2013-02-11T21:29:30.870 回答
0

theBank未初始化。

如果是静态对象,则new()在类级别执行,否则在方法中执行。如果在您进入方法时它需要可用,请将其作为参数传递。

奖励:总是做null检查。

if(null!=theBank && theBank.validCard(currentCard, currentPIN)) 
于 2013-02-11T21:54:21.020 回答