簡體   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