【问题标题】:Add & Print from List using Scanner使用扫描仪从列表中添加和打印
【发布时间】:2014-12-14 09:53:51
【问题描述】:

我正在创建一个项目,允许用户创建、删除或显示银行账户以及存款、取款或打印交易。

当用户提供账户 ID 时,我不知道如何使用扫描仪进行存款、取款、打印交易。

主要:

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    BankProcess bankProcess = new BankProcess();
    TransactionProcess transactionProcess = new TransactionProcess();

    Bank bank = new Bank();
    BankAccount bankAccount = new BankAccount();

    int input = 0;
    int selection = 0;

    while (input == 0) {
      System.out.println("");
      System.out.println("Please choose one of the following: ");
      System.out.println("[1] Create an account");
      System.out.println("[2] Print all existing accounts");
      System.out.println("[3] Delete an account");
      System.out.println("[4] Deposit");
      System.out.println("[5] Withdraw");
      System.out.println("[6] Print transactions");
      System.out.println("[0] Exit");
      selection = scan.nextInt();

      switch (selection) {

        case 0:
          System.out.println("Exit Successful");
          System.exit(0);

        case 1:
          System.out.println("'[1] Create an account' has been selected.");
          System.out.print("Account Id: ");
          int accountId = scan.nextInt();
          scan.nextLine();

          System.out.print("Holder Name: ");
          String holderName = scan.nextLine();

          System.out.print("Holder Address: ");
          String holderAddress = scan.nextLine();

          System.out.print("Opening Balance: ");
          double openingBalance = scan.nextDouble();

          System.out.print("Open Date: ");
          String openDate = scan.next();

          bankAccount = new BankAccount(accountId, holderName, openingBalance, holderAddress, openDate);
          bank.setAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));

          System.out.println("Successfully Added.");
          break;

        case 2:
          System.out.println("'[2] Display all existing accounts' has been selected");
          System.out.println("-----------------------------------------------------");
          bank.getAccounts().forEach((i, b) - > System.out.println(b));
          System.out.println("-----------------------------------------------------");
          break;

        case 3:
          System.out.println("[3] Delete an account has been selected");
          System.out.println("Enter the account ID: ");
          bank.removeAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));
          break;

        case 4:
          System.out.println("[4] Deposit has been selected");

          break;

        case 5:
          System.out.println("[5] Withdraw has been selected");

          break;

        case 6:
          System.out.println("[6] Print Transaction has been selected");

          break;

        default:
          System.out.println("Your choice was not valid!");

      }
    }
  }

类银行

public class Bank {

  private TreeMap < Integer, BankAccount > bankAccounts = new TreeMap < Integer, BankAccount > ();

  public TreeMap < Integer, BankAccount > getAccounts() {
    return bankAccounts;
  }
  public void setAccounts(TreeMap < Integer, BankAccount > accounts) {
    this.bankAccounts = accounts;
  }

  public void removeAccounts(TreeMap < Integer, BankAccount > accounts) {
    this.bankAccounts = accounts;
  }
}

类BankProcess

public class BankProcess {
  // return the  Updated list of BankAccounts
  public TreeMap < Integer, BankAccount > openNewAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
    //Get the List of existing bank Accounts then add the new BankAccount to it.
    bankAccounts.put(bankAccount.getAccountId(), bankAccount);
    return bankAccounts;
  }

  public TreeMap < Integer, BankAccount > removeAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
    bankAccounts.remove(bankAccount.getAccountId(), bankAccount);
    return bankAccounts;
  }
}

类 BankAccount

public class BankAccount {
  private int accountId;
  private String holderName;
  private String holderAddress;
  private String openDate;
  private double currentBalance;

  private List < Transaction > transactions = new ArrayList < Transaction > ();

  //Provide Blank Constructor
  public BankAccount() {}

  //Constructor with an arguments.
  public BankAccount(int accountNum, String holderNam, double currentBalance, String holderAdd, String openDate) {
    this.accountId = accountNum;
    this.holderName = holderNam;
    this.holderAddress = holderAdd;
    this.openDate = openDate;
    this.currentBalance = currentBalance;
  }

  // Always Provide Setter and Getters
  public int getAccountId() {
    return accountId;
  }
  public void setAccountId(int accountId) {
    this.accountId = accountId;
  }
  public String getHolderName() {
    return holderName;
  }
  public void setHolderName(String holderName) {
    this.holderName = holderName;
  }
  public String getHolderAddress() {
    return holderAddress;
  }
  public void setHolderAddress(String holderAddress) {
    this.holderAddress = holderAddress;
  }
  public String getOpenDate() {
    return openDate;
  }
  public void setOpenDate(String openDate) {
    this.openDate = openDate;
  }
  public double getCurrentBalance() {
    return currentBalance;
  }
  public void setCurrentBalance(double currentBalance) {
    this.currentBalance = currentBalance;
  }

  public List < Transaction > getTransactions() {
    return transactions;
  }

  public void setTransactions(List < Transaction > transactions) {
    this.transactions = transactions;
  }

  public String toString() {
    return "\nAccount number: " + accountId + "\nHolder's name: " + holderName + "\nHolder's address: " + holderAddress + "\nOpen Date: " + openDate + "\nCurrent balance: " + currentBalance;
  }
}

类交易

public class Transaction {
  private int transactionId;
  private String transactionType;
  private double transactionAmount;
  private double moneyBeforeTransaction;
  private double moneyAfterTransaction;

  public Transaction() {}

  public Transaction(int transactionId, String transactionType, double transactionAmount, double moneyBeforeTransaction) {
    this.transactionId = transactionId;
    this.transactionType = transactionType;
    this.transactionAmount = transactionAmount;
    this.moneyBeforeTransaction = moneyBeforeTransaction;
  }

  public int getTransactionId() {
    return transactionId;
  }

  public void setTransactionId(int transactionId) {
    this.transactionId = transactionId;
  }

  public String getTransactionType() {
    return transactionType;
  }

  public void setTransactionType(String transactionType) {
    this.transactionType = transactionType;
  }

  public double getTransactionAmount() {
    return transactionAmount;
  }

  public void setTransactionAmount(double transactionAmount) {
    this.transactionAmount = transactionAmount;
  }

  public double getMoneyBeforeTransaction() {
    return moneyBeforeTransaction;
  }

  public void setMoneyBeforeTransaction(double moneyBeforeTransaction) {
    this.moneyBeforeTransaction = moneyBeforeTransaction;
  }

  public double getMoneyAfterTransaction() {
    return moneyAfterTransaction;
  }

  public void setMoneyAfterTransaction(double moneyAfterTransaction) {
    this.moneyAfterTransaction = moneyAfterTransaction;
  }

  //Override the toString() method of String ? 
  public String toString() {
    return "Transaction ID : " + this.transactionId +
      " Transaction Type : " + this.transactionType +
      " Transaction Amount : " + this.transactionAmount +
      " Money Before Transaction : " + this.moneyBeforeTransaction +
      " Money After Transaction : " + this.moneyAfterTransaction;
  }

}

类 TransactionProcess

public class TransactionProcess {

  //Always Provide another class for process.
  //Pass the bankAccount of the user
  public void deposit(BankAccount bankAccount, double depositAmount) {
    //Get the CurrentBalance
    double currentBalance = bankAccount.getCurrentBalance();

    //First Argument : set the Id of transaction
    //Second Argument : set the Type of Transaction
    //Third Argument : set the TransactionAmount 
    //Fourth Argument : set the Balance Before the transaction (for record purposes)
    Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Deposit", depositAmount, currentBalance);

    if (depositAmount <= 0) {
      System.out.println("Amount to be deposited should be positive");
    } else {
      //Set the updated or transacted balance of bankAccount.
      bankAccount.setCurrentBalance(currentBalance + depositAmount);
      //then set the MoneyAfterTransaction
      transaction.setMoneyAfterTransaction(bankAccount.getCurrentBalance());
      //after the transaction add it to the list of Transaction of bankAccount
      bankAccount.getTransactions().add(transaction);
    }

  }

  // Explanation same as above
  public void withdraw(BankAccount bankAccount, double withdrawAmount) {
    double currentBalance = bankAccount.getCurrentBalance();
    Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Withdraw", withdrawAmount, currentBalance);

    if (withdrawAmount <= 0) {
      System.out.println("Amount to be withdrawn should be positive");
    } else {
      if (currentBalance < withdrawAmount) {
        System.out.println("Insufficient balance");
      } else {
        bankAccount.setCurrentBalance(currentBalance - withdrawAmount);
        transaction.setMoneyAfterTransaction(bankAccount.getCurrentBalance());
        bankAccount.getTransactions().add(transaction);
      }
    }
  }
}

【问题讨论】:

  • 您需要添加更多细节,或许还需要减少代码量。不清楚你在问什么。
  • 不要粘贴整个项目,而是粘贴相关代码和您遇到的异常或错误。
  • 我在项目的交易部分遇到问题。如何在扫描仪中创建交易(存款、取款和打印所有交易)。用户将输入一个已创建的accountid,并将存入或提取金额。我不知道如何在 mainsample 类中进行布局。
  • 这是一段代码,但我怀疑它只运行一次是否正确? while (input == 0) 有问题。您确实将其初始化为 0,但随后您将 0 作为退出 #,在循环之前,我也没有看到您确定是这种情况的任何地方(可能错过了?)。因此,似乎继续该过程的唯一方法是选择退出,这显然“不计算”。
  • 查看 main() 中的代码。您的 while 条件不起作用。如果用户第一次输入 0,则逐行跟随您的代码,如果用户第一次没有输入 0,则再次跟随它。您会看到用户将能够退出前者,并且如果在后者中输入 0,则用户将无法继续执行其他操作。 IOW,你有一个逻辑悖论;可以这么说。

标签: java


【解决方案1】:

depositwithdraw 等操作的工作方式几乎相同,所以现在让我们专注于 deposit

您已经有相应的开关盒:

case 4: {
     // deposit
     break;
}

(顺便说一句:大括号{}在这里不是必须的,它们只是帮助隔离代码,以便于阅读)

无论如何;要在银行账户上存钱,您首先需要帐号,然后您需要从银行获取账户

 case 4: {
     int accountNumber =  scan.nextInt();  // user types account number
     TreeMap <Integer, BankAccount> bankAccounts = bank.getAccounts();  // bank returns all accounts (this is quite an insecure operation, it would be better to add a method to the bank class that returns only one account when passing the accountNumber
     BankAccount bankAccount = bankAccounts.get(accountNumber);
     break;
}

在这里使用bank.getAccounts 方法不是一个好的设计,因为该方法将返回银行的所有 帐户。最好在您的类Bank 中有一个返回单个帐户的方法。

public class Bank{
  // ...
  public BankAccount getAccount(Integer accountNumber){
     return bankAccounts.get(accountNumber);
  }
}

因为这会将检索一个帐户的逻辑封装到Bank 类。在那里您还可以添加一些错误处理逻辑,例如当帐号无效时。

因此,此时您拥有用户的帐户,并且您知道该用户想要存入一些钱。你只需要问他想存多少钱。再次使用扫描仪让用户输入金额。

现在您已经有了BankAccount 以及制作Transaction 或更好的TransactionProcess 所需的金额

 TransactionProcess transactionProcess = new TransactionProcess();  // use the standard constructor to create an empty transactionProcess
 transactionProcess.deposit(bankAccount, amount);

如果我正确理解您的程序,deposit 方法将已经使用用户的 BankAccount 并在为该帐户创建交易时添加资金。我对么?那么你实际上已经在这里完成了。

switch-chase 4 的代码放在一起,如果可行,请使用类似的逻辑来实现withdraw

我希望这会有所帮助!

// 编辑 // 回答你的其他问题,这就是我的想法:

在你的 BankAccount 类中添加一个类似这样的方法:

public void addTransaction(Transaction transaction){
   if(transactions.size() >= 6){  // test if the list has 6 or more transactions saved 
      transactions.remove(0);     // if so, then remove the first (it's the oldest)
   }
   transactions.add(transaction); // the new transaction is always added, no matter how many other transactions there are already in the list
}

这只是一个示例,但我认为您应该能够像这样控制每个银行帐户的交易量。此外,您现在可以简化调用:查看TransactionProcess 类中deposit 方法的最后一行。你打电话给你

bankAccount.getTransactions().add(transaction);  // takes the bank account, retrieves the list of transactions from the bank account and adds a transaction to the list

使用新方法addTransaction,您现在可以这样写:

bankAccount.addTransaction(transaction);    // adds a transaction to the bank account

更干净,你不觉得吗?现在您可以将管理和添加事务的所有逻辑放入该新方法中:)

【讨论】:

  • 我理解你在这里告诉我的概念,但是当我尝试实现它时,出现类似于案例 4 的错误,它说变量已经定义。我的 transaction 和 transactionprocess 类的布局是否正确?
  • 我很高兴听到这个消息!
  • 对于交易,我只需要存储最后 6 笔交易并打印出来。我需要为此彻底改变我的交易流程吗?
  • 不,你不必改变太多。现在您添加这样的事务:bankAccount.getTransactions().add(transaction);。这与我之前告诉过你的getAccount() 相同 - 不要只为添加一项而获取整个列表。在您的类BankAccount 中创建一个新方法,用于添加一个新事务。像这样的东西:addTransaction(transaction)。在该方法中,您将交易添加到列表中。要限制列表中的交易数量,您可以在添加新交易之前删除第一个交易 `if(transactions.size()>=6){transactions.remove(0);}
  • 我完全理解最后的代码。但对其他代码应该去哪里感到困惑。
猜你喜欢
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多