我的方法只运行一次并且map.get()影响所有条目时运行两次

So, I'm working on a project with a loop (while (true) { //do stuff) and I have values stored in a map (only 2 entries).

第一个问题:方法执行两次(我认为这是map部分的问题) 第二个问题:map.get(key)正在所有键上执行,而不仅仅是指定的键。

在我的主要班级:

private static void gameLoop() {
        while (true) {

            whatToDo();
            shelter.tick();
            showPets();   //when it shows pets here, the .feed() and .tick() have been executed twice
        }
    }

    private static void whatToDo() {
        System.out.println("What would you like to do?");
        System.out.println("\t 1: Feed");

        int response = input.nextInt();
        input.nextLine();

        switch (response) {
            case 1: //I have more options and more cases
                feedOptions();
                break;
        }
    }

    private static void feedOptions() {
        System.out.println("Enter pet name or \"all\" to feed all:");
        showPetNames(); //This displays the 2 pets names from my map. Pet names are keys, pet objects are values
        String response = input.nextLine();

        if (response.toLowerCase().equals("all")) {
            shelter.feedAllPets();  //Shelter is my object from Shelter class, it houses my map
        } else {
            shelter.feedPet(response);  //I intend to feed only 1 pet. response = pet name
        }
    }

在我的庇护班上:

private Map<String, VirtualPet> pets = new HashMap<>();

public void feedAllPets() {
        for (VirtualPet value : pets.values())
            value.feed();     //this executes twice per each pet
    }

    public void feedPet(String name) {
        pets.get(name).feed();  //supposed to feed 1 pet, but it feeds all pets and runs twice
    }

    public void tick() {
        for (VirtualPet value : pets.values())
            value.tick();
    }
评论