簡體   English   中英

從另一個類調用方法-錯誤:類Customer中的構造方法Customer無法應用於給定類型

[英]Calling method from another class - Error: constructor Customer in class Customer cannot be applied to given types

我正在嘗試調整Store類的richestCustomer()方法中的代碼以利用hasMoreMoneyThan()方法,但是我一直收到錯誤消息:“類Customer中的構造方法Customer無法應用於給定類型”

有誰知道如何解決這一問題?

客戶分類:

public class Customer {
  private String name;
  private int age;
  private float money;
  public Customer(String n, int a, float m) {
    name = n;
    age = a;
    money = m;
  }
  public String toString() {
    return "Customer " + name + ": a " + age + " year old with $" + money;
  }

  public String getName(){
    return name;
  }
  public int getAge(){
    return age;
  }

  public boolean hasMoreMoneyThan(Customer c){
    if(this.money > c.money){
      return true;
    }else{
      return false;
    }
  }
}

商店分類:

public class Store {
  public static final int MAX_CUSTOMERS = 500;
  String name;
  Customer[] customers;
  int customerCount;
  public Store(String n) {
    name = n;
    customers = new Customer[MAX_CUSTOMERS];
    customerCount = 0;
  }
  public void addCustomer(Customer c) {
    if (customerCount < MAX_CUSTOMERS)
      customers[customerCount++] = c;
  }
  public void listCustomers() {
    for (int i=0; i<customerCount; i++)
      System.out.println(customers[i]);
  }
  public int averageCustomerAge(){
    int sum = 0;
    for(int i = 0; i < customerCount; i++){
      sum += customers[i].getAge();
    }
    int averageAge = sum/customerCount;
    return averageAge;
  }

  public Customer richestCustomer(){
    Customer richest = new Customer();
    for(int i = 0; i < customerCount; i++){
      if(customers[i].hasMoreMoneyThan(richest)){
        richest = customers[i];
      }
    }
    return richest;
  }

當您在類中定義自定義構造函數時,默認情況下該類中不再包含默認構造函數,則需要顯式定義它。 在客戶類中定義默認構造函數,或使用通過傳遞默認值定義的構造函數。

Customer richest = new Customer(null, 0, 0f);

您方法的一個更好的實現方法是假定第一個客戶為最富有的客戶,然后與其余客戶進行比較:

public Customer richestCustomer(){
    if(customerCount <= 0) {
        return null; // or throw exception
    }
    Customer richest = customers[0];
    for(int i = 1; i < customerCount; i++){
        if(customers[i].hasMoreMoneyThan(richest)){
            richest = customers[i];
        }
    }
    return richest;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM