我想在控制台中用数字列出物品(每个物品都有一个满足饥饿的值),因此用户可以通过输入物品的编号来选择物品。
- 热狗3
- 蛋糕2
我用所有食物和值的HashMap创建了一个类Food。在另一个类(OhterClass)中,我想列出项目和值并处理用户输入。我的目标是读出所选项的值并将其添加到数据字段:hunger.
当我这样做的时候,我必须在OtherClass中创建一个foreach,并通过索引读取每个项目和值,我还必须检查用户输入的开关情况,但我认为这个解决方案不是很好,但我不知道如何解决它。
有人给我一些建议吗?
你可以试试:
public class Hunger {
public static void main(String[] args) {
for (Food food : Food.values()) {
System.out.printf("%d %-8s %dn", 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;
}
}
尝试为您的解决方案实现一个访问者模式。
它看起来像:
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());
}
}