2014-12-17 5 views
2

H. Я получаю сообщение об ошибке в этом фрагменте кода и не знаю, что делать. Может ли кто-нибудь сказать мне, что может быть проблемой и как ее решить.Ошибка 'Constructor not found ....'

Ошибка: Нет подходящий конструктор найдено для транзакции (междунар, String, двойной, двойной (

код не указывается:

Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Deposit", depositAmount, currentBalance); 
/* 
* 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; 
/** 
* 
* @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(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 

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

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


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


    public Transaction() {} 

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

    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 " Transaction Amount : "+ this.transactionAmount + 
      " Transaction Type : " + this.transactionType + 
      " Transaction Date: " + this.transactionDate; 

    } 

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


} 
+0

Это не конструктор, который принимает четыре аргумента. Единственный конструктор, который вы дали, содержит три аргумента. – Jared

ответ

6

Вы звоните Transaction(bankAccount.getTransactions().size(), "Deposit", depositAmount, currentBalance); Этот означает, что вы проходите мимо four arguments.

Но вы создали Transaction(String transactionType, int transactionDate, double transactionAmount) который принимает только three arguments.

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

Если вы хотите три аргумента:

измените следующую строку кода в программе:

Transaction transaction = new Transaction(bankAccount.getTransactions().size(), depositAmount, currentBalance);

В соответствии мой комментарий ниже:

You need to verify the data types of all the parameters you are passing. It certainly means String is needed and you are passing an int. And I doubt if it is regarding the bankAccount.getTransactions().size() parameter as size() is supposed to give you int value but in your constructor you need String transactionType String value. You will have to change the types as per your need. And a hint to convert int value to String you can use String.valueOf();

+0

Хорошо. Понять это. Как это можно исправить? Мне нужны только три аргумента. –

+0

Я все еще получаю сообщение об ошибке с тем же кодом. Несовместимые типы: int не может быть преобразован в строку. –

+1

@InsideFootball Вам необходимо проверить типы данных всех параметров, которые вы передаете. Это, конечно, означает, что String необходим, и вы передаете int. И я сомневаюсь, что он относится к параметру 'bankAccount.getTransactions(). Size()', поскольку 'size()' должен указывать вам значение int, но в вашем конструкторе вам нужно значение String transactionType' String. Вам придется изменить типы в соответствии с вашими потребностями. И подсказка для преобразования значения int в String вы можете использовать 'String.valueOf();' – gprathour

3

Конструктора у вас есть

Transaction(String, int, double);

Но вы пытаетесь дать

Transaction(int, String, int, double); 

Измените следующие,

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

вместо

Transaction transaction = new Transaction(bankAccount.getTransactions().size(), "Deposit", depositAmount, currentBalance); 

Заменить класс транзакции следующим.

public class Transaction { 


     private String transactionType; 
     private double transactionAmount; 
     private double balanceAmount; 
     private Date transactionDate; 


     public Transaction() {} 

     public Transaction(String transactionType, Date transactionDate, double transactionAmount, double balanceAmount) { 

     this.transactionType = transactionType; 
     this.transactionAmount = transactionAmount; 
     this.transactionDate = transactionDate; 
     this.balanceAmount = balanceAmount; 
    } 

     public Transaction(String transactionType, double transactionAmount, double balanceAmount) { 

    this.transactionType = transactionType; 
    this.transactionAmount = transactionAmount; 
    this.balanceAmount = balanceAmount; 

    } 

     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 " Transaction Amount : "+ this.transactionAmount + 
       " Transaction Type : " + this.transactionType + 
       " Balance Amount : " + this.balanceAmount + 
       " Transaction Date: " + this.transactionDate; 

     } 

     /** 
     * @return the balanceAmount 
     */ 
     public double getBalanceAmount() 
     { 
      return balanceAmount; 
     } 

     /** 
     * @param balanceAmount the balanceAmount to set 
     */ 
     public void setBalanceAmount(double balanceAmount) 
     { 
      this.balanceAmount = balanceAmount; 
     } 

    } 

Метод печати Transaction

public void printTransaction(int accountNumberId) 
    { 
     List<Transaction> transactionList = getTransactions(accountNumberId); // this getTransactions() you have to create and fetch all the transaction listed by the holderName 

     for(Transaction transaction : transactionList) 
     { 
      System.out.println("Transaction Amount : "+transaction.getTransactionAmount()); 
      System.out.println("Transaction Date : "+transaction.getTransactionDate()); 
      System.out.println("Transaction Type : "+transaction.getTransactionType()); 
     } 
    } 
+0

Комментарии не предназначены для расширенного обсуждения; этот разговор был [перемещен в чат] (http://chat.stackoverflow.com/rooms/67126/discussion-on-answer-by-newuser-constructor-not-found-error). – Taryn

0

Причина ошибки заключается в том, что вы следующий конструктор класса транзакций:

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

И вы передаете 4 аргумент, который не суммируется и не соответствует ни одному из них , Вместо этого попробуйте:

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

Как у банковской учетной записи есть текущие данные о балласте, вам не нужно их передавать. Также нет необходимости передавать размер транзакции в вашем случае, так как я не вижу в вашем коде какой-либо цели.