Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.96 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class InvalidNameException extends Exception {
  5.    
  6.     /**
  7.      *
  8.      */
  9.     protected String name;
  10.    
  11.     private static final long serialVersionUID = 1L;
  12.  
  13.     public InvalidNameException() {
  14.         super("Invalid Name");
  15.     }
  16.            
  17.     public InvalidNameException(String name) {
  18.         super();
  19.         this.name = name;
  20.     }
  21.    
  22. }
  23.  
  24. class InvalidNumberException extends Exception {
  25.    
  26.     /**
  27.      *
  28.      */
  29.     private static final long serialVersionUID = 1L;
  30.  
  31.     public InvalidNumberException() {
  32.         super("Invalid Number");
  33.     }
  34.    
  35.     public InvalidNumberException(String message) {
  36.         super(message);
  37.     }
  38. }
  39.  
  40. class MaximumSizeExceddedException extends Exception {
  41.    
  42.     /**
  43.      *
  44.      */
  45.     private static final long serialVersionUID = 1L;
  46.  
  47.     public MaximumSizeExceddedException() {
  48.         super("Maximum size excedded");
  49.     }
  50.    
  51.     public MaximumSizeExceddedException(String message) {
  52.         super(message);
  53.     }
  54. }
  55.  
  56. class InvalidFormatException extends Exception {
  57.     /**
  58.      *
  59.      */
  60.     private static final long serialVersionUID = 1L;
  61.  
  62.     public InvalidFormatException() {
  63.         super("Invalid Format");
  64.     }
  65.    
  66.     public InvalidFormatException(String message) {
  67.         super(message);
  68.     }
  69. }
  70.  
  71. class Contact {
  72.     private String name;
  73.     private ArrayList<String> phoneNumbers = new ArrayList<String>();
  74.     private static final String[] VALID_PREFIX = {"070", "071", "072", "075", "076", "077", "078"};
  75.        
  76.     public Contact(String name, String... phoneNumbers) throws InvalidNameException, InvalidNumberException, MaximumSizeExceddedException {
  77.         if (name.length() < 4 || name.length() > 10 || !containsLettersAndNumbers(name)) throw new InvalidNameException();
  78.         if (!arePhonesValid(phoneNumbers)) throw new InvalidNumberException();
  79.         if (phoneNumbers.length > 5) throw new MaximumSizeExceddedException();
  80.        
  81.         this.name = name;
  82.         for (int i = 0; i < phoneNumbers.length; i++)
  83.             this.phoneNumbers.add(phoneNumbers[i]);
  84.                
  85.     }
  86.    
  87.     public String getName() {
  88.         return name;
  89.     }
  90.    
  91.     public static boolean containsLettersAndNumbers(String s) {
  92.         for (int i = 0; i < s.length(); i++)
  93.             if (!(Character.isLetterOrDigit(s.charAt(i))))
  94.                 return false;
  95.        
  96.         return true;
  97.     }
  98.    
  99.     public static boolean containsDigitsOnly(String s) {
  100.         for (int i = 0; i < s.length(); i++)
  101.             if (!(Character.isDigit(s.charAt(i))))
  102.                 return false;
  103.        
  104.         return true;
  105.     }
  106.        
  107.     public boolean isValid(String phoneNumber) {
  108.        
  109.         if (phoneNumber.length() == 9 && containsDigitsOnly(phoneNumber)) {
  110.             String prefix = phoneNumber.substring(0, 3);
  111.            
  112.             for (int i = 0; i < VALID_PREFIX.length; i++)
  113.                 if (prefix.compareTo(VALID_PREFIX[i]) == 0)
  114.                     return true;
  115.         }
  116.        
  117.         return false;
  118.     }
  119.    
  120.     public boolean arePhonesValid(String[] phoneNumbers) {
  121.                
  122.         for (String phoneNumber : phoneNumbers)
  123.             if (!isValid(phoneNumber))
  124.                 return false;
  125.        
  126.         return true;       
  127.     }
  128.    
  129.     public boolean equals(Object o) {
  130.         if (o == null) return false;
  131.        
  132.         if (getClass() != o.getClass()) return false;
  133.        
  134.         Contact that = (Contact) o;
  135.        
  136.         return this.name.equals(that.name) && this.phoneNumbers.size() == that.phoneNumbers.size()
  137.                                            && this.phoneNumbers.equals(that.phoneNumbers);
  138.     }
  139.    
  140.     public String[] getNumbers() {
  141.         String[] temp = new String[phoneNumbers.size()];
  142.         temp = phoneNumbers.toArray(temp);
  143.        
  144.         Arrays.sort(temp);
  145.        
  146.         return temp;
  147.     }
  148.    
  149.     public void addNumber(String phoneNumber) throws MaximumSizeExceddedException, InvalidNumberException {
  150.        
  151.         if (isValid(phoneNumber)) {
  152.             if (phoneNumbers.size() > 5) throw new MaximumSizeExceddedException();
  153.            
  154.             phoneNumbers.add(phoneNumber);
  155.            
  156.         } else {
  157.             throw new InvalidNumberException();
  158.         }
  159.     }
  160.    
  161.     public String toString() {
  162.         StringBuilder sb = new StringBuilder();
  163.         sb.append(this.name + "\n" + Integer.toString(this.phoneNumbers.size()) + "\n");
  164.        
  165.         String[] lexiOrdered = new String[getNumbers().length];
  166.         lexiOrdered = getNumbers();
  167.        
  168.         for (int i = 0; i < lexiOrdered.length; i++)
  169.             sb.append(lexiOrdered[i] + "\n");      
  170.        
  171.         return sb.toString();
  172.     }
  173.    
  174.     public static Contact valueOf(String s) throws InvalidFormatException {
  175.         String[] temp = s.split("\n");
  176.         String[] phoneNumbers = new String[Integer.parseInt(temp[1])];
  177.        
  178.         for (int i = 0; i < phoneNumbers.length; i++)
  179.             phoneNumbers[i] = temp[i + 2];
  180.        
  181.         try {
  182.             return new Contact(temp[0], phoneNumbers);
  183.            
  184.         } catch (Exception e) {
  185.             throw new InvalidFormatException();
  186.         }
  187.     }
  188.    
  189.     public int hashCode() {
  190.         return phoneNumbers.hashCode();
  191.     }
  192. }
  193.  
  194. class PhoneBook {
  195.    
  196.     private ArrayList<Contact> contacts = new ArrayList<Contact>();
  197.    
  198.     public PhoneBook() {
  199.        
  200.     }
  201.    
  202.     public void addContact(Contact contact) throws MaximumSizeExceddedException, InvalidNameException {
  203.         if (contacts.size() > 250) throw new MaximumSizeExceddedException();
  204.        
  205.         if (!contacts.contains(contact)) {
  206.             contacts.add(contact);
  207.         } else {
  208.             throw new InvalidNameException(contact.getName());
  209.         }
  210.     }
  211.    
  212.     public Contact getContactForName(String name) {
  213.         for (int i = 0; i < contacts.size(); i++)
  214.             if (contacts.get(i).getName().equals(name))
  215.                 return contacts.get(i);
  216.            
  217.         return null;
  218.     }
  219.    
  220.     public int numberOfContacts() {
  221.         return contacts.size();
  222.     }
  223.    
  224.     public Contact[] getContacts() {
  225.         Contact[] contactsArray = new Contact[contacts.size()];
  226.         contactsArray = contacts.toArray(contactsArray);
  227.         Contact temp;
  228.        
  229.         for (int i = 0; i < contacts.size(); i++) {
  230.             for (int j = 1; j < contacts.size() - i; j++) {
  231.                 if (contactsArray[j - 1].getName().compareTo(contactsArray[j].getName()) > 0) {
  232.                     temp = contactsArray[j - 1];
  233.                     contactsArray[j - 1] = contactsArray[j];
  234.                     contactsArray[j] = temp;
  235.                 }
  236.             }
  237.         }
  238.    
  239.         return contactsArray;
  240.     }  
  241.            
  242.     public boolean removeContact(String name) {
  243.         boolean foundName = false;
  244.        
  245.         for (int i = 0; i < contacts.size(); i++) {
  246.             if (contacts.get(i).getName().equals(name)) {
  247.                 foundName = true;
  248.                 contacts.remove(i);
  249.             }
  250.         }
  251.        
  252.         return foundName;
  253.     }
  254.    
  255.     public String toString() {
  256.         StringBuilder sb = new StringBuilder();
  257.        
  258.         Contact[] contactsToString = new Contact[getContacts().length];
  259.         contactsToString = getContacts();
  260.        
  261.         for (int i = 0; i < contactsToString.length; i++)
  262.             sb.append(contactsToString[i].toString() + "\n");
  263.        
  264.         return sb.toString();
  265.     }
  266.    
  267.     public static boolean saveAsTextFile(PhoneBook phonebook, String path) throws IOException {
  268.        
  269.         PrintWriter out = null;
  270.        
  271.         try {
  272.             out = new PrintWriter(new FileOutputStream(path));
  273.             out.print(phonebook);
  274.             out.close();
  275.             return true;
  276.         } catch (Exception e) {
  277.             return false;
  278.         }
  279.     }
  280.    
  281.     public static PhoneBook loadFromTextFile(String path) throws IOException, InvalidFormatException,
  282.                                                             MaximumSizeExceddedException, InvalidNameException, InvalidNumberException {
  283.  
  284.         int noOfContacts = 0;
  285.         PhoneBook phoneBook = new PhoneBook();
  286.         Scanner inputStream = null;    
  287.         inputStream = new Scanner(new FileInputStream(path));
  288.         try {          
  289.             while (inputStream.hasNextLine()) {
  290.                
  291.                 noOfContacts = 0;
  292.                 StringBuilder contact = new StringBuilder();
  293.                
  294.                 contact.append(inputStream.nextLine() + "\n");
  295.                            
  296.                 noOfContacts = Integer.parseInt(inputStream.nextLine());
  297.                                            
  298.                 contact.append(Integer.toString(noOfContacts) + "\n");
  299.                            
  300.                 for (int i = 0; i < noOfContacts; i++)
  301.                     contact.append(inputStream.nextLine() + "\n");
  302.                                                                        
  303.                 phoneBook.addContact(Contact.valueOf(contact.toString()));
  304.                
  305.                 inputStream.nextLine();
  306.             }
  307.         } catch (InvalidFormatException e) {
  308.             throw new InvalidFormatException();
  309.         }
  310.        
  311.         inputStream.close();
  312.         return phoneBook;                      
  313.     }
  314.    
  315.     public Contact[] getContactsForNumber(String numberPrefix) {
  316.         boolean hasPrefix = false;
  317.         ArrayList<Contact> contactsWithPrefix = new ArrayList<Contact>();
  318.        
  319.         for (int i = 0; i < contacts.size(); i++) {
  320.             String[] numbers = contacts.get(i).getNumbers();
  321.             hasPrefix = false;
  322.            
  323.             for (int j = 0; j < numbers.length; j++) {
  324.                 if (numbers[j].substring(0, 3).equals(numberPrefix)) {
  325.                     hasPrefix = true;
  326.                     break;
  327.                 }
  328.             }
  329.            
  330.             if (hasPrefix) contactsWithPrefix.add(contacts.get(i));
  331.         }
  332.        
  333.         Contact[] temp = new Contact[contactsWithPrefix.size()];
  334.         temp = contactsWithPrefix.toArray(temp);
  335.        
  336.         return temp;
  337.     }
  338.    
  339.     public boolean equals(Object o) {
  340.         if (o == null) return false;
  341.         if (getClass() != o.getClass()) return false;
  342.        
  343.         PhoneBook that = (PhoneBook) o;
  344.         /*System.out.println("PRVA NIZAAAAAAAAAAAAaaaaaa");
  345.         for (int i = 0; i < contacts1.length; i++)
  346.             System.out.println(contacts1[i]);
  347.         System.out.println("VTORA NIZAAAAAAAAAAAAaaaaaa");
  348.         for (int i = 0; i < contacts2.length; i++)
  349.             System.out.println(contacts2[i]);*/
  350.        
  351.         return this.contacts.equals(that.contacts);
  352.     }
  353. }
  354.  
  355. public class PhonebookTester {
  356.  
  357.     public static void main(String[] args) throws Exception {
  358.         Scanner jin = new Scanner(System.in);
  359.         String line = jin.nextLine();
  360.         switch( line ) {
  361.             case "test_contact":
  362.                 testContact(jin);
  363.                 break;
  364.             case "test_phonebook_exceptions":
  365.                 testPhonebookExceptions(jin);
  366.                 break;
  367.             case "test_usage":
  368.                 testUsage(jin);
  369.                 break;
  370.             case "test_file":
  371.                 testFile(jin);
  372.                 break;
  373.         }
  374.     }
  375.  
  376.     private static void testFile(Scanner jin) throws Exception {
  377.         PhoneBook phonebook = new PhoneBook();
  378.         while ( jin.hasNextLine() )
  379.             phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  380.         String text_file = "phonebook.txt";
  381.         PhoneBook.saveAsTextFile(phonebook,text_file);
  382.         PhoneBook pb = PhoneBook.loadFromTextFile(text_file);
  383.         if ( ! pb.equals(phonebook) ) System.out.println("Your file saving and loading doesn't seem to work right");
  384.         else System.out.println("Your file saving and loading works great. Good job!");
  385.     }
  386.  
  387.     private static void testUsage(Scanner jin) throws Exception {
  388.         PhoneBook phonebook = new PhoneBook();
  389.         while ( jin.hasNextLine() ) {
  390.             String command = jin.nextLine();
  391.             switch ( command ) {
  392.                 case "add":
  393.                     phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  394.                     break;
  395.                 case "remove":
  396.                     phonebook.removeContact(jin.nextLine());
  397.                     break;
  398.                 case "print":
  399.                     System.out.println(phonebook.numberOfContacts());
  400.                     //System.out.println("AAAAAAAAAAAAAAA");
  401.                     System.out.println(Arrays.toString(phonebook.getContacts()));
  402.                     //System.out.println("AAAAAAAAAAAAAAA");
  403.                     System.out.println(phonebook.toString());
  404.                     //System.out.println("AAAAAAAAAAAAAAA");
  405.                     break;
  406.                 case "get_name":
  407.                     System.out.println(phonebook.getContactForName(jin.nextLine()));
  408.                     break;
  409.                 case "get_number":
  410.                     System.out.println(Arrays.toString(phonebook.getContactsForNumber(jin.nextLine())));
  411.                     break;
  412.             }          
  413.         }
  414.     }
  415.  
  416.     private static void testPhonebookExceptions(Scanner jin) {
  417.         PhoneBook phonebook = new PhoneBook();
  418.         boolean exception_thrown = false;
  419.         try {
  420.             while ( jin.hasNextLine() ) {
  421.                 phonebook.addContact(new Contact(jin.nextLine()));
  422.             }
  423.         }
  424.         catch ( InvalidNameException e ) {
  425.             System.out.println(e.name);
  426.             exception_thrown = true;
  427.         }
  428.         catch ( Exception e ) {}
  429.         if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw InvalidNameException");
  430.         /*
  431.         exception_thrown = false;
  432.         try {
  433.         phonebook.addContact(new Contact(jin.nextLine()));
  434.         } catch ( MaximumSizeExceddedException e ) {
  435.             exception_thrown = true;
  436.         }
  437.         catch ( Exception e ) {}
  438.         if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw MaximumSizeExcededException");
  439.         */
  440.     }
  441.  
  442.     private static void testContact(Scanner jin) throws Exception {    
  443.         boolean exception_thrown = true;
  444.         String names_to_test[] = { "And\nrej","asd","AAAAAAAAAAAAAAAAAAAAAA","Ð�ндрејA123213","Andrej#","Andrej<3"};
  445.         for ( String name : names_to_test ) {
  446.             try {
  447.                 new Contact(name);
  448.                 exception_thrown = false;
  449.             } catch (InvalidNameException e) {
  450.                 exception_thrown = true;
  451.             }
  452.             if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNameException");
  453.         }
  454.         String numbers_to_test[] = { "+071718028","number","078asdasdasd","070asdqwe","070a56798","07045678a","123456789","074456798","073456798","079456798" };
  455.         for ( String number : numbers_to_test ) {
  456.             try {
  457.                 new Contact("Andrej",number);
  458.                 exception_thrown = false;
  459.             } catch (InvalidNumberException e) {
  460.                 exception_thrown = true;
  461.             }
  462.             if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNumberException");
  463.         }
  464.         String nums[] = new String[10];
  465.         for ( int i = 0 ; i < nums.length ; ++i ) nums[i] = getRandomLegitNumber();
  466.         try {
  467.             new Contact("Andrej",nums);
  468.             exception_thrown = false;
  469.         } catch (MaximumSizeExceddedException e) {
  470.             exception_thrown = true;
  471.         }
  472.         if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw a MaximumSizeExceddedException");
  473.         Random rnd = new Random(5);
  474.         Contact contact = new Contact("Andrej",getRandomLegitNumber(rnd),getRandomLegitNumber(rnd),getRandomLegitNumber(rnd));
  475.         System.out.println(contact.getName());
  476.         System.out.println(Arrays.toString(contact.getNumbers()));
  477.         System.out.println(contact.toString());
  478.         contact.addNumber(getRandomLegitNumber(rnd));
  479.         System.out.println(Arrays.toString(contact.getNumbers()));
  480.         System.out.println(contact.toString());
  481.         contact.addNumber(getRandomLegitNumber(rnd));
  482.         System.out.println(Arrays.toString(contact.getNumbers()));
  483.         System.out.println(contact.toString());
  484.     }
  485.  
  486.     static String[] legit_prefixes = {"070","071","072","075","076","077","078"};
  487.     static Random rnd = new Random();
  488.    
  489.     private static String getRandomLegitNumber() {
  490.         return getRandomLegitNumber(rnd);
  491.     }
  492.    
  493.     private static String getRandomLegitNumber(Random rnd) {
  494.         StringBuilder sb = new StringBuilder(legit_prefixes[rnd.nextInt(legit_prefixes.length)]);
  495.         for ( int i = 3 ; i < 9 ; ++i )
  496.             sb.append(rnd.nextInt(10));
  497.         return sb.toString();
  498.     }
  499.    
  500.  
  501. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement