只能迭代一个数组

时间:2014-08-26 16:56:05

标签: java

enum Bags {
    SMALL(10832, 10000000), MEDIUM(10833, 100000000), HUGE(10834, 100000000), HEFTY(
            10835, 2147000000);

    public int id, mAmount;

    Bags(int id, int mAmount) {
        this.id = id;
        this.mAmount = mAmount;
    }

    public int getId() {
        return id;
    }

    public int getMoneyAmount() {
        return mAmount;
    }

    public Bags getBagConfig(int index) {

        for (Bags bag : Bags.values()) {

            for (int bagId : bag.getId()) {

                if (bagId == index) {
                    return bag;
                }

            }

        }
        return null;
    }
}

public static void init(final Client c, final int itemUsed,
        final int useWith) {
    if (itemUsed == 7 && useWith == 1) {
        c.getItems().deleteItem(7, 1);
    }
    c.eventContainer.addEvent(new CycleEvent(5) {

        public void execute() {
            c.getItems().addItem(1, 3);
        }
    });
}

它说:Can only iterate over an array or an instance of java.lang.Iterable
有人可以帮我解决这个问题吗?

我不知道如何修复此错误,错误在for循环中。

2 个答案:

答案 0 :(得分:4)

错误消息是正确的,这是

for (Bags bag : Bags.values()) {
  for (int bagId : bag.getId()) { // <-- HERE!
    if (bagId == index) {
      return bag;
    }
  }
}

不合法。我想你想要

for (Bags bag : Bags.values()) {
  if (bag.getId() == index) {
    return bag;
  }
}

因为getId()会返回一个int

答案 1 :(得分:0)

替换此代码:

for (int bagId : bag.getId()) {
    if (bagId == index) {
         return bag;
    }
}

if (bag.getId() == index) {
     return bag;
}