In: Computer Science
Okay, I have a general idea of how to use the scanner, but i'm a bit confused of how to ask multiple questions and also how maps work, which is making me struggle on this questions... If i had more time, i'd study a bit more, but I only have about 3 hours. If possible, could you explain every step with comments?
Use the scanner class to ask users their name and age. Store at least 10 users on a map, and use the iterator to print all the values. Print the youngest user's name
/*******************************YoungestUser.java***********************/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class YoungestUser {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);// initialize the scanner
Map<Integer, String> users = new HashMap<>();// initialize map
/*
* for loop to enter number of times
you want to enter user
*/
for (int i = 0; i < 3; i++)
{
System.out.print("Enter the name of user: ");// prompt for
name
String name =
scan.nextLine();// read name as full line
System.out.print("Enter the age of user: ");// prompt for age
int age =
scan.nextInt();// read age
scan.nextLine();// clear the buffer after read nextInt
users.put(age,
name);// put data in map
}
Map<Integer, String>
treeMap = new TreeMap<Integer, String>(users);//sort the map
using age as key
System.out.println("****************Print the users youngest to
oldest********");
Set<Entry<Integer,
String>> entrySet = treeMap.entrySet();
Iterator<Entry<Integer,
String>> it = entrySet.iterator(); // using iterator iterate
the entry set
while (it.hasNext()) {
Map.Entry<Integer,String> me =
(Map.Entry<Integer,String>) it.next();// read value one by
one
System.out.println("Name is: " + me.getValue() + " and age is: " +
me.getKey());// print the data
}
Entry<Integer, String> entry
= treeMap.entrySet().iterator().next();
System.out.println("The youngest
users is: "+entry.getValue());
scan.close();// close the
scanner
}
}
/****************output*****************/
Enter the name of user: JKS
Enter the age of user: 10
Enter the name of user: Virat
Enter the age of user: 56
Enter the name of user: Gagan
Enter the age of user: 6
****************Print the users youngest to oldest********
Name is: Gagan and age is: 6
Name is: JKS and age is: 10
Name is: Virat and age is: 56
The youngest users is: Gagan
Please let me know if you have any doubt or modify the answer, Thanks:)