java My方法运行了两次,而它们应该只运行一次并映射。get()正在影响所有条目
因此,我正在处理一个带有循环(while (true) { //do stuff
)的项目,并且我在映射中存储了值(只有2个条目)
第一个问题:方法执行两次(我认为这是映射部分的问题)。虚拟机。tick和VirtualPet。每个循环执行两次feed方法
第二期:地图。get(键)在所有键上执行,而不仅仅是在指定的键上
在我的主课上:
private static VirtualPetShelter shelter = new VirtualPetShelter();
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
generatePets();
gameLoop();
}
private static void showPets() {
shelter.showPets();
}
private static void generatePets() {
VirtualPet pet1 = new VirtualPet();
VirtualPet pet2 = new VirtualPet();
shelter.addPet("Max", pet1);
shelter.addPet("Skippy", pet1);
}
private static void gameLoop() {
while (true) {
whatToDo();
shelter.tick();
showPets();
}
}
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:
feedOptions();
break;
}
}
private static void feedOptions() {
System.out.println("Enter pet name or \"all\" to feed all:");
showPetNames();
String response = input.nextLine();
if (response.toLowerCase().equals("all")) {
shelter.feedAllPets();
} else {
shelter.feedPet(response);
}
}
在我的庇护班:
private Map<String, VirtualPet> pets = new HashMap<>();
public VirtualPetShelter() {
}
public void addPet(String name, VirtualPet pet) {
pets.put(name, pet);
}
public void showPets() {
for (Map.Entry<String, VirtualPet> entry : pets.entrySet())
System.out.println("\t" + entry.getKey() + "\n" +
"\t\tHunger: " + entry.getValue().getHunger());
}
public void showPetNames() {
for (Map.Entry<String, VirtualPet> entry : pets.entrySet())
System.out.println(entry.getKey());
}
public void feedAllPets() {
for (VirtualPet value : pets.values())
value.feed();
}
public void feedPet(String name) {
pets.get(name).feed();
}
public void tick() {
for (VirtualPet value : pets.values())
value.tick();
}
在VirtualSet类中:
private int hunger;
public VirtualPet() {
hunger = 5;
}
public int getHunger() {
return hunger;
}
public void feed() {
hunger -= 2;
}
public void tick(){
hunger += 1;
}
共 (0) 个答案