【问题标题】:Undefined method for a type类型的未定义方法
【发布时间】:2014-01-04 15:48:20
【问题描述】:

我正在尝试实现一个程序,该程序计算从硬币列表中获取特定数量的可能性的数量,但我得到了错误

在 coin(s-1) 的这一行中,对于 Money 类型的方法 coin(int) 未定义:
返回梳子(s-1,数量,硬币)+梳子(s,数量-硬币(s-1),硬币);

这是我的代码

class List<T> {
T head;
List<T> tail;

List(T head, List<T> tail) {
    this.head = head;
    this.tail = tail;
}
static <U> List<U> node(U head, List<U> tail) {
    return new List<U>(head, tail);
}
}

public class Money{

//should count number of combinations to get change amount amount

static int comb(int s, int amount, List<Integer> coins) { 
         if (amount == 0 ) 
                return 1;

     else if (amount < 0) 
            return 0;

     return comb(s-1, amount, coins) + comb(s, amount-coins(s-1), coins); 

有什么问题?

【问题讨论】:

  • 你为什么使用你自己的List类? 确切地 将其命名为 Java's List interface 会让人感到困惑,而且它似乎比普通的 ArrayListLinkedList 没有任何优势。

标签: java recursion


【解决方案1】:

我认为您的问题是您尝试访问列表元素的方式。

return comb(s-1, amount, coins) + comb(s, amount-coins(s-1), coins); 

应该是:

return comb(s-1, amount, coins) + comb(s, amount-coins.get(s-1), coins);

Coins 是一个列表,因此您应该使用coins.get(index) 来访问单个元素。 Here 是有关 Java 列表的更多信息。

【讨论】:

  • 谢谢,我已经试过了。但它不起作用并给我错误“方法get(int)对于类型List是未定义的”......还有其他想法吗? :)
  • @user3157144 因为你的 List 实现没有get(int) 方法。 connor 可能假设您使用的是标准 Java List 接口,该接口确实具有get(int) 方法。
  • 好的,谢谢!有没有一种简单的方法来实现我自己的 get(int) 方法?
  • 没错。当我认为我发现了错误时,我没有注意第一部分。您可以使用标准列表或将 get() 功能添加到您的自定义列表中
  • 为什么需要实现自己的列表?
猜你喜欢
  • 1970-01-01
  • 2022-12-23
  • 2016-06-07
  • 2021-06-19
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多