2014-12-17 3 views
3

Я создаю проект, который позволяет пользователю делать то, что вы обычно можете использовать в банке (создавать, удалять счета, снимать, депонировать, печатать транзакции).Проблема с присвоением переменной

Моя проблема печать сделка. Я могу печатать что-то, но неправильные значения появляются. Например, при создании банковского счета вам нужно будет ввести начальный баланс, который был (5,00). Когда я печатаю транзакцию, ничего не возникает. Таким образом, я ввожу деньги на один и тот же счет (10.00), когда я печатаю, (5.00) от него появляется и появляется (10.00) в транзакции. Однако, когда я просматриваю баланс счета, все это добавляет к тому, что он показывает.

Может ли кто-нибудь помочь мне устранить неполадки и устранить проблему?

package mainsample; 
import java.util.*; 

public class Main { 


    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; 
    int selection; 

    while(true) { 
     System.out.println(""); 
     System.out.println("######## MENU ########"); 
     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");  
     System.out.println("######################"); 
     System.out.println("Please choose one of the following: "); 
     selection = scan.nextInt(); 

     switch (selection) { 

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

     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: "); 
      int accountNo = scan.nextInt(); 
      bankAccount = bank.getAccount(accountNo); // get bankAccount from account id 
      bank.removeAccounts(bankProcess.removeAccount(bank.getAccounts(), bankAccount)); 
      System.out.println("Account has been deleted."); 
     break; 

     case 4: 
      System.out.println("[4] Deposit has been selected"); 
      System.out.println("Enter account ID: "); 
      int accountNumber = scan.nextInt(); 

      System.out.println("Enter deposit amount: "); 
      double depositAmount = scan.nextDouble();   

      transactionProcess.deposit(bankAccount, depositAmount); 


      break; 

     case 5: 
      System.out.println("[5] Withdraw has been selected"); 
      System.out.println("Enter account ID: "); 
      int accountNu = scan.nextInt(); 

      System.out.println("Enter withdraw amount: "); 
      double withdrawAmount = scan.nextDouble();   

      transactionProcess.withdraw (bankAccount, withdrawAmount);   

      break;   


     case 6: 
      System.out.println("[6] Print Transaction has been selected"); 
      System.out.println("Enter account ID: "); 
      int accountN = scan.nextInt(); 
      bankAccount = bank.getAccount(accountN); 
      for (Transaction transaction: bankAccount.getTransactions()) { 
      // print transaction information ... 
      System.out.println(transaction.toString()); 

} 



      break; 






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

     } 

    } 
    } 
} 
package mainsample; 

/** 
* 
* @author Khalid 
*/ 
public class Transaction { 


    private String transactionType; 
    private double transactionAmount; 
    private int transactionDate; 


    public Transaction() {} 

    public Transaction(String transactionType, double transactionAmount, int transactionDate) { 

    this.transactionType = transactionType; 
    this.transactionAmount = transactionAmount; 
    this.transactionDate = transactionDate; 

    } 

    public int getTransactionDate() { 
     return transactionDate; 
    } 

    public void setTransactionDate (int transactionDate) { 
     this.transactionDate = transactionDate; 
    } 


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

    //Override the toString() method of String ? 
    public String toString() { 
    return "\nTransaction Amount : "+ this.transactionAmount + 
      "\nTransaction Type : " + this.transactionType + 
      "\nTransaction Date: " + this.transactionDate; 

    } 

} 
package mainsample; 
/** 
* 
* @author Khalid 
*/ 
public class TransactionProcess { 

    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("Deposit", currentBalance, (int) depositAmount); 

    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 

     bankAccount.addTransaction(transaction); // adds a transaction to the bank account 
     System.out.println(depositAmount + " has been deposited."); 
    } 

    } 

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

    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);   
     bankAccount.addTransaction(transaction); // adds a transaction to the bank account 
     System.out.println(withdrawAmount + " has been withdrawed,"); 
     } 
    } 
    } 
} 

/* 
 
* To change this license header, choose License Headers in Project Properties. 
 
* To change this template file, choose Tools | Templates 
 
* and open the template in the editor. 
 
*/ 
 
package mainsample; 
 
import java.util.*; 
 
/** 
 
* 
 
* @author Khalid 
 
*/ 
 
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 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 
 
    } 
 

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

 
    
 
}

package mainsample; 
 
import java.util.*; 
 
/** 
 
* 
 
* @author Khalid 
 
*/ 
 
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 BankAccount getAccount(Integer accountNumber){ 
 
    return bankAccounts.get(accountNumber); 
 
    } 
 

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

 
    
 
}

package mainsample; 
 
import java.util.*; 
 
/** 
 
* 
 
* @author Khalid 
 
*/ 
 
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; 
 
     
 
    } 
 
    
 

 
    
 

 
}

+1

Где Ваш - банковский счет класс? – SMA

+0

Возможно ли, что вы не получаете фактическое значение с помощью «bankAccount = bank.getAccount (accountNo) », из случаев 4 и 5? –

+0

@almasshaikh вверх –

ответ

-1

Вы не называя:

ВагЛАссоипЬ = bank.getAccount (AccountN);

указать банковский счет в пункте 4 (депозит) и 5 ​​(снять).

FIX:

case 4: 
     System.out.println("[4] Deposit has been selected"); 
     System.out.println("Enter account ID: "); 
     int accountNumber = scan.nextInt(); 

     System.out.println("Enter deposit amount: "); 
     double depositAmount = scan.nextDouble();   
    ---> bankAccount = bank.getAccount(accountN); 
     transactionProcess.deposit(bankAccount, depositAmount); 


     break; 

    case 5: 
     System.out.println("[5] Withdraw has been selected"); 
     System.out.println("Enter account ID: "); 
     int accountNu = scan.nextInt(); 

     System.out.println("Enter withdraw amount: "); 
     double withdrawAmount = scan.nextDouble();   
    ---> bankAccount = bank.getAccount(accountN); 
     transactionProcess.withdraw (bankAccount, withdrawAmount);   

     break; 
+0

Я не понимаю, что вы пытаетесь сказать. Работают пункты 4 и 5. Я могу проверить его, посмотрев текущий баланс. Это транзакции, которые не работают должным образом (печать) –

+0

@razcor Это уже упоминалось в комментариях. –

+0

@andresoviedo, я тестирую его заявку и набрав ответ, не вижу твой комментарий – razcor

0

Сначала вы сделали ошибку в транзакции constrctor

public Transaction(String transactionType, double transactionAmount, int transactionDate) { 

     this.transactionType = transactionType; 
     this.transactionAmount = transactionAmount; 
     this.transactionDate = transactionDate; 

    } 

Но вы назначаете как этот

Transaction transaction = new Transaction("Deposit", currentBalance, (int) depositAmount); 

порядка ваш аргумент совершенно неправильно здесь. почему вы назначаете сумму депозита вместо даты. это должно быть как

Transaction transaction = new Transaction("Deposit", (int) depositAmount,date); 

Также при создании новой учетной записи вы не добавляете эту сумму в транзакцию. Вы создаете новую учетную запись, используя этот код

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

Но вы не добавили эту начальную сумму в транзакцию. он должен быть включен в конструктор bankAccount

Transaction transaction = new Transaction("Deposit", 0, (int) depositAmount); 

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 

    bankAccount.addTransaction(transaction); // adds a transaction to the bank account 
    System.out.println(depositAmount + " has been deposited."); 
} 

Теперь я получаю правильный вывод. когда вы создаете учетную запись, которую вы задали. когда вы делаете депозит, вы не задали дату.Таким образом, вы не можете назначить дату операции для внесения депозита или снятия средств

Transaction Amount : 5.0 Transaction Type : Deposit Transaction Date: 4 

Transaction Amount : 10.0 Transaction Type : Deposit Transaction Date: 10 
+0

Почему вы изменили currentBalance на 0? –

+0

, когда вы создаете новую учетную запись, текущий баланс должен быть равен 0. Также вы допустили некоторые ошибки в транзакционном процессе constrctor.check it – Burusothman

Смежные вопросы