gpt4 book ai didi

java - ClassCastException 异常处理和类创建需要帮助

转载 作者:行者123 更新时间:2023-12-02 04:22:08 25 4
gpt4 key购买 nike

在同事的帮助下,我一直在努力修改我的代码,并取得了一些进展。我面临两个问题,希望得到帮助。首先是在我的 MyListener 类中。根据之前的教程和示例,我查看了使用的“JButton source = (JButton) e.getSource();”检查正在使用哪个操作。当我只使用按钮时这很好,但现在我有了单选按钮,它会抛出castClassException。不确定这个问题的解决方法。我面临的下一个问题是 InsufficientFunds 类,我在这些部分放置了大块引号以获得更好的可视化效果。该类设置为当余额低于请求提取或转账的金额时抛出异常。我为这些事件设置了手动触发器,因为我无法正确设置类来处理这种情况。我如何正确设置此类来处理异常,以及如何将它们实现到 Account 类下的正确事件中(这是应该使用它的地方)?最后,如果有人对我当前的代码有进一步的建议,我将不胜感激,因为我正在尝试完成该项目。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.JFrame;

class Account {

private double balance;

public Account(double initialBalance) {
balance = initialBalance;
}

public double getBalance() {
return balance;
}

public void deposit(double amount) {
balance += amount;
}

public void withdraw(double amount) {
balance -= amount;

}
} // End class Account

class InsufficientFunds extends Exception {

/*
*
*
* Needs to create InsufficientFUnds() and be implemented in Account class
*
*
*/
} // End class InsufficientFunds

public class ATM extends JFrame {

private final JButton withdrawButton;
private final JButton depositButton;
private final JButton transferButton;
private final JButton balanceButton;
private final JRadioButton checkingRadio;
private final JRadioButton savingsRadio;
private final JTextField valueText;
private static final int FRAME_WIDTH = 325;
private static final int FRAME_HEIGHT = 200;

static Account checkingAccount;
static Account savingsAccount;

public ATM() {
// Sets Frame and Layout
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("ATM Machine");
setResizable(false);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;

// Create withdrawButton Button and places is on display
withdrawButton = new JButton("Withdraw");
constraints.insets = new Insets(5, 50, 2, 5);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
add(withdrawButton, constraints);

// Create depositButton Button and places is on display
depositButton = new JButton("Deposit");
constraints.insets = new Insets(5, 5, 2, 50);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 1;
add(depositButton, constraints);

// Create transferButton Button and places is on display
transferButton = new JButton("Transfer To");
constraints.insets = new Insets(1, 50, 2, 5);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 2;
add(transferButton, constraints);

// Create balanceButton Button and places is on display
balanceButton = new JButton("Balance");
constraints.insets = new Insets(1, 5, 2, 50);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 1;
add(balanceButton, constraints);

// Create checkingRadio RadioButton and places is on display
checkingRadio = new JRadioButton("Checking");
constraints.insets = new Insets(1, 50, 5, 5);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 3;
add(checkingRadio, constraints);

// Create savingsRadio RadioButton and places is on display
savingsRadio = new JRadioButton("Savings");
constraints.insets = new Insets(1, 5, 5, 50);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.PAGE_END;
constraints.gridx = 1;
add(savingsRadio, constraints);

// Create valueText TextField and places is on display
valueText = new JTextField(10);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(1, 35, 30, 35);
constraints.gridx = 0;
constraints.gridwidth = 2;
constraints.gridy = 4;
add(valueText, constraints);

//Group RadioButtons so that only one selection allowed
ButtonGroup radioButtons = new ButtonGroup();
radioButtons.add(checkingRadio);
radioButtons.add(savingsRadio);

// Group Buttons so that only one selection allowed
ButtonGroup buttons = new ButtonGroup();
buttons.add(withdrawButton);
buttons.add(depositButton);
buttons.add(transferButton);
buttons.add(balanceButton);

// Sets the frame open and close
JFrame frame = new JFrame("ATM Machine");
frame.pack();
frame.getContentPane();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Adds ActionListeners to each of the Buttons
withdrawButton.addActionListener(new MyListener());
depositButton.addActionListener(new MyListener());
transferButton.addActionListener(new MyListener());
balanceButton.addActionListener(new MyListener());
checkingRadio.addActionListener(new MyListener());
savingsRadio.addActionListener(new MyListener());
valueText.addActionListener(new MyListener());
}

// Handles Events for the JButtons
class MyListener implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {

JButton source = (JButton) e.getSource();

if ("Withdraw".equalsIgnoreCase(source.getText())) {
if (checkingRadio.isSelected()) {
try {
String amountString = valueText.getText();
double withdrawAmount = Double.parseDouble(amountString);
if (withdrawAmount % 20 == 0) {
if (withdrawAmount <= checkingAccount.getBalance()) {
checkingAccount.withdraw(Double.parseDouble(valueText.getText()));
JOptionPane.showMessageDialog(null, "Withdraw Complete");
} else {
JOptionPane.showMessageDialog(null, "Insufficient Funds");
}
} else {
JOptionPane.showMessageDialog(null, "Please Use Increments of $20");
}
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Please Enter a Numerical Value");
}
} // End withdraw/checking

if (savingsRadio.isSelected()) {
try {
String amountString = valueText.getText();
double withdrawAmount = Double.parseDouble(amountString);
if (withdrawAmount % 20 == 0) {
if (withdrawAmount <= savingsAccount.getBalance()) {
savingsAccount.withdraw(Double.parseDouble(valueText.getText()));
JOptionPane.showMessageDialog(null, "Withdraw Complete");
} else {
JOptionPane.showMessageDialog(null, "Insufficient Funds");
}
} else {
JOptionPane.showMessageDialog(null, "Please Use Increments of $20");
}
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Please Enter a Numerical Value");
}
} // End withdraw/savings


valueText.setText("");
} // End Withdraw Events

if ("Deposit".equalsIgnoreCase(source.getText())) {
if (checkingRadio.isSelected()) {
try {
checkingAccount.deposit(Double.parseDouble(valueText.getText()));
JOptionPane.showMessageDialog(null, "Deposit Complete ");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please Enter a Numerical Value");
}
} // End deposit/checking
if (savingsRadio.isSelected()) {
try {
savingsAccount.deposit(Double.parseDouble(valueText.getText()));
JOptionPane.showMessageDialog(null, "Deposit Complete");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please Enter a Numerical Value");
}
} // End deposit/savings
valueText.setText("");
} // End Deposit Events

if ("Transfer To".equalsIgnoreCase(source.getText())) {
if (checkingRadio.isSelected()) {
try {
String amountString = valueText.getText();
double transferAmount = Double.parseDouble(amountString);
if (transferAmount <= savingsAccount.getBalance()) {
savingsAccount.withdraw(transferAmount);
checkingAccount.deposit(transferAmount);
JOptionPane.showMessageDialog(null, "Transfer Complete ");
} else {
JOptionPane.showMessageDialog(null, "Insufficient Funds");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please Enter a Numerical Value");
}
} // End transfer/checking
if (savingsRadio.isSelected()) {
try {
String amountString = valueText.getText();
double transferAmount = Double.parseDouble(amountString);
if (transferAmount <= checkingAccount.getBalance()) {

checkingAccount.withdraw(transferAmount);
savingsAccount.deposit(transferAmount);
JOptionPane.showMessageDialog(null, "Transfer Complete ");
} else {
JOptionPane.showMessageDialog(null, "Insufficient Funds");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please Enter a Numerical Value");
}
} // End transfer/savings


valueText.setText("");
} // End Transfer Events

if ("Balance".equalsIgnoreCase(source.getText())) {
double currentBalance;
DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00");

if (checkingRadio.isSelected()) {
currentBalance = checkingAccount.getBalance();
JOptionPane.showMessageDialog(null, "Current Balance: $" + df.format(currentBalance));
} else if (savingsRadio.isSelected()) {
currentBalance = savingsAccount.getBalance();
JOptionPane.showMessageDialog(null, "Current Balance: $" + df.format(currentBalance));
} else {
JOptionPane.showMessageDialog(null, "Please Select an Account");
}
} // End Balance Events
} // End ActionPerformed
} // End class myListener

public static void main(String[] args) {
ATM atm = new ATM();
// Checking and Savings Objects
checkingAccount = new Account(0);
savingsAccount = new Account(0);
} // End Main
} // End class ATM

最佳答案

I need an event handler that ensure the data typed in the TextField is numeric

使用应用于 JTextFieldDocumentDocumentFilter 来限制可以在其中输入的内容。

看看Implementing a Document FilterDocumentFilter Examples了解更多详情。

您还可以使用 JSpinnerJFormattedTextField 来获得或多或少相同的结果,请参阅 How to Use SpinnersHow to Use Formatted Text Fields了解更多详情

also only checking or savings RadioButtons are selected at one time

使用 ButtonGroup 将该组中所选项目的数量限制为单个项目

参见How to Use the ButtonGroup Component了解更多详情

关于java - ClassCastException 异常处理和类创建需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32643770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com