繁体   English   中英

Java-在简单的GUI Banking程序中运行总计

[英]Java - Running Total in Simple GUI Banking Program

我在尝试弄清楚如何为我的银行程序编码存款和取款并保持运行总额时遇到麻烦。 该程序应从银行的$ 0开始,并且不能低于$ 0。 您可以从该帐户存款和取款,还可以从菜单中查看谁存款和取款。

我需要帮助尝试对保留帐户总数的部分进行编码,以使用户提取的金额不能超过帐户中的金额。 因此,如果帐户中有$ 100,他们将无法提取$ 200。

注意:“创建帐户”操作仅用于在存款/取款时给自己一个唯一的ID,完全不影响登录。

Login.java:

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Login {

    private JFrame mainFrame;
    private JLabel headerLabel;
    private JLabel statusLabel;
    private JPanel controlPanel;

    int cid;

    public Login() {
        prepareGUI();
    }

    public static void main(String[] args) {
        Login login = new Login();
        login.showTextField();
    }

    private void prepareGUI() {
        mainFrame = new JFrame("Login");
        mainFrame.setSize(400, 400);
        mainFrame.setLayout(new GridLayout(3, 1));
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent wE) {
                System.exit(0);
            }
        });
        headerLabel = new JLabel("", JLabel.CENTER);
        statusLabel = new JLabel("", JLabel.CENTER);

        statusLabel.setSize(350, 100);

        controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());

        mainFrame.add(headerLabel);
        mainFrame.add(controlPanel);
        mainFrame.add(statusLabel);
        mainFrame.setVisible(true);
    }

    private void showTextField() {
        headerLabel.setText("Account Access");

        JLabel namelabel = new JLabel("User ID: ", JLabel.RIGHT);
        JLabel passwordLabel = new JLabel("Password: ", JLabel.CENTER);
        final JTextField userText = new JTextField(6);
        final JPasswordField passwordText = new JPasswordField(6);

        JButton loginButton = new JButton("Login");
        JButton createAccountButton = new JButton("Create Account?");

        loginButton.addActionListener(new ActionListener() {
            @SuppressWarnings("deprecation")
            public void actionPerformed(ActionEvent e) {
                /*
                 * check for correct password/usernameinclude a desired
                 * 'hardcoded' username /password to verify againstuser input
                 * values for both username & password fieldsgive popup message
                 * if either username or password is incorrect
                 */
                if (userText.getText().equals("mister")
                        && passwordText.getText().equals("jim")) {

                    // close of Login window
                    mainFrame.dispose();
                    // open up MainWindow
                    new MainWindow(userText.getText(), cid);

                }

                else {
                    String message = "Incorrect username and/or password!\nTry again!";
                    JOptionPane.showMessageDialog(null, message);
                }
            }

        });

        createAccountButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String name = JOptionPane.showInputDialog(null,
                        "Enter your name");
                // generate client id
                Random r = new Random();
                cid = r.nextInt(100000);
            }

        });

        controlPanel.add(namelabel);
        controlPanel.add(userText);
        controlPanel.add(passwordLabel);
        controlPanel.add(passwordText);
        controlPanel.add(loginButton);
        controlPanel.add(createAccountButton);
        mainFrame.setVisible(true);
    }
}

MainWindow.java:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class MainWindow extends JFrame {

    private JFrame mainFrame;
    private JLabel statusLabel;

    private JMenu file = new JMenu("File");
    private JMenu Account = new JMenu("Account");

    int cid;

    public MainWindow(String name, final int cid) {

        this.cid = cid;

        file.setMnemonic('F');
        JMenuItem ItemNew = new JMenuItem("New");
        ItemNew.setMnemonic('N');
        file.add(ItemNew);
        JMenuItem ItemExit = new JMenuItem("Exit");
        ItemExit.setMnemonic('x');
        file.add(ItemExit);

        ItemExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        Account.setMnemonic('A');
        JMenuItem ItemDeposits = new JMenuItem("Deposits");
        ItemDeposits.setMnemonic('D');
        Account.add(ItemDeposits);

        JMenuItem ItemWithdraws = new JMenuItem("Withdrawals");
        ItemWithdraws.setMnemonic('W');
        Account.add(ItemWithdraws);

        JMenuItem ItemView = new JMenuItem("View Account");
        ItemView.setMnemonic('W');
        Account.add(ItemView);

        ItemDeposits.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {// add a deposit
                Double sBal = Double.parseDouble(JOptionPane.showInputDialog(
                        null, "Enter deposit amount"));
                // create Account object
                Account accountObj = new Account();
                accountObj.setBal(sBal);

                // show result
                System.out.println(accountObj.getCID() + accountObj.getBal());
                File f = new File("account.dat");
                try {
                    FileWriter fw = new FileWriter(f, true);
                    fw.write(cid + " " + accountObj.getBal() + "\n");

                    fw.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });

        ItemWithdraws.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {// add a deposit
                Double sBal = Double.parseDouble(JOptionPane.showInputDialog(
                        null, "Enter withdrawal amount"));
                // create Account object
                Account accountObj = new Account();
                accountObj.setBal(sBal);

                // show result
                System.out.println(accountObj.getBal());
                File f = new File("account.dat");
                try {
                    FileWriter fw = new FileWriter(f, true);
                    fw.write(cid + " " + accountObj.getBal() + "\n");

                    fw.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });

        ItemView.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusLabel.setVisible(false); // make status label invisible

                // set up JTable logic
                Vector<Vector<String>> myVector = new Vector<Vector<String>>(); // multidim
                                                                                // vector
                                                                                // (vector
                                                                                // of
                                                                                // vectors)

                try {

                    BufferedReader file = new BufferedReader(new FileReader(
                            "account.dat"));
                    String input;
                    while ((input = file.readLine()) != null) {
                        String[] temp = input.split(" "); // grab row (record)
                                                            // data parsed by a
                                                            // space
                        Vector<String> v = new Vector<String>(); // single dim
                                                                    // vector to
                                                                    // get
                                                                    // fields in
                                                                    // each
                                                                    // record
                        for (int i = 0; i < temp.length; i++) {
                            v.add(temp[i]); // add each field to vector
                        }
                        myVector.add(v); // add all field data as a new vector
                                            // row (represents a record of data
                                            // each dynamically!!!)
                    }
                    file.close();
                } catch (IOException e1) {
                    e1.printStackTrace(System.err);
                }

                Vector<String> columnData = new Vector<String>();
                columnData.addElement("ID");
                columnData.addElement("D/W");

                try {

                    JTable jt;

                    jt = new JTable(myVector, columnData);
                    jt.setBounds(30, 40, 200, 300);
                    JScrollPane sp = new JScrollPane(jt);

                    mainFrame.add(sp);

                } catch (Exception ex) {
                    System.out.println("There was a problem: " + ex);
                    ex.printStackTrace();
                }
            }
        });

        ItemNew.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        statusLabel = new JLabel();

        statusLabel.setText("Currently Logged In: " + name + " #" + cid);
        statusLabel.setHorizontalAlignment(JLabel.RIGHT);
        statusLabel.setVerticalAlignment(JLabel.TOP);

        prepareGUI();

    }

    private void prepareGUI() {
        mainFrame = new JFrame("Main");

        // adjust label position to sit in the upper right corner of window
        mainFrame.add(statusLabel);

        // add menu bar component to frame
        JMenuBar bar = new JMenuBar();
        bar.add(file); // set menu orders
        bar.add(Account);
        mainFrame.setJMenuBar(bar);

        mainFrame.setSize(400, 400);
        mainFrame.setVisible(true);

    }

}

Account.java:

public class Account {

    // data members
    double bal;
    static double intRate;
    int cid;
    String name;

    public Account() {
    }

    // getters
    double getBal() {
        return bal;
    }

    int getCID() {
        return cid;
    }

    // setters
    void setBal(double bal) {
        // update balance
        this.bal += bal;

    }

    void setCID(int cid) {
        this.cid = cid;
    }

    static void adjustIntRate(double r) {
        intRate = r;
    }

}

我需要帮助尝试对保留帐户总数的部分进行编码,以使用户提取的金额不能超过帐户中的金额。 因此,如果帐户中有$ 100,他们将无法提取$ 200。

尽管您不花力气解释这一点,但我想setBal是您用来提取和存放的东西。 我还假定传递给此方法的负值意味着退出。

如果您想完全阻止提现超出您的要求的请求,请使用:

void setBal(double bal) {

    if (this.bal + bal >= 0)
        this.bal += bal;
}

意思是,“如果提款金额等于或大于0,请继续(否则忽略)”。

如果要允许提取将您设置为0的最大金额,请使用:

void setBal(double bal) {

    if (this.bal + bal >= 0)
        this.bal += bal;
    else
        this.bal = 0;
}

意思是,“如果提取金额,您将获得0或更多,否则您将剩下0”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM