0

我想在控制台中列出带有数字的项目(每个项目都有一个用于满足饥饿的值),因此用户可以通过输入该项目的编号来选择一个项目。

  1. 热狗 3
  2. 纸杯蛋糕 2

我创建了一个包含所有食物和值的 HashMap 的类 Food。在另一个类(OhterClass)中,我想列出项目和值并处理用户输入。我的目标是读出所选项目的值并将其添加到数据字段:饥饿。

当我这样做时,我必须在 OtherClass 中创建一个 foreach 并用索引读出每个项目和 vlue,我还必须使用 switch case 检查用户输入,但我认为这个解决方案不是很好,但我不知道如何以不同的方式解决它。

有人对我有什么建议吗?

4

2 回答 2

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;
    }
}
于 2014-03-26T09:26:13.117 回答
-1

尝试为您的解决方案实施访问者模式

它看起来像:

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());
    }
}
于 2014-03-26T09:22:56.307 回答