In: Computer Science
Creating a Perl Product Directory - A product "id" will be used to identify a product (the key) and the description will be stored as the value
Some code is provided to you as a template.
The following code is written in JAVA.
---------------------------------------------------------------------------------------------------------------------------
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class PerlDirectory {
public static void main(String[] args) {
/*
Create a hash map with an integer key and string description
*/
HashMap<Integer,String> map = new
HashMap<Integer,String>();
boolean program = true;
while(program){
System.out.println("******************************");
System.out.println("---------MENU-----------");
System.out.println("1. ADD");
System.out.println("2. REMOVE");
System.out.println("3. LOOKUP");
System.out.println("4. LIST");
System.out.println("5. QUIT");
System.out.println("******************************");
Scanner sc = new Scanner(System.in);
System.out.print("Enter your choice : ");
int choice = sc.nextInt();
if(choice == 5){
//QUIT AND CLOSE THE MENU , END OF LOOP
program = false;
System.out.println("Menu closed");
}else if(choice == 4){
//LIST ALL ENTRIES
for (Map.Entry<Integer,String> entry : map.entrySet())
System.out.println(entry.getKey() + " - "+ entry.getValue());
}else if(choice == 3){
// LOOKUP FOR A PRODUCT IN HASH MAP
System.out.print("Enter product ID : ");
int product_id = sc.nextInt();
if(map.containsKey(product_id)){
System.out.println(map.get(product_id));
}else{
System.out.println("Key not found");
}
}else if(choice == 2){
// DELETE ITEM FROM HASH MAP
System.out.print("Enter product ID : ");
int product_id = sc.nextInt();
/*
Here containsKey() is a method which returns true or false
depending on
whether the entered key is present in the map or not
*/
if(map.containsKey(product_id)){
map.remove(product_id);
System.out.println("Item successfully removed");
}else{
System.out.println("Key not found");
}
}else if(choice == 1){
System.out.print("Enter product ID : ");
int product_id = sc.nextInt();
sc.nextLine();
System.out.print("Enter description : ");
String description = sc.nextLine();
//ADD ITEM TO HASH MAP
map.put(product_id,description);
System.out.println("Item Added Successfully");
}else{
System.out.print("Incorrect Menu Item Selected");
}
}
}
}