I think this is working the way that I want but I can't figure how to print out each KeyValue one at a time that is entered only after asking of the user wants to continue. I know it's working because if I run the for loop it prints out what I entered. But I want to be able to call them back one at a time.
I tried to reduce the amount of code I'm showing. The first while loop is working (though I took most of it out), I can't seem to figure out the second while loop.
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.
Try this:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.