我想在控制台中使用数字列出项目(每个项目都有一个用于满足饥饿的值),因此用户可以通过输入此项目的编号来选择项目。
我创建了一个带有所有食物和价值的HashMap的食物。 在另一个类(OhterClass)中,我想列出项和值并处理用户输入。我的目标是读出所选项目的值并将其添加到数据字段:饥饿。
当我这样做时,我必须在OtherClass中创建一个foreach并用索引读出每个项目和vlue,我还必须检查用户输入的开关案例,但我认为这个解决方案不是&#39非常好,但我不知道如何以不同的方式解决它。
有人有人对我提出一些建议吗?
答案 0 :(得分:0)
你可以试试这个:
public class Hunger {
public static void main(String[] args) {
for (Food food : Food.values()) {
System.out.printf("%d %-8s %d\n", food.ordinal(), food.caption, food.sustenance);
}
System.out.print("Hungry? Make your choice: ");
Scanner scanner = new Scanner(System.in);
Food food;
while (true) {
try {
food = Food.values()[scanner.nextInt() - 1];
break;
} catch (Exception e) {
System.out.println("Naa ... choose again: ");
}
}
System.out.printf("This %s was yummy!\n", food.caption);
}
}
enum Food {
HOT_DOG("Hot Dog", 3),
CUP_CAKE("Cup Cake", 2);
final String caption;
final int sustenance;
private Food(String caption, int sustenance) {
this.caption = caption;
this.sustenance = sustenance;
}
}
答案 1 :(得分:-1)
尝试为您的解决方案实施visitor pattern。
看起来像是:
public interface FoodVisitor {
void visit(FoodType food);
}
public interface FoodType {
void accept(FoodVisitor visitor);
String getName();
}
public class HotDog implements FoodType {
public void accept(FoodVisitor visitor) {
visitor.visit(this);
}
public String getName() {
return "Hot Dog";
}
}
public class FoodVisitorImpl implements FoodVisitor {
public void visit(FoodType food) {
System.out.println("Enter the amount of " + food.getName() + " you would like");
Scanner in= ....
//Get the amount, save it in a field in the visitor
}
}
public class Demo {
public static void main(String ... args) {
FoodVisitorImpl visitor= new FoodVisitorImpl();
for (FoodType food : foodList) {
food.accept(visitor);
}
//also, implement a certain getResult() method in the visitor
System.out.println(visitor.getResult());
}
}