Blackvein
Blackvein

Reputation: 558

Java: For statement inside of Do statement?

This is related to my other question 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);
    }
  }

When this method runs, System does not print anything out. Through a series of print tests, I have determined that it goes inside of the do-while loop. I'm not sure if it goes inside the for loop though.

Upvotes: 1

Views: 124

Answers (2)

Dave Newton
Dave Newton

Reputation: 160191

Start from here instead:

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

Upvotes: 2

Lionel
Lionel

Reputation: 428

Your items might contain something, but your weapons may be empty. Your code doesn't seem to do anything in this case.

Upvotes: 1

Related Questions