在询问用户是否要继续后,如何一次打印出一个HashMap KeyValue?

时间:2019-07-06 19:11:02

标签: java

我认为这是我想要的方式,但是我无法弄清楚如何仅在询问用户要继续后才一次输入每个KeyValue。我知道它正在工作,因为如果我运行for循环,它将打印出我输入的内容。但我希望能够一次给他们回电。

我试图减少显示的代码量。第一个while循环正在工作(尽管我大部分都花了),但是我似乎无法弄清楚第二个while循环。

    Map<String, String> pets = new HashMap<>();

        String userInput;
        String name;
        String type;


try (Scanner scnr = new Scanner(System.in)) {
    do {  

           System.out.println("Would you like to enter another? (y/n) ");

        numberOfPets++;

    } while (scnr.nextLine().equalsIgnoreCase("y"));

        System.out.println("You entered " + numberOfPets + " pets.");


        do {
           System.out.println("Enter one of the names of the pets (or type END to quit): ");
            userInput = scnr.nextLine();
            pets.get(userInput);

              for (Map.Entry<String, String> pet : pets.entrySet()) {
              System.out.println(pet.getKey() + " is an " + pet.getValue());
             }

        } while (scnr.nextLine().equalsIgnoreCase("e"));

    }

I want it to look like this: 
You entered 2 pets.
Enter one of the pets names (or type END to quit): {User enters Aslan}
Aslan is a Lion.
Enter one of the pets names (or type END to quit): {User enters Eustance}
Eustance is a dragon.

1 个答案:

答案 0 :(得分:-1)

尝试一下:


      Map<String, String> pets = Map.of("a", "lion", "b", "bear", "c", "cat");
      Scanner scnr = new Scanner(System.in);

      do {
         System.out.println("Enter one letter (or type END to quit): ");
         String userInput = scnr.nextLine();
         if (userInput.equalsIgnoreCase("end")) {
            break;
         }
         System.out.println(userInput + " is an " + pets.get(userInput));

      } while (true);