Advertisement
Filip_Markoski

[NP] 3.2 Телефонски именик (Solved)

Oct 25th, 2017
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.12 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Arrays;
  3. import java.util.Comparator;
  4. import java.util.Random;
  5. import java.util.Scanner;
  6. import java.util.stream.IntStream;
  7.  
  8. /*
  9. JSON Builder
  10. https://pastebin.com/jG70ZZzX
  11. */
  12.  
  13. class InvalidNameException extends Exception {
  14.     //Ovoj isklucok se frla dokolku dolzinata na imeto ne e od 5 do 10 karakteri,
  15.     //ili imeto sodrzi karakteri koi ne se bukvi ili brojki.
  16.     public String name;
  17.  
  18.     InvalidNameException(String name) {
  19.         this.name = name;
  20.     }
  21. }
  22.  
  23. class InvalidNumberException extends Exception {
  24.     InvalidNumberException() {
  25.         super();
  26.     }
  27. }
  28.  
  29. class MaximumSizeExceddedException extends Exception {
  30. }
  31.  
  32. class InvalidFormatException extends Exception {
  33. }
  34.  
  35. class Contact implements Comparable<Contact> {
  36.     private String name;
  37.     private String phones[];
  38.     private int size;
  39.  
  40.     Contact(String name, String... phoneNumber) throws InvalidNameException, InvalidNumberException, MaximumSizeExceddedException {
  41.  
  42.         if (!validName(name)) {
  43.             throw new InvalidNameException(name);
  44.         }
  45.  
  46.         if (phoneNumber.length > 5) {
  47.             throw new MaximumSizeExceddedException();
  48.         }
  49.  
  50.         this.name = name;
  51.         this.phones = new String[phoneNumber.length];
  52.         this.size = 0;
  53.  
  54.         for (int i = 0; i < phoneNumber.length; i++) {
  55.             if (validNumber(phoneNumber[i])) {
  56.                 //System.out.println(phoneNumber[i]);
  57.                 this.phones[i] = phoneNumber[i];
  58.                 this.size++;
  59.             } else {
  60.                 throw new InvalidNumberException();
  61.             }
  62.         }
  63.     }
  64.  
  65.     public boolean validName(String name) {
  66.         if (name.length() < 4 || name.length() > 10) {
  67.             return false;
  68.         }
  69.  
  70.         for (int i = 0; i < name.length(); i++) {
  71.             if (!(Character.isLetterOrDigit(name.charAt(i)))) {
  72.                 return false;
  73.             }
  74.         }
  75.         return true;
  76.     }
  77.  
  78.     public boolean validNumber(String phoneNumber) {
  79.         /* 0 1 2  5 6 7  8*/
  80.         String prefixes[] = new String[]{"070", "071", "072", "075", "076", "077", "078"};
  81.  
  82.         if (phoneNumber.length() != 9) {
  83.             return false;
  84.         }
  85.  
  86.         for (int i = 0; i < phoneNumber.length(); i++) {
  87.             if (!(Character.isDigit(phoneNumber.charAt(i)))) {
  88.                 return false;
  89.             }
  90.         }
  91.  
  92.         String prefix = phoneNumber.substring(0, 3);
  93.  
  94.         for (int i = 0; i < prefixes.length; i++) {
  95.             if (prefix.equals(prefixes[i])) {
  96.                 return true;
  97.             }
  98.         }
  99.         return false;
  100.     }
  101.  
  102.     public String getName() {
  103.         return name;
  104.     }
  105.  
  106.     public String[] getNumbers() {
  107.         String temp[] = Arrays.copyOf(phones, size);
  108.         Arrays.sort(temp);
  109.         return temp;
  110.     }
  111.  
  112.     public void addNumber(String phoneNumber) throws InvalidNumberException {
  113.         if (validNumber(phoneNumber)) {
  114.             String temp[] = Arrays.copyOf(phones, size + 1);
  115.             /* maybe phones.length + 1 */
  116.             temp[size++] = phoneNumber;
  117.             phones = temp;
  118.         } else {
  119.             throw new InvalidNumberException();
  120.         }
  121.     }
  122.  
  123.     @Override
  124.     public String toString() {
  125.         StringBuffer sb = new StringBuffer();
  126.         sb.append(name + "\n");
  127.         sb.append(size + "\n");
  128.         String temp[] = getNumbers();
  129.         for (int i = 0; i < size; i++) {
  130.             if (temp[i] != null) {
  131.                 sb.append(temp[i] + "\n");
  132.             }
  133.         }
  134.  
  135.         return sb.toString();
  136.     }
  137.  
  138.     @Override
  139.     public boolean equals(Object o) {
  140.         if (this == o) return true;
  141.         if (o == null || getClass() != o.getClass()) return false;
  142.  
  143.         Contact contact = (Contact) o;
  144.  
  145.         if (name != null ? !name.equals(contact.name) : contact.name != null) return false;
  146.         // Probably incorrect - comparing Object[] arrays with Arrays.equals
  147.         return Arrays.equals(phones, contact.phones);
  148.  
  149.     }
  150.  
  151.     @Override
  152.     public int hashCode() {
  153.         int result = name != null ? name.hashCode() : 0;
  154.         result = 31 * result + Arrays.hashCode(phones);
  155.         return result;
  156.     }
  157.  
  158.     /*
  159.     статички метод кој за дадена тексутална репрезентација на контактот ќе врати соодветен објект -
  160.     доколку настане било каков проблем при  претварањето од тексутална репрезентација во објект Contact
  161.     треба да се фрли исклучок од тип InvalidFormatException
  162.      */
  163.     public static Contact valueOf(String string) throws InvalidFormatException {
  164.         try {
  165.             Scanner scanner = new Scanner(string);
  166.             String name = scanner.next();
  167.             int length = scanner.nextInt();
  168.             String phones[] = new String[length];
  169.             IntStream.range(0, length)
  170.                     .filter(i -> scanner.hasNext())
  171.                     .forEach(i -> phones[i] = scanner.next());
  172.             return new Contact(name, phones);
  173.         } catch (Exception e) {
  174.             throw new InvalidFormatException();
  175.         }
  176.     }
  177.  
  178.     @Override
  179.     public int compareTo(Contact contact) {
  180.         return name.compareTo(contact.name);
  181.     }
  182. }
  183.  
  184. class PhoneBook {
  185.     private Contact contacts[];
  186.     private int size;
  187.  
  188.     PhoneBook() {
  189.         contacts = new Contact[250];
  190.         size = 0;
  191.     }
  192.  
  193.     public boolean isUnique(Contact contact) {
  194.         /* Unique name */
  195.         //System.out.println("Inside Unique");
  196.         for (int i = 0; i < size; i++) {
  197.             //System.out.println("Inside Unique For");
  198.             //System.out.println(contacts[i].getName() + " " + contact.getName() + " " + contacts[i].getName().equals(contact.getName()));
  199.             if (contacts[i].getName().equals(contact.getName())) {
  200.                 return false;
  201.             }
  202.         }
  203.         return true;
  204.     }
  205.  
  206.     public void addContact(Contact contact) throws MaximumSizeExceddedException, InvalidNameException {
  207.         if (size >= 250) {
  208.             throw new MaximumSizeExceddedException();
  209.         }
  210.         if (!contact.validName(contact.getName())) {
  211.             throw new InvalidNameException(contact.getName());
  212.         }
  213.  
  214.         if (isUnique(contact)) {
  215.             contacts[size++] = contact;
  216.         } else {
  217.             throw new InvalidNameException(contact.getName());
  218.         }
  219.  
  220.     }
  221.  
  222.     public Contact getContactForName(String name) {
  223.         for (int i = 0; i < size; i++) {
  224.             /* Just name comparison, getName() is a String */
  225.             if (contacts[i].getName().equals(name)) {
  226.                 return contacts[i];
  227.             }
  228.         }
  229.         return null;
  230.     }
  231.  
  232.     public int numberOfContacts() {
  233.         return size;
  234.     }
  235.  
  236.     public Contact[] getContacts() {
  237.         Contact temp[] = Arrays.copyOf(contacts, size);
  238.         /* Sort by name */
  239.         /*for (int i = 0; i < contacts.length - 1; i++) {
  240.             for (int j = 0; j < contacts.length - i - 1; j++) {
  241.                 if (contacts[j].)
  242.             }
  243.         }*/
  244.  
  245.         //Arrays.sort(temp, Comparator.comparing(Contact::getName));
  246.  
  247.         Arrays.sort(temp); /* same as above but works because I've implemented compareTo() */
  248.         return temp;
  249.     }
  250.  
  251.     public int indexContactFromArray(Contact contact) {
  252.         for (int i = 0; i < size; i++) {
  253.             if (contacts[i].equals(contact)) {
  254.                 return i;
  255.             }
  256.         }
  257.         return -1;
  258.     }
  259.  
  260.     public void avoidElement(Object array[], int index) {
  261.         int elementsToMove = size - 1 - index;
  262.         if (elementsToMove > 0) {
  263.             /* This will copy the sub-array over the index element */
  264.             System.arraycopy(array, index + 1, array, index, elementsToMove);
  265.         }
  266.         array[--size] = null;
  267.     }
  268.  
  269.     public void removeContactFromArray(Contact contact) {
  270.         /* Find its index */
  271.         int index = indexContactFromArray(contact);
  272.         if (index < 0 || index > size) {
  273.             System.out.println("removeContactFromArray index out of bounds");
  274.         }
  275.  
  276.         avoidElement(contacts, index);
  277.         /*System.arraycopy(contacts, );
  278.         Contact left[] = Arrays.copyOfRange(contacts, 0, index);
  279.         Contact right[] = Arrays.copyOfRange(contacts, index + 1, size);
  280.  
  281.         Contact result[] = new Contact[left.length + right.length];
  282.         int k = 0;
  283.         for (int i = 0; i < left.length; i++) {
  284.             result[k++] = left[i];
  285.         }
  286.         for (int i = 0; i < right.length; i++) {
  287.             result[k++] = right[i];
  288.         }
  289.         *//* Change the actual array contacts *//*
  290.         contacts = result;*/
  291.     }
  292.  
  293.     public boolean removeContact(String name) {
  294.         Contact temp = getContactForName(name);
  295.         if (temp != null) {
  296.             removeContactFromArray(temp);
  297.             return true;
  298.         } else {
  299.             return false;
  300.         }
  301.     }
  302.  
  303.     @Override
  304.     public String toString() {
  305.         StringBuffer sb = new StringBuffer();
  306.         Contact sorted[] = getContacts();
  307.         for (int i = 0; i < size; i++) {
  308.             sb.append(sorted[i].toString() + "\n");
  309.         }
  310.         //sb.setLength(sb.length() - 1);
  311.         return sb.toString();
  312.     }
  313.  
  314.     /*public static boolean saveAsTextFile(PhoneBook phonebook,String path) throws IOException {
  315.         try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(path),StandardOpenOption.CREATE)){
  316.             phonebook.contacts.forEach
  317.         }
  318.     }*/
  319.     static public boolean saveAsTextFile(PhoneBook phonebook, String path) throws IOException, FileNotFoundException {
  320.         //try(PrintWriter pw = new PrintWriter(new FileWriter(path))){}
  321.         try {
  322.             File temp = new File(path);
  323.             temp.createNewFile(); // if file already exists will do nothing
  324.             PrintWriter pw = new PrintWriter(temp);
  325.             pw.print(phonebook.toString());
  326.             pw.flush();
  327.             pw.close(); // flushes before close
  328.         } catch (FileNotFoundException e) {
  329.             return false;
  330.         }
  331.         return true;
  332.     }
  333.  
  334.     static public PhoneBook loadFromTextFile(String path)
  335.             throws IOException, InvalidFormatException, InvalidNumberException, InvalidNameException, MaximumSizeExceddedException {
  336.         try (BufferedReader br = new BufferedReader(new FileReader(new File(path)))) {
  337.             String current;
  338.             PhoneBook phoneBook = new PhoneBook();
  339.             while ((current = br.readLine()) != null) {
  340.                 String name = current;
  341.                 int len = Integer.parseInt(br.readLine());
  342.                 String phoneNumbers[] = new String[len];
  343.                 for (int i = 0; i < len; i++) {
  344.                     phoneNumbers[i] = br.readLine();
  345.                 }
  346.                 Contact contact = new Contact(name, phoneNumbers);
  347.                 phoneBook.addContact(contact);
  348.                 br.readLine();
  349.             }
  350.             return phoneBook;
  351.         }
  352.     }
  353.  
  354.  
  355.     public Contact[] getContactsForNumber(String number_prefix) {
  356.         Contact temp[] = new Contact[size];
  357.         int k = 0;
  358.         for (int i = 0; i < size; i++) {
  359.             String numbers[] = contacts[i].getNumbers();
  360.             for (int j = 0; j < numbers.length; j++) {
  361.                 String prefix = numbers[j].substring(0, 3);
  362.                 if (prefix.equals(number_prefix)) {
  363.                     /* Add the number to result, but check if it's unique */
  364.                     /* Unique name */
  365.                     temp[k++] = contacts[i];
  366.                     /* To avoid duplicates we should break */
  367.                     /* The phonebook should already be unique only */
  368.                     break;
  369.                 }
  370.             }
  371.         }
  372.  
  373.         Contact result[] = new Contact[k];
  374.         for (int i = 0; i < k; i++) {
  375.             result[i] = temp[i];
  376.         }
  377.  
  378.         return result;
  379.     }
  380. }
  381.  
  382. public class PhonebookTester {
  383.  
  384.     public static void main(String[] args) throws Exception {
  385.         Scanner jin = new Scanner(System.in);
  386.         String line = jin.nextLine();
  387.         switch (line) {
  388.             case "test_contact":
  389.                 testContact(jin);
  390.                 break;
  391.             case "test_phonebook_exceptions":
  392.                 testPhonebookExceptions(jin);
  393.                 break;
  394.             case "test_usage":
  395.                 testUsage(jin);
  396.                 break;
  397.         }
  398.     }
  399.  
  400.     private static void testFile(Scanner jin) throws Exception {
  401.         PhoneBook phonebook = new PhoneBook();
  402.         while (jin.hasNextLine())
  403.             phonebook.addContact(new Contact(jin.nextLine(), jin.nextLine().split("\\s++")));
  404.         String text_file = "phonebook.txt";
  405.         PhoneBook.saveAsTextFile(phonebook, text_file);
  406.         PhoneBook pb = PhoneBook.loadFromTextFile(text_file);
  407.         if (!pb.equals(phonebook)) System.out.println("Your file saving and loading doesn't seem to work right");
  408.         else System.out.println("Your file saving and loading works great. Good job!");
  409.     }
  410.  
  411.     private static void testUsage(Scanner jin) throws Exception {
  412.         PhoneBook phonebook = new PhoneBook();
  413.         while (jin.hasNextLine()) {
  414.             String command = jin.nextLine();
  415.             switch (command) {
  416.                 case "add":
  417.                     //System.out.println("\nADDING\n");
  418.                     phonebook.addContact(new Contact(jin.nextLine(), jin.nextLine().split("\\s++")));
  419.                     break;
  420.                 case "remove":
  421.                     phonebook.removeContact(jin.nextLine());
  422.                     break;
  423.                 case "print":
  424.                     //System.out.println("\nPRINTING\n");
  425.                     System.out.println(phonebook.numberOfContacts());
  426.                     System.out.println(Arrays.toString(phonebook.getContacts()));
  427.                     System.out.println(phonebook.toString());
  428.                     break;
  429.                 case "get_name":
  430.                     System.out.println(phonebook.getContactForName(jin.nextLine()));
  431.                     break;
  432.                 case "get_number":
  433.                     System.out.println(Arrays.toString(phonebook.getContactsForNumber(jin.nextLine())));
  434.                     break;
  435.             }
  436.         }
  437.     }
  438.  
  439.     private static void testPhonebookExceptions(Scanner jin) {
  440.         PhoneBook phonebook = new PhoneBook();
  441.         boolean exception_thrown = false;
  442.         try {
  443.             while (jin.hasNextLine()) {
  444.                 phonebook.addContact(new Contact(jin.nextLine()));
  445.             }
  446.         } catch (InvalidNameException e) {
  447.             System.out.println(e.name);
  448.             exception_thrown = true;
  449.         } catch (Exception e) {
  450.         }
  451.         if (!exception_thrown) System.out.println("Your addContact method doesn't throw InvalidNameException");
  452.         /*
  453.         exception_thrown = false;
  454.         try {
  455.         phonebook.addContact(new Contact(jin.nextLine()));
  456.         } catch ( MaximumSizeExceddedException e ) {
  457.             exception_thrown = true;
  458.         }
  459.         catch ( Exception e ) {}
  460.         if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw MaximumSizeExcededException");
  461.         */
  462.     }
  463.  
  464.     private static void testContact(Scanner jin) throws Exception {
  465.         boolean exception_thrown = true;
  466.         String names_to_test[] = {"And\nrej", "asd", "AAAAAAAAAAAAAAAAAAAAAA", "Ð�ндрејA123213", "Andrej#", "Andrej<3"};
  467.         for (String name : names_to_test) {
  468.             try {
  469.                 new Contact(name);
  470.                 exception_thrown = false;
  471.             } catch (InvalidNameException e) {
  472.                 exception_thrown = true;
  473.             }
  474.             if (!exception_thrown) System.out.println("Your Contact constructor doesn't throw an InvalidNameException");
  475.         }
  476.         String numbers_to_test[] = {"+071718028", "number", "078asdasdasd", "070asdqwe", "070a56798", "07045678a", "123456789", "074456798", "073456798", "079456798"};
  477.         for (String number : numbers_to_test) {
  478.             try {
  479.                 new Contact("Andrej", number);
  480.                 exception_thrown = false;
  481.             } catch (InvalidNumberException e) {
  482.                 exception_thrown = true;
  483.             }
  484.             if (!exception_thrown)
  485.                 System.out.println("Your Contact constructor doesn't throw an InvalidNumberException");
  486.         }
  487.         String nums[] = new String[10];
  488.         for (int i = 0; i < nums.length; ++i) nums[i] = getRandomLegitNumber();
  489.         try {
  490.             new Contact("Andrej", nums);
  491.             exception_thrown = false;
  492.         } catch (MaximumSizeExceddedException e) {
  493.             exception_thrown = true;
  494.         }
  495.         if (!exception_thrown)
  496.             System.out.println("Your Contact constructor doesn't throw a MaximumSizeExceddedException");
  497.         Random rnd = new Random(5);
  498.         Contact contact = new Contact("Andrej", getRandomLegitNumber(rnd), getRandomLegitNumber(rnd), getRandomLegitNumber(rnd));
  499.         System.out.println(contact.getName());
  500.         System.out.println(Arrays.toString(contact.getNumbers()));
  501.         System.out.println(contact.toString());
  502.         contact.addNumber(getRandomLegitNumber(rnd));
  503.         System.out.println(Arrays.toString(contact.getNumbers()));
  504.         System.out.println(contact.toString());
  505.         contact.addNumber(getRandomLegitNumber(rnd));
  506.         System.out.println(Arrays.toString(contact.getNumbers()));
  507.         System.out.println(contact.toString());
  508.     }
  509.  
  510.     static String[] legit_prefixes = {"070", "071", "072", "075", "076", "077", "078"};
  511.     static Random rnd = new Random();
  512.  
  513.     private static String getRandomLegitNumber() {
  514.         return getRandomLegitNumber(rnd);
  515.     }
  516.  
  517.     private static String getRandomLegitNumber(Random rnd) {
  518.         StringBuilder sb = new StringBuilder(legit_prefixes[rnd.nextInt(legit_prefixes.length)]);
  519.         for (int i = 3; i < 9; ++i)
  520.             sb.append(rnd.nextInt(10));
  521.         return sb.toString();
  522.     }
  523.  
  524.  
  525. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement