Search code examples
javalisthashmapuser-inputcode-structure

Suggestions for better solution, choosing item from a list


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?


Solution

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