繁体   English   中英

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

[英]How do I print out one HashMap KeyValue at one time after asking the user if they want to continue?

我认为这是按照我想要的方式工作的,但我无法弄清楚如何一次打印出每个 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.

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM