Java ATM 程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26706313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:07:21  来源:igfitidea点击:

Java ATM Program

java

提问by tcd9

I'm doing an atm program and I'm having a hard time trying to figure out how to get it to actually deposit and withdraw. The balance starts off automatically as $0 but I can't get anything I type in to actually add on or subtract to it what am I doing wrong?

我正在做一个 atm 程序,我很难弄清楚如何让它实际存入和取出。余额自动以 0 美元开始,但我无法输入任何内容来实际添加或减去它我做错了什么?

public class ATM {
static Scanner keyboard = new Scanner(System.in);
static String acctNum, pwd, result;
static double oldBalance, newBalance, deposit, withdraw;
static int choose;

public static void main(String[] args) {
    for (int run = 0; run < 3; run++) {
        System.out.println("Enter your account number");
        acctNum = keyboard.nextLine();
        System.out.println("Enter your account password");
        pwd = keyboard.nextLine();

        result = checkID(acctNum, pwd);
        if (!result.equals("ERROR")) {
            break;
        } else if (run == 2) {// you cannot try to log in anymore than 3
                                // times
            System.out.println("MAXIMUM TRIES EXCEEDED");
            return;
        }

    }
    menu();
}

public static String checkID(String acctNum, Object pwd) {
    String result = "ERROR";
    String a = "44567-5 mypassword 520.36";
    String b = "1234567-6 anotherpassword 48.20";
    String c = "4321-0 betterpassword 96.74";

    if (acctNum.equals("44567-5") && pwd.equals("mypassword")) {
        result = "520.36";
    } else if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")) {
        result = "48.20";
    } else if (acctNum.equals("4321-0") && pwd.equals("betterpassword")) {
        result = "96.74";
    }
    System.out.println(result);
    return result;
}

public static int menu() {
    System.out
            .println("Choose one of the following: \n1.Display Balance\n2.Deposit\n3.Withdraw\n4.Log Out");
    choose = keyboard.nextInt();

    if (choose == 1) {// 1. Display Balance
        displayBalance();
        menu();
        return 1;

    }
    if (choose == 2) {// 2. Deposit
        deposit();
        menu();
        return 2;

    }
    if (choose == 3) {// 3. Withdraw
        withdraw();
        menu();
        return 3;

    }
    if (choose == 4) {// 4. Log out
        System.out.println("You are logged out.");
        return 4;

    }
    if (choose <= 5) {// type in anything greater than 4 and you will get a
                        // system error
        System.out.println("System Error");
        menu();
        return 5;
    }
    if (choose >= 1) {// type in anything less than 1 and you will get a
                        // system error
        System.out.println("System Error");
        menu();
        return 6;
    }
    return choose;

}

public static double deposit() {
    System.out.println("How much would you like to deposit?");
    deposit = keyboard.nextInt();
    System.out.println((deposit + oldBalance)==newBalance);// deposit money into balance
    return 2;
}

public static double displayBalance() {
    System.out.println("Total balance is: $" + oldBalance);
    oldBalance = 0.00;
    return 1;
}

public static double withdraw() {
    System.out.println("How much would you like to withdraw?");
    withdraw = keyboard.nextInt();
    System.out.println(newBalance + withdraw);// withdraw money from balance
    return 3;
}

}

}

采纳答案by hfontanez

A few observations:

一些观察:

  1. Your class should not declare oldBalance, deposit, and withdrawal as global variables. The withdrawal method should not have access to the deposit variable and vice versa. It is a good programming practice to limit the scope of your variables as much as you can. Because a "deposit" variable is not really required outside this method, there is absolutely no reason to make it a global variable. The same cannot be said about "current balance." This variable is needed by all methods of the class: deposit, withdrawal, displayBalance, etc. Therefore, there is a good reason why to make it global (Still, if you can solve the problem with less scope, you should do that).

  2. I do not see why deposit()and withdrawal()need to return anything.

  1. 您的类不应将 oldBalance、存款和取款声明为全局变量。取款方法不应访问存款变量,反之亦然。尽可能地限制变量的范围是一种很好的编程习惯。因为在此方法之外并不真正需要“存款”变量,所以绝对没有理由将其设为全局变量。关于“当前余额”,情况并非如此。该类的所有方法都需要此变量:存款、取款、显示余额等。因此,将其设为全局是有充分理由的(不过,如果您可以用较小的范围解决问题,则应该这样做)。

  2. 我不明白为什么deposit()并且withdrawal()需要返回任何东西。

The simplest implementation of deposit()and withdrawal()is to simply add the user input to the currentBalanceand save it in currentBalance.

deposit()and的最简单实现withdrawal()是简单地将用户输入添加到currentBalance并将其保存在currentBalance.

public void deposit()
{
   Scanner input = new Scanner(System.in);
   System.out.printn("Enter deposit amount: );
   double amount = input.nextDouble();
   System.out.println("Your deposit amount: " + amount);
   currentBalance += amount;
   System.out.println("Your new balance is: + currentBalance);
}

public void withdrawal()
{
   Scanner input = new Scanner(System.in);
   System.out.printn("Enter withdrawal amount: );
   double amount = input.nextDouble();
   System.out.println("Your withdrawal amount: " + amount);
   currentBalance -= amount;
   System.out.println("Your new balance is: + currentBalance);
}

You are never saving the current balance. The == operator is a comparison operator, not an assignment operator. When you do something like this:

您永远不会保存当前余额。== 运算符是比较运算符,而不是赋值运算符。当你做这样的事情时:

System.out.println((deposit + oldBalance)==newBalance);

Or like this:

或者像这样:

System.out.println(newBalance + withdraw);

All you are doing is to pass the values to the println()method and not updating the variable that is supposed to hold the balance. In fact, the first one should print false(unless both deposit and oldBalance are zero). If you look at my code example, currentBalance += amount;is shorthand for currentBalance = currentBalance + amount;which means "add this amountto currentBalanceand store it in currentBalance. Because I am reusing currentBalance, I eliminated the need for an oldBalancevariable.

您所做的只是将值传递给println()方法,而不是更新应该保持平衡的变量。事实上,第一个应该打印false(除非存款和旧余额都为零)。如果你看一下我的代码示例,currentBalance += amount;是简写currentBalance = currentBalance + amount;,意思是“这添加amountcurrentBalance并将其存储在currentBalance。因为我重用currentBalance,我消除了一个需要oldBalance的变量。

回答by priyanka.sarkar

Full Running Code

完整运行代码

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import java.util.ArrayList;
import java.util.Scanner;

/**
   A simulation of an automatic teller machine
*/

public class ATM  {
static Scanner keyboard = new Scanner(System.in);
static String acctNum, pwd, result;
static double oldBalance, newBalance, deposit, withdraw,currentBalance;
static int choose;

public static void main(String[] args) {
    for (int run = 0; run < 3; run++) {
        System.out.println("Enter your account number");
        acctNum = keyboard.nextLine();
        System.out.println("Enter your account password");
        pwd = keyboard.nextLine();

        result = checkID(acctNum, pwd);
        if (!result.equals("ERROR")) {
            break;
        } else if (run == 2) {// you cannot try to log in anymore than 3
                                // times
            System.out.println("MAXIMUM TRIES EXCEEDED");
            return;
        }

    }
    menu();
}

public static String checkID(String acctNum, Object pwd) {
    String result = "ERROR";
    String a = "44567-5 mypassword 520.36";
    String b = "1234567-6 anotherpassword 48.20";
    String c = "4321-0 betterpassword 96.74";

    if (acctNum.equals("2345") && pwd.equals("2345")) {
        result = "520.36";
    } else if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")) {
        result = "48.20";
    } else if (acctNum.equals("4321-0") && pwd.equals("betterpassword")) {
        result = "96.74";
    }
    System.out.println(result);
    return result;
}

public static int menu() {
    System.out.println("Choose one of the following: \n1.Display Balance\n2.Deposit\n3.Withdraw\n4.Log Out");
    choose = keyboard.nextInt();

    if (choose == 1) {// 1. Display Balance
        displayBalance();
        menu();
        return 1;

    }
    if (choose == 2) {// 2. Deposit
        deposit();
        menu();
        return 2;

    }
    if (choose == 3) {// 3. Withdraw
        withdraw();
        menu();
        return 3;

    }
    if (choose == 4) {// 4. Log out
        System.out.println("You are logged out.");
        return 4;

    }
    if (choose <= 5) {// type in anything greater than 4 and you will get a
                        // system error
        System.out.println("System Error");
        menu();
        return 5;
    }
    if (choose >= 1) {// type in anything less than 1 and you will get a
                        // system error
        System.out.println("System Error");
        menu();
        return 6;
    }
    return choose;

}

public static void deposit()
{
   Scanner input = new Scanner(System.in);
   System.out.println("Enter deposit amount:");
   double amount = input.nextDouble();
   System.out.println("Your deposit amount: " + amount);
   currentBalance += amount;
   System.out.println("Your new balance is: " + currentBalance);
}

public static double displayBalance() {
    System.out.println("Total balance is: $" + currentBalance);
    oldBalance = 0.00;
    return 1;
}

public static void withdraw()
{
   Scanner input = new Scanner(System.in);
   System.out.println("Enter withdrawal amount: ");
   double amount = input.nextDouble();
   System.out.println("Your withdrawal amount: " + amount);
   currentBalance -= amount;
   System.out.println("Your new balance is: " + currentBalance);
}
}

回答by Arun

    package shraam.bank.atm;

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;
    import java.util.logging.Level;


    public class CalculateMoneyAtm {
        static Integer initialtwothousandrupees = 0;
        static Integer initialhundressrupees = 0;
        static Integer initialfiftyrupees = 0;
        static Integer initialtenrupees = 0;

        static Integer twothousandrupees = 0;
        static Integer hundressrupees = 0;
        static Integer fiftyrupees = 0;
        static Integer tenrupees = 0;
        static Integer totalAmount = 0;

        public static void main(String[] args) {

            ATMStatus atmStatus = new ATMStatus();
            getMoney(atmStatus);

        }//end of psvm

        public static void reRun(ATMStatus atmStatus) {
            MyLog.logit().info("Would u like to credit more money ? y/n");
            System.out.println("Would u like to credit more money ? y/n ");
            Scanner input = new Scanner(System.in);
            String choice = input.nextLine();
            if (choice.equals("y") || choice.equals("Y")) {
                getMoney(atmStatus);
            }
            if (choice.equals("n") || choice.equals("N")) {
                System.exit(1);
            } else {
                MyLog.logit().log(Level.SEVERE, "Invalid Input :"+choice);
                System.out.println("Invalid Input");
            }
            reRun(atmStatus);
        }

        public static void getMoney(ATMStatus atmStatus) {
            twothousandrupees = 0;
             hundressrupees = 0;
             fiftyrupees = 0;
             tenrupees = 0;
             totalAmount = 0;
            Integer amountInt=0;
            System.out.println("Currency Avaialbe in ATM");
            for (String key : atmStatus.getAvaialableMoney().keySet()) {
                System.out.println(atmStatus.getAvaialableMoney().get(key) + ":"
                        + key + " Notes");
            }

            for (String key : atmStatus.getAvaialableMoney().keySet()) {
                if (key.equals("2000"))
                    initialtwothousandrupees = atmStatus.getAvaialableMoney().get(key);
                if (key.equals("100"))
                    initialhundressrupees = atmStatus.getAvaialableMoney().get(key);
                if (key.equals("50"))
                    initialfiftyrupees = atmStatus.getAvaialableMoney().get(key);
                if (key.equals("10"))
                    initialtenrupees = atmStatus.getAvaialableMoney().get(key);
            }

            Scanner input = new Scanner(System.in);
            System.out.print("Enter Money > ");
            String amount = input.nextLine();
            try {
                try{
                 amountInt = Integer.parseInt(amount);
                 if(amountInt%10!=0)
                 {
                     System.out.println("Please enter amount in multiple of 10 ");
                     reRun(atmStatus);
                 }
                }catch(NumberFormatException ne){
                    MyLog.logit().log(Level.SEVERE, ne.getMessage());
                }
                System.out.print("Required Amount : ");
                System.out.println(amount);

                totalAmount = ((initialtwothousandrupees * 2000) + (initialhundressrupees * 100)
                        + (initialfiftyrupees * 50) + (initialtenrupees * 10));
                System.out
                        .println("Total Available amount in ATM : " + totalAmount);
                if (totalAmount < amountInt) {
                    System.out
                            .println("Total Avaialble amount is less in atm, Sorry for Inconvience");
                     reRun(atmStatus);
                }


                while (amountInt >= 2000 && initialtwothousandrupees > 0) {
                    initialtwothousandrupees = initialtwothousandrupees - 1;
                    twothousandrupees++;
                    amountInt = amountInt - 2000;
                }

                while (amountInt >= 100 && initialhundressrupees > 0) {
                    initialhundressrupees = initialhundressrupees - 1;
                    hundressrupees++;
                    amountInt = amountInt - 100;
                }

                while (amountInt >= 50 && initialfiftyrupees > 0) {
                    initialfiftyrupees = initialfiftyrupees - 1;
                    fiftyrupees++;
                    amountInt = amountInt - 50;
                }
                while (amountInt >= 10 && initialtenrupees > 0) {
                    initialtenrupees = initialtenrupees - 1;
                    tenrupees++;
                    amountInt = amountInt - 10;
                }
                if (amountInt > 0) {
                    System.out.println("No avalable balance in this unit");
                    reRun(atmStatus);
                } else {
                    System.out.println("Plz take your money in currency");
                    Map<String, Integer> avaialableMoney = new HashMap<String, Integer>();
                    System.out.println("     No of 2000:"+ twothousandrupees);
                    System.out.println("     No of 100:"+ hundressrupees);
                    System.out.println("     No of 50:"+ fiftyrupees);
                    System.out.println("     No of 10:"+ tenrupees);
                    avaialableMoney.put("2000", (initialtwothousandrupees));
                    avaialableMoney.put("100", (initialhundressrupees));
                    avaialableMoney.put("50", (initialfiftyrupees));
                    avaialableMoney.put("10", (initialtenrupees));
                    atmStatus.setAvaialableMoney(avaialableMoney);
                }
                //return amountInt;
            } catch (Exception e) {
                MyLog.logit().log(Level.SEVERE, e.getMessage());
            }
            System.out.println("Take your Amount = "+(2000*twothousandrupees+100*hundressrupees+50*fiftyrupees+10*tenrupees));
            reRun(atmStatus);

        }//end of getMoney
    }

    package shraam.bank.atm;

    import java.util.HashMap;
    import java.util.Map;
    import java.util.logging.Level;

    public class ATMStatus {
        public  Map<String,Integer> avaialableMoney=new HashMap<String,Integer>();
        public ATMStatus(){
                MyLog.logit().log(Level.INFO, " ATMStatus Initialized");

        avaialableMoney.put("2000", 10);
        avaialableMoney.put("100", 10);
        avaialableMoney.put("50", 10);
        avaialableMoney.put("10", 10);
        }
        public  Map<String, Integer> getAvaialableMoney() {
            return this.avaialableMoney;
        }
        public void setAvaialableMoney(Map<String, Integer> avaialableMoney) {
            this.avaialableMoney = avaialableMoney;
        }

    }

    package shraam.bank.atm;

    import java.io.IOException;
    import java.util.logging.FileHandler;
    import java.util.logging.Logger;
    import java.util.logging.SimpleFormatter;

    public class MyLog {

        public static Logger logit()
        {
            Logger logger = Logger.getLogger("MyLog");  
            FileHandler fh;  

            try {  

                // This block configure the logger with handler and formatter  
                fh = new FileHandler("C:/ArunTest/temp/MyLogFile.log");  
                logger.addHandler(fh);
                SimpleFormatter formatter = new SimpleFormatter();  
                fh.setFormatter(formatter);  

                // the following statement is used to log any messages  
                logger.info("My first log");  

            } catch (SecurityException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }
            return logger;  
        }

    }
//
output:
Nov 27, 2016 10:43:48 PM shraam.bank.atm.MyLog logit
INFO: My first log
Nov 27, 2016 10:43:48 PM shraam.bank.atm.ATMStatus <init>
SEVERE:  ATMStatus 
Currency Avaialbe in ATM
10:100 Notes
10:2000 Notes
10:50 Notes
10:10 Notes
Enter Money > 540
Required Amount : 540
Total Available amount in ATM : 21600
Plz take your money in currency
     No of 2000:0
     No of 100:5
     No of 50:0
     No of 10:4
Take your Amount = 540
Nov 27, 2016 10:43:52 PM shraam.bank.atm.MyLog logit
INFO: My first log
Nov 27, 2016 10:43:52 PM shraam.bank.atm.CalculateMoneyAtm reRun
INFO: Would u like to credit more money ? y/n
Would u like to credit more money ? y/n 
y
Currency Avaialbe in ATM
5:100 Notes
10:2000 Notes
10:50 Notes
6:10 Notes
Enter Money > 2060
Required Amount : 2060
Total Available amount in ATM : 21060
Plz take your money in currency
     No of 2000:1
     No of 100:0
     No of 50:1
     No of 10:1
Take your Amount = 2060
Nov 27, 2016 10:44:04 PM shraam.bank.atm.MyLog logit
INFO: My first log
Nov 27, 2016 10:44:04 PM shraam.bank.atm.CalculateMoneyAtm reRun
INFO: Would u like to credit more money ? y/n
Would u like to credit more money ? y/n