You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决银行ATM程序选择已有账户时的NullPointerException问题

问题分析与修复方案

问题根源

  1. 空指针异常原因:选择「I already have an account」(对应switch的case 1)时,静态变量accnt未被实例化,始终为null,调用其方法(如deposit()、displayAccntInfo())必然触发NullPointerException。而新建账户(case 0)时,代码执行了accnt = new SavingsAccount(...)完成初始化,所以后续操作正常。
  2. 流程逻辑bug:case 0代码块末尾未添加break,导致新建账户后会自动进入case 1的交易流程,不符合常规交互逻辑。

修复步骤

  1. 为已有账户添加登录逻辑:在case 1中,弹出输入框让用户输入账号和PIN码,验证通过后初始化accnt对象(示例中模拟简单验证,实际场景应对接账户存储)。
  2. 补全case 0的break语句:终止当前分支流程,避免自动进入交易环节。
  3. 增加输入异常处理:对用户输入的数字类型内容(如交易选项、金额)添加try-catch,防止非数字输入导致程序崩溃。

修改后的代码示例

import javax.swing.*;

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 account?" , 
                "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)+min);  // 修正随机数生成逻辑,确保生成100-500区间的账号
                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;
                
                JOptionPane.showMessageDialog(null, "Account created successfully!");
                break;  // 添加break,终止新建账户后的流程跳转
                
            case 1:
                // 已有账户登录逻辑
                String inputAccntNo = JOptionPane.showInputDialog("Enter your account number:");
                String inputPin = JOptionPane.showInputDialog("Enter your PIN:");
                
                // 模拟账户验证,实际场景应从数据库/文件读取真实账户信息
                if (inputAccntNo != null && inputPin != null && !inputAccntNo.isEmpty() && !inputPin.isEmpty()) {
                    // 模拟获取账户信息,需根据实际SavingsAccount构造逻辑调整
                    accnt = new SavingsAccount("Registered User", inputAccntNo, inputPin);
                    accnt.accntAge = 25;
                    accnt.accntContactNo = "1234567890";
                    JOptionPane.showMessageDialog(null, "Login successful!");
                } else {
                    JOptionPane.showMessageDialog(null, "Invalid account or PIN!");
                    return;
                }
                
                int trans;
                String php;
                double amt;
                
                do {
                    String s = JOptionPane.showInputDialog("1. Deposit"
                            + "\n2. Withdraw"
                            + "\n3. Balance Inquiry"
                            + "\n4. Display Account Info"
                            + "\n5. Exit");
                    
                    // 处理交易选项输入异常
                    try {
                        trans = Integer.parseInt(s);
                    } catch (NumberFormatException | NullPointerException e) {
                        JOptionPane.showMessageDialog(null, "Please enter a valid number!");
                        continue;
                    }
                    
                    switch (trans) {
                        case 1:
                            php = JOptionPane.showInputDialog("Enter amount to deposit: ");
                            try {
                                amt = Double.parseDouble(php);
                                accnt.deposit(amt);
                            } catch (NumberFormatException | NullPointerException e) {
                                JOptionPane.showMessageDialog(null, "Invalid amount!");
                            }
                            break;
                        
                        case 2:
                            php = JOptionPane.showInputDialog("Enter amount to withdraw: ");
                            try {
                                amt = Double.parseDouble(php);
                                accnt.withdraw(amt);
                            } catch (NumberFormatException | NullPointerException e) {
                                JOptionPane.showMessageDialog(null, "Invalid amount!");
                            }
                            break;
                        
                        case 3:
                            accnt.balInquiry();
                            break;
                        
                        case 4:
                            accnt.displayAccntInfo();
                            break;
                        
                        case 5:
                            JOptionPane.showMessageDialog(null, "Thank you for using our service!~");
                            break;
                        
                        default:
                            JOptionPane.showMessageDialog(null, "Invalid option! Please enter 1-5.");
                    }
                } while (trans != 5);
                break;
            
            case 2:
                JOptionPane.showMessageDialog(null, "Thank you for visiting!");
                return;
        }
    }
}

// 示例SavingsAccount类定义,需根据实际业务调整
class SavingsAccount {
    String accntName;
    String accntNo;
    String accntPin;
    int accntAge;
    String accntContactNo;
    double balance = 0.0;
    
    public SavingsAccount(String name, String accntNo, String pin) {
        this.accntName = name;
        this.accntNo = accntNo;
        this.accntPin = pin;
    }
    
    public void deposit(double amt) {
        if (amt > 0) {
            balance += amt;
            JOptionPane.showMessageDialog(null, "Deposit successful! New balance: " + balance);
        } else {
            JOptionPane.showMessageDialog(null, "Deposit amount must be positive!");
        }
    }
    
    public void withdraw(double amt) {
        if (amt > 0 && amt <= balance) {
            balance -= amt;
            JOptionPane.showMessageDialog(null, "Withdrawal successful! New balance: " + balance);
        } else if (amt <= 0) {
            JOptionPane.showMessageDialog(null, "Withdrawal amount must be positive!");
        } else {
            JOptionPane.showMessageDialog(null, "Insufficient balance!");
        }
    }
    
    public void balInquiry() {
        JOptionPane.showMessageDialog(null, "Current balance: " + balance);
    }
    
    public void displayAccntInfo() {
        String info = "Account Info:\n"
                + "Name: " + accntName + "\n"
                + "Account Number: " + accntNo + "\n"
                + "Age: " + accntAge + "\n"
                + "Contact Number: " + accntContactNo;
        JOptionPane.showMessageDialog(null, info);
    }
}

内容的提问来源于stack exchange,提问作者Alexandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 15:45:03