afiqakraam

PhonebookHashtable

Jun 22nd, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Main {
  5.  
  6. private Hashtable phoneBooks;
  7.  
  8. public Main(){
  9.  this.phoneBooks = new Hashtable();
  10.  }
  11.  
  12.  
  13.  
  14. public void tambah(String name, String number){
  15.  if(this.phoneBooks.containsKey(name)){
  16.  System.out.println(name+ " exists.");
  17.  } else {
  18.  this.phoneBooks.put(name, number);
  19.  System.out.println(name+" success.");
  20.  }
  21.  }
  22.  
  23. public void cari (String name){
  24.  if(this.phoneBooks.containsKey(name)){
  25.  String number = (String) this.phoneBooks.get(name);
  26.  System.out.println(name+"'s number is "+number+".");
  27.  } else {
  28.  System.out.println("Unknown '"+name+"'");
  29.  }
  30.  }
  31.  
  32. public void status(){
  33.  Enumeration names;
  34.  names = this.phoneBooks.keys();
  35.  int total = 0;
  36.  while(names.hasMoreElements()) {
  37.  String str = (String) names.nextElement();
  38.  System.out.println(str + " " + this.phoneBooks.get(str));
  39.  total++;
  40.  }
  41.  System.out.println("Total "+total+" kontak.");
  42.  }
  43.  
  44. public void hapus_entry(String name){
  45.  if(this.phoneBooks.containsKey(name)){
  46.  this.phoneBooks.remove(name);
  47.  System.out.println(name+" deleted.");
  48.  } else {
  49.  System.out.println("Unknown'"+name+"'");
  50.  }
  51.  }
  52.  
  53. public static void main(String[] args ) throws IOException {
  54.  
  55. Scanner scanner = new Scanner(System.in);
  56. Main phoneBook = new Main();
  57.  
  58. while(true){
  59.     System.out.print("Choose category\n");
  60.     System.out.print("1. Add contact \n");
  61.     System.out.print("2. Search contact \n");
  62.     System.out.print("3. Status \n");
  63.     System.out.print("4. Delete contact \n");
  64.     System.out.print("5. Exit \n");
  65.     System.out.print("Command: ");
  66.  
  67. int command = scanner.nextInt();
  68.  
  69. if(command==1){
  70.     System.out.print("Name: ");
  71.     String name = scanner.next();
  72.     System.out.print("Number: ");
  73.     String number = scanner.next();
  74.     phoneBook.tambah(name, number);
  75.  }
  76.  else if(command==2){
  77.     System.out.print("Name: ");
  78.     String name = scanner.next();
  79.     phoneBook.cari(name);
  80.  }
  81.  else if(command==3){
  82.     phoneBook.status();
  83.  }
  84.  else if(command==4){
  85.     System.out.print("Name: ");
  86.     String name = scanner.next();
  87.     phoneBook.hapus_entry(name);
  88.  }
  89.  else if(command==5){
  90.  break;
  91.  }
  92.  }
  93.  scanner.close();
  94.  }
  95.  }
Advertisement
Add Comment
Please, Sign In to add comment