当我尝试输入存款,取款,余额查询和帐户信息的金额时,当我尝试选择"我已经有一个帐户,但如果我选择创建一个新帐户,则运行顺利"时,我的程序输出null。
public class BankAtm {
public static SavingsAccount accnt;
public static void main(String[] args) {
JTextField name = new JTextField();
JTextField pin = new JTextField();
JTextField aage = new JTextField();
JTextField contactNo = new JTextField();
String aNo;
String aName;
String aPin;
int age;
String aContactNo;
String[] choices = {"Yes", "I already have an account", "Exit"};
int y = JOptionPane.showOptionDialog(null, "Would you like to open a new acount?" ,
"Bank ATM",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, choices, choices[0]);
switch (y) {
case 0:
int max = 500;
int min = 100;
Object[] a = {"Account Name: ", name, "Age: ", aage, "Account Pin Number: ", pin, "Contact Number (please input parent's or guardian's contact number if below 18): ", contactNo};
JOptionPane op= new JOptionPane(a, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null);
JDialog dialog= op.createDialog(null, "Create New Account");
dialog.setVisible(true);
aName = name.getText();
age = Integer.parseInt(aage.getText());
aPin = pin.getText();
aContactNo=contactNo.getText();
int no = (int) (Math.random()*(max-min+1)+max);
JOptionPane.showMessageDialog(null, "Your account number is "+no);
aNo = Integer.toString(no);
accnt = new SavingsAccount (aName, aNo, aPin);
accnt.accntName=aName;
accnt.accntNo= aNo;
accnt.accntAge= age;
accnt.accntPin= aPin;
accnt.accntContactNo=aContactNo;
case 1:
int trans;
String php;
double amt;
do {
String s = JOptionPane.showInputDialog("1. Deposit"
+ "n2. Withdraw"
+ "n3. Balance Inquiry"
+ "n4. Display Account Info"
+ "n5. Exit");
trans = Integer.parseInt(s);
switch (trans) {
case 1:
php = JOptionPane.showInputDialog("Enter amount to deposit: ");
amt = Double.parseDouble(php);
accnt.deposit(amt);
break;
case 2:
php = JOptionPane.showInputDialog("Enter amount to withdraw: ");
amt = Double.parseDouble(php);
accnt.withdraw(amt);
break;
case 3:
accnt.balInquiry();
break;
case 4:
accnt.displayAccntInfo();
break;
case 5:
JOptionPane.showMessageDialog(null, "Thank you for using our service!~");
break;
}
} while (trans!=5);
}
return;
}
}
程序在线程"main"中输出Exceptionjava.lang.NullPointerException:无法调用SavingsAccount.displayAccntInfo()"因为"BankAtm.accnt"为空
在switch
的情况0中,您通过其构造函数创建了一个新的SavingsAccount
,从而给了他一个值,但如果您输入switch
的情况1,则帐户构造函数从未被调用,因为您只是声明它:
public static SavingsAccount accnt;
当您初始化一个变量而不给它赋值时,它会得到一个默认值,即null
。您不能访问null
对象的属性,因为它没有任何属性。在对象上使用任何方法之前,必须从某处调用构造函数。