Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA question create a class People that will store a table of people\'s first n

ID: 3868997 • Letter: J

Question

JAVA question

create a class People that will store a table of people's first names and ages
(using a HashMap, the people's names as the key, and integer ages as the value).
Read people and ages from the console (e.g. Bob 19) and add to the HashMap.
For this example, assume ages are integers and names do not contain spaces. After
a list of name, age pairs, a name will be entered without an age (e.g. Mary) and
the user will terminate their input by typing ctrl-D, by pressing the control and
'D' keys (ctrl-Z on Windows). Treat the last name (Mary in this example) as a
query. Print out the age of the person entered last, or print unknown if the
person's name is unknown (i.e. it did not appear earlier in the list).

Explanation / Answer

PeopleTest.java

import java.util.Scanner;

public class PeopleTest {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.print("Enter the first name(QUIT to exit): ");

String firstName = scan.next();

People p = new People();

while (!firstName.equals("QUIT")) {

System.out.print("Enter the age: ");

int age = scan.nextInt();

p .setDetails(firstName, age);

System.out.print("Enter the first name(QUIT to exit): ");

firstName = scan.next();

}

System.out.print("Enter the first name to search age: ");

firstName = scan.next();

if(p.getMap().containsKey(firstName)) {

System.out.println("Age is "+p.getMap().get(firstName));

} else {

System.out.println("Age is unknown");

}

}

}

People.java

import java.util.HashMap;

public class People {

HashMap<String, Integer> map = null;

public People() {

map = new HashMap<String, Integer>();

}

public void setDetails(String firstName, int age) {

map.put(firstName, age);

}

public HashMap<String, Integer> getMap() {

return map;

}

}

Output:

Enter the first name(QUIT to exit): Suresh
Enter the age: 30
Enter the first name(QUIT to exit): Sekhar
Enter the age: 29
Enter the first name(QUIT to exit): Anshu
Enter the age: 8
Enter the first name(QUIT to exit): QUIT
Enter the first name to search age: Sekhar
Age is 29