数组和银行账户的Java [英] Arrays and bank accounts in Java

查看:340
本文介绍了数组和银行账户的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个简单的银行账户管理程序,执行以下操作:

创建具有帐号和平衡一个新的帐户从用户并存入数组
选择(从阵列)的帐户
删除选定的帐户
提款并存入选定帐户。

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

我尝试使用不同类型的账户和余额存储阵列,但我没有没有找到答案。我搜索的引用文件,文档,简单的例子网页和#1,但找不到任何(即我中找到的,使用一些命令和事情,我还不知道,所以我可以了解他们的工作)。我是一个初学者,我仍然在学习,并将AP preciate一些建议。谢谢!

  //银行账户类
公共类账户{
私人诠释aNumber的;
私人双平衡;公共账号(双initialBalance,诠释ACCNO){
    平衡= initialBalance;
    aNumber的= ACCNO;
}公共无效存款(双u_amm){
    余额+ = u_amm;
}公共双撤回(双额){
    平衡 - =金额;
    返回金额;
}公共双所以getBalance(){
    回到平衡;
}
公众诠释是getAccount(){
    返回aNumber的;
}
}

这是主类

 进口java.util.Scanner中;
 //主类
 公共类bankmain {
 公共静态无效的主要(字串[] args){
    扫描程序扫描=新的扫描仪(System.in);
    //菜单从这里开始
    扫描仪输入=新的扫描仪(System.in);
    的System.out.println(请输入您需要的操作选项:);
    的System.out.println(********* *********);
    的System.out.println([选项:东北 - 新帐户德 - 删除帐户]);
    的System.out.println([DP - 存款的Wi - 提取]);
    的System.out.println([ - 选择帐户恩 - SE退出]);
    的System.out.println(********* *********);
    System.out.print(>中); //用户输入指示
    字符串选择= input.next();
    //选项
    而(真){
  如果(选择==NE){
    INT NACC;
    INT BAL;
    INT [] []数组=新INT [NACC] [BAL]; //阵帐及资产
    System.out.print(插入帐号:);
    NACC = input.nextInt(); // - 输入NR数组插入
    System.out.print(输入初始余额:);
    BAL = input.nextInt(); // - 输入NR数组插入
    的System.out.println(经常账户+ NACC ++平衡+ BAL);
    打破;
  }
  //选择账户
  如果(choice.equals(SE)){
    的System.out.println(账户被选中输入数字:);
    //从阵列账户NR用户输入
    的System.out.println(账户关闭。);
  }
  //关闭账户
  如果(choice.equals(德)){
    //阵列选择关闭
    的System.out.println(账户关闭。);
  }
  //存款
  如果(choice.equals(DP)){
    System.out.print(输入金额存款);
    双量= scan.nextDouble();
    如果(度< = 0){
        的System.out.println(你必须存入金额大于0);
    }其他{
        的System.out.println(您已存入+(+量account.getBalance()));
    }
  }
  //撤军
  如果(choice.equals(无线网络)){
    System.out.print(输入量被撤回:);
    双量= scan.nextDouble();
        如果(量GT; account.balance()){
            的System.out.println(你不能撤销量!);
   }否则如果(度< = account.balance()){
    account.withdraw(量);
    的System.out.println(百伦=+ account.getBalance());
   }
   }
//放弃
如果(选择==EX){
    System.exit(0);
        }
    } //菜单循环结束
 } //主结束
 } //类的结束


解决方案

您code是错误在许多层面上 - 首先尝试在您的格式和命名约定的工作,所以你不要学坏习惯所。不使用小leters命名类,尽量用完整的单词来形容在Account.class例如变量和字段,如:

 公共类账户{
    私人整数使用accountNumber;
    私人双平衡;    公共帐户(最终整型了accountNumber,最终双initialBalance){
        this.accountNumber =使用accountNumber;
        平衡= initialBalance;
    }    公众存款双(双depositAmmount){
        平衡+ = depositAmmount;
        回到平衡;
    }    公共双撤回(双withdrawAmmount){
        平衡 - = withdrawAmmount;
        回到平衡;
    }    公共双所以getBalance(){
        回到平衡;
    }    公共整数getAccountNumber(){
        返回使用accountNumber;
    }
}

也可以尝试使用相同的格式(即括号后的空格)在所有code,所以它的简单供您阅读。

现在 - 什么是错在你的应用程序:


  1. 定义适当的持有人帐户即HashMap的,将持有所有账户信息,并能够通过使用accountNumber找到他们。

    的HashMap<整数,帐户> accountMap =新的HashMap<整数,帐户>();


  2. 这应该是你的while循环中,只要你想你的用户做多项任务。你可以ommit中的println的,但这时用户就不得不回到屏幕顶部看到的选项。

     的System.out.println(请输入您需要的操作选项:);
    的System.out.println(********* *********);
    的System.out.println([选项:东北 - 新帐户德 - 删除帐户]);
    的System.out.println([DP - 存款的Wi - 提取]);
    的System.out.println([ - 选择帐户恩 - SE退出]);
    的System.out.println(********* *********);
    System.out.print(>中); //用户输入指示
    字符串选择= input.nextLine();
    的System.out.println(您的选择:+选择);


  3. ,因为它可能不会返回预期值,则不应使用'=='操作比较字符串。看看:如何比较Java中的字符串 Java的== VS equals()方法的混乱。为世上使用的对象,而不是相等,即:

      choice.equals(NE)


  4. 有您创建的帐户没有地方:

     帐户newAccount =新帐户(newAccountNumber,initialBalance);


  5. 您没有的if-else,只是如果我们使用。它应该看起来更像(为什么要检查如果选择的是无线,如果它已经被认为是'东北')

     如果(choice.equals(NE)){
        //做东西
    }否则如果choice.equals(SE){
        //做东西
    } //等等。


  6. 如果您使用的Java版本> = 7,然后代替的if-else您可以使用开关来比较字符串。


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

     }其他{
        的System.out.println(错误的选项选择。);
    }


  8. 您没有关闭您的扫描对象。这真的不重要这里,因为它是在main方法,将它关闭,但它是很好的习惯所的问题用它做的时候总是关闭的流,数据来源等:

      input.close();


所以整个code可以是这样的:

 进口的java.util.HashMap;
进口java.util.Scanner中;
//主类
公共类的BankAccount {    公共静态无效的主要(字串[] args){        扫描仪输入=新的扫描仪(System.in);
        HashMap的<整数,帐户> accountMap =新的HashMap<整数,帐户>();         //选项
        而(真){            的System.out.println(请输入您需要的操作选项:);
            的System.out.println(********* *********);
            的System.out.println([选项:东北 - 新帐户德 - 删除帐户]);
            的System.out.println([DP - 存款的Wi - 提取]);
            的System.out.println([ - 选择帐户恩 - SE退出]);
            的System.out.println(********* *********);
            System.out.print(>中); //用户输入指示            字符串选择= input.next();
            的System.out.println(您的选择:+选择);            如果(choice.equals(NE)){
                整数newAccountNumber;
                双initialBalance;
                账户newAccount;                //阵帐及资产
                System.out.print(插入帐号:);
                newAccountNumber = input.nextInt(); // - 输入NR数组插入
                System.out.print(输入初始余额:);
                initialBalance = input.nextDouble(); // - 输入NR数组插入
                newAccount =新帐户(newAccountNumber,initialBalance);
                accountMap.put(newAccountNumber,newAccount);
                的System.out.println(新帐户+ newAccountNumber +与平衡创造:+ initialBalance);
            }
            //选择账户
            否则,如果(choice.equals(SE)){
                的System.out.println(账户被选中输入数字:);
                整数accountToGetNumber = input.nextInt();
                占returnedAccount = accountMap.get(accountToGetNumber);
                如果(returnedAccount!= NULL)
                {
                    的System.out.println(帐户开立当前余额:+ returnedAccount.getBalance());
                }
                其他
                {
                    //从阵列账户NR用户输入
                    的System.out.println(帐户不存在。);
                }
            }
            //关闭账户
            否则,如果(choice.equals(德))
            {
                的System.out.println(账户被选中输入数字:);
                整数accountToDeleteNumber = input.nextInt();
                占removedAccount = accountMap.remove(accountToDeleteNumber);
                如果(removedAccount!= NULL)
                {
                    的System.out.println(账户+ removedAccount.getAccountNumber()+已经关闭与平衡:+ removedAccount.getBalance());
                }
                其他
                {
                    //从阵列账户NR用户输入
                    的System.out.println(帐户不存在。);
                }
            }
            //存款
            否则如果(choice.equals(DP)){
                的System.out.println(输入帐户存款数:);
                整数accountToDeposit = input.nextInt();
                System.out.print(输入金额存款);
                双量= input.nextDouble();
                如果(度< = 0){
                    的System.out.println(你必须存入金额大于0);
                }其他{
                    accountMap.get(accountToDeposit).deposit(量);
                    的System.out.println(您已存入+(量));
                    的System.out.println(当前余额+ accountMap.get(accountToDeposit).getBalance());
                }
            }
            //撤军
            否则如果(choice.equals(无线网络)){
                的System.out.println(输入帐户中撤出数:);
                整数accountToWithdraw = input.nextInt();
                System.out.print(输入金额退出:);
                双量= input.nextDouble();
                如果(度< = 0){
                    的System.out.println(你必须存入金额大于0);
                }其他{
                    accountMap.get(accountToWithdraw).withdraw(量);
                    的System.out.println(您已存入+(量));
                    的System.out.println(当前余额+ accountMap.get(accountToWithdraw).getBalance());
                }
            }
            //放弃
            否则,如果(choice.equals(EX)){
                打破;
            }其他{
                的System.out.println(错误的选择。);
            } //如果结束
        } //循环结束        input.close();
    } //主结束
 } //类的结束

仍有很大的改善,即输入验证 - 但这应该开始时工作

I am trying to write a simple Bank Account Management program that does the following:

Creates a new account with Account number and Balance taken from user and stored in an array Selects an account (from the array) Deletes the account selected Withdraw and Deposit into account selected.

Problem: I don't understand what the my mistakes are.

I tried using different types of arrays for account number and balance storing, but I didn't not find the answer yet. I search the web and Stackoverflow for references, documentations, simple examples, but could not find any (the ones that I found, use some commands and things that I haven't learned yet so I can understand how they work). I am a beginner, I am still learning and would appreciate some advice. Thanks!

//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;
}
}

And this is the Main class

 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

解决方案

Your code was wrong on many levels - first try to work on your formatting and naming conventions so you don't learn bad habbits. Dont use small leters for naming classes, try to use full words to describe variables and fields, like in that Account.class example:

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;
    }
}

Also try to use the same formatting(ie. spaces after brackets) in all code, so that it's simpler for you to read.

Now - what was wrong in your app:

  1. Define the proper holder for your accounts i.e. HashMap that will hold the information about all accounts and will be able to find them by accountNumber.

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

  2. This one should be inside your while loop, as you want your user to do multiple tasks. You could ommit the println's but then the user would have to go back to the top of the screen to see the options.

    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. You shouldn't compare Strings using '==' operator as it may not return expected value. Take a look at: How do I compare strings in Java? or Java == vs equals() confusion. For safty use Objects equals instead, ie:

    choice.equals("ne")
    

  4. There was no place where you created the account:

    Account newAccount = new Account(newAccountNumber, initialBalance);
    

  5. You didn't use if-else, just if's. It should look more like that (why to check if the choice is 'wi' if it was already found to be 'ne'):

    if(choice.equals("ne")) {
        //doStuff
    } else if choice.equals("se") {
        //doStuff
    } //and so on.
    

  6. If your using Java version >= 7 then instead of if-else you can use switch to compare Strings.

  7. There was no notification of the wrong option:

    } else {
        System.out.println("Wrong option chosen.");
    }
    

  8. You didn't close your Scanner object. This really doesn't matter here, as it's in main method and will close with it, but it's a matter of good habbits to always close your streams, data sources etc when done using it:

    input.close(); 
    

So the whole code can look like this:

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

There still is much to improve, i.e. input validation - but this should work for the begining.

这篇关于数组和银行账户的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆