Pregunta

I want to list items (each item has a value which serve to satisfy hunger) with numbers in a console, so the user can choose an item by entering the number of this item.

  1. HotDog 3
  2. CupCake 2

I created a class Food with a HashMap of all food and values. In an other class (OhterClass) I want to list the items and values and process the user input. My goal is to read out the value of the choosen item and add it to the datafield: hunger.

When I do it like this i have to create a foreach in OtherClass and read out each item and vlue with an index, and I also have to check the user input with a switch case, but I think this solution isn't very nice, but I have no idea how I could solve it differently.

Does someone have anyone have some suggestions for me?

¿Fue útil?

Solución

You may try this:

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;
    }
}

Otros consejos

Try implementing a visitor pattern for your solution.

It would look something like:

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());
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top