java - Java 中的数组和银行账户

标签 java arrays bank

我正在尝试编写一个简单的银行帐户管理程序,该程序执行以下操作:

使用从用户处获取的帐号和余额并存储在数组中创建一个新帐户 选择一个帐户(从数组中) 删除所选帐户 提款并存入所选账户。

问题:我不明白我的错误是什么。

我尝试使用不同类型的数组来存储帐号和余额,但我还没有找到答案。我在网络和 Stackoverflow 上搜索引用资料、文档、简单的示例,但找不到任何内容(我找到的那些使用了一些我还没有学过的命令和东西,所以我可以理解它们是如何工作的)。我是初学者,仍在学习中,希望得到一些建议。谢谢!

//Bank account class
public class account {
private int ANumber;
private double balance;

public account(double initialBalance, int accno) {
    balance = initialBalance;
    ANumber = accno;
}

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

public double withdraw(double amount) {
    balance -= amount;
    return amount;
}

public double getBalance() {
    return balance;
}
public int getAccount(){
    return ANumber;
}
}

这是主类

 import java.util.Scanner;
 // main class
 public class bankmain {
 public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    // Menu starts from here
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the option for the operation you need:");
    System.out.println("****************************************************");
    System.out.println("[ Options: ne - New Account de - Delete Account ]");
    System.out.println("[       dp - Deposit    wi - Withdraw      ]");
    System.out.println("[           se - Select Account ex - Quit      ]");
    System.out.println("****************************************************");
    System.out.print("> ");  //indicator for user input
    String choice = input.next();
    //Options
    while(true){
  if(choice == "ne"){
    int nacc;
    int bal;
    int [][]array = new int[nacc][bal];   // Array for account and balance
    System.out.print("Insert account number: ");
    nacc =input.nextInt(); //-- Input nr for array insertion
    System.out.print("Enter initial balance: ");
    bal=input.nextInt(); //-- Input nr for array insertion
    System.out.println("Current account: " + nacc + " " +  "Balance " + bal);
    break;
  }
  // account selection      
  if(choice.equals("se")){
    System.out.println("Enter number of account to be selected: ");
    //user input for account nr from array
    System.out.println("Account closed.");
  }     
  //close account
  if(choice.equals("de")){
    //array selected for closing
    System.out.println("Account closed.");
  }
  // deposit
  if(choice.equals("dp")){
    System.out.print("Enter amount to deposit:  ");
    double amount = scan.nextDouble();
    if(amount <= 0){
        System.out.println("You must deposit an amount greater than 0.");
    } else {
        System.out.println("You have deposited " + (amount + account.getBalance()));
    }
  }
  // withdrawal     
  if(choice.equals("wi")){
    System.out.print("Enter amount to be withdrawn: ");
    double amount = scan.nextDouble();
        if (amount > account.balance()){ 
            System.out.println("You can't withdraw that amount!");
   } else if (amount <= account.balance()) {
    account.withdraw(amount);
    System.out.println("NewBalance = " + account.getBalance());
   }
   }
//quit 
if(choice == "ex"){
    System.exit(0);
        } 
    }   // end of menu loop
 }// end of main
 } // end of class

最佳答案

您的代码在很多层面上都是错误的 - 首先尝试调整您的格式和命名约定,这样您就不会养成坏习惯。不要使用小字母来命名类,尝试使用完整的单词来描述变量和字段,就像 Account.class 示例中的那样:

public class Account  {
    private Integer accountNumber;
    private Double balance;

    public Account(final Integer accountNumber, final Double initialBalance) {
        this.accountNumber = accountNumber;
        balance = initialBalance;
    }

    public Double deposit (double depositAmmount) {
        balance += depositAmmount;
        return balance;
    }

    public Double withdraw(double withdrawAmmount) {
        balance -= withdrawAmmount;
        return balance;
    }

    public Double getBalance() {
        return balance;
    }

    public Integer getAccountNumber() {
        return accountNumber;
    }
}

还尝试在所有代码中使用相同的格式(即括号后的空格),以便您更容易阅读。

现在 - 您的应用出了什么问题:

  1. 为您的帐户定义适当的持有者,即 HashMap,它将保存有关所有帐户的信息,并能够通过 accountNumber 找到它们。

    HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>() ;

  2. 这个应该位于 while 循环内,因为您希望用户执行多项任务。您可以省略 println,但用户必须返回到屏幕顶部才能看到选项。

    System.out.println("Enter the option for the operation you need:");
    System.out.println("****************************************************");
    System.out.println("[ Options: ne - New Account de - Delete Account ]");
    System.out.println("[       dp - Deposit    wi - Withdraw      ]");
    System.out.println("[           se - Select Account ex - Quit      ]");
    System.out.println("****************************************************");
    System.out.print("> ");  //indicator for user input
    String choice = input.nextLine();   
    System.out.println("Your choice: " + choice);
    
  3. 您不应使用“==”运算符来比较字符串,因为它可能不会返回预期值。看看:How do I compare strings in Java?What is the difference between == vs equals() in Java? 。为了安全起见,请使用对象等于,即:

    choice.equals("ne")
    
  4. 没有您创建帐户的位置:

    Account newAccount = new Account(newAccountNumber, initialBalance);
    
  5. 您没有使用 if-else,只是使用了 if's。它应该看起来更像这样(如果已经发现选项是“ne”,为什么要检查选项是否是“wi”):

    if(choice.equals("ne")) {
        //doStuff
    } else if choice.equals("se") {
        //doStuff
    } //and so on.
    
  6. 如果您使用的 Java 版本 >= 7,那么您可以使用 switch 来代替 if-else 来比较字符串。

  7. 没有错误选项的通知:

    } else {
        System.out.println("Wrong option chosen.");
    }
    
  8. 您没有关闭 Scanner 对象。这在这里并不重要,因为它在 main 方法中,并且会随之关闭,但使用完后始终关闭流、数据源等是一个好习惯的问题:

    input.close(); 
    

所以整个代码可以如下所示:

import java.util.HashMap;
import java.util.Scanner;
// main class
public class BankAccount {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>(); 

         //Options
        while(true) {

            System.out.println("Enter the option for the operation you need:");
            System.out.println("****************************************************");
            System.out.println("[ Options: ne - New Account de - Delete Account ]");
            System.out.println("[       dp - Deposit    wi - Withdraw      ]");
            System.out.println("[           se - Select Account ex - Quit      ]");
            System.out.println("****************************************************");
            System.out.print("> ");  //indicator for user input

            String choice = input.next();   
            System.out.println("Your choice: " + choice);

            if(choice.equals("ne")) {
                Integer newAccountNumber;
                Double initialBalance;
                Account newAccount;

                // Array for account and balance
                System.out.print("Insert account number: ");
                newAccountNumber = input.nextInt(); //-- Input nr for array insertion
                System.out.print("Enter initial balance: ");
                initialBalance=input.nextDouble(); //-- Input nr for array insertion
                newAccount = new Account(newAccountNumber, initialBalance);
                accountMap.put(newAccountNumber, newAccount);
                System.out.println("New Account " + newAccountNumber + " created with balance: " + initialBalance);
            }
            //select account
            else if(choice.equals("se")) {
                System.out.println("Enter number of account to be selected: ");
                Integer accountToGetNumber = input.nextInt();
                Account returnedAccount = accountMap.get(accountToGetNumber);
                if (returnedAccount != null)
                {
                    System.out.println("Account open. Current balance: " + returnedAccount.getBalance());
                }
                else
                {
                    //user input for account nr from array
                    System.out.println("Account does not exist.");
                }
            }
            //close account
            else if(choice.equals("de"))
            {
                System.out.println("Enter number of account to be selected: ");
                Integer accountToDeleteNumber = input.nextInt();
                Account removedAccount = accountMap.remove(accountToDeleteNumber);
                if (removedAccount != null)
                {
                    System.out.println("Account " + removedAccount.getAccountNumber() + " has been closed with balance: " + removedAccount.getBalance());
                }
                else
                {
                    //user input for account nr from array
                    System.out.println("Account does not exist.");
                }
            }
            // deposit
            else if(choice.equals("dp")) {
                System.out.println("Enter number of account to deposit: ");
                Integer accountToDeposit = input.nextInt();
                System.out.print("Enter amount to deposit:  ");
                double amount = input.nextDouble();
                if(amount <= 0){
                    System.out.println("You must deposit an amount greater than 0.");
                } else {
                    accountMap.get(accountToDeposit).deposit(amount);
                    System.out.println("You have deposited " + (amount));
                    System.out.println("Current balance " + accountMap.get(accountToDeposit).getBalance());
                }
            }
            // withdrawal     
            else if(choice.equals("wi")) {
                System.out.println("Enter number of account to withdraw: ");
                Integer accountToWithdraw = input.nextInt();
                System.out.print("Enter amount to withdraw:  ");
                double amount = input.nextDouble();
                if(amount <= 0) {
                    System.out.println("You must deposit an amount greater than 0.");
                } else {
                    accountMap.get(accountToWithdraw).withdraw(amount);
                    System.out.println("You have deposited " + (amount));
                    System.out.println("Current balance " + accountMap.get(accountToWithdraw).getBalance());
                }
            }
            //quit 
            else if(choice.equals("ex")) {
                break;
            } else {
                System.out.println("Wrong option.");
            } //end of if
        } //end of loop

        input.close();
    } //end of main
 } //end of class

还有很多需要改进的地方,即输入验证 - 但这应该在开始时有效。

关于java - Java 中的数组和银行账户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336914/

相关文章:

ios - 从 subview 中的父 View Controller 检索数组

java - Eclipse Java - 发生错误 (Win10)

java - 使用 WindowManager 覆盖页脚

java - TabLayoutPanel 动态调整大小?

python - 使用 numpy genfromtxt 读取每第 n 行的最快方法

objective-c - 关于 Objective-C 中没有主体的 "for"循环的奇怪编译器优化/行为

Java多线程银行转账、同步问题

php - 确定生成的日期是否属于假期(PHP)?

api - 如何以编程方式下载美国银行交易记录?

java - 将 int 放入对象数组后,我得到的是 Integer 还是 int ?