Java:对于Do语句中的语句?

时间:2011-10-20 00:02:38

标签: java for-loop do-while

这与我的其他问题here

有关
  public void equipWep(String weapontoequip){
    if(items.isEmpty() && weapons.isEmpty()){
       System.out.println("You are not carrying anything.");
    } else {
      boolean weaponcheck_finished = false;
      do {
        for (String s : weapons) {
          if (s.contains(weapontoequip)) {
            System.out.println("You equip " + s + ".");
            weaponcheck_finished = true;
          } else {
            System.out.println("You cannot equip \"" + weapontoequip + "\", or you do not have it.");
            weaponcheck_finished = true;
          }
        }
      }while(weaponcheck_finished == false);
    }
  }

此方法运行时,系统不会打印任何内容。通过一系列的打印测试,我确定它进入了do-while循环。我不确定它是否进入for循环。

2 个答案:

答案 0 :(得分:2)

从这里开始:

public void equipWithWeapon(String weapon) {
    if (items.isEmpty() && weapons.isEmpty()) {
        System.out.println("You are not carrying anything.");
        return;
    }

    String foundWeapon = findWeapon(weapon);
    if (foundWeapon == null) {
        System.out.println("You cannot equip \"" + weapon + "\", or you do not have it.");
    }

    System.out.println("You equip " + foundWeapon + ".");
}

private String findWeapon(String weapon) {
    for (String s : weapons) {
        if (s.contains(weapon)) {
            return s;
        }
    }
    return null;
}

答案 1 :(得分:1)

您的物品可能包含某些物品,但您的武器可能是空的。在这种情况下,您的代码似乎没有做任何事情。