Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.58 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.println(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.        
  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.        
  308.         inputStream.close();
  309.         return phoneBook;                      
  310.     }
  311.    
  312.     public Contact[] getContactsForNumber(String numberPrefix) {
  313.         boolean hasPrefix = false;
  314.         ArrayList<Contact> contactsWithPrefix = new ArrayList<Contact>();
  315.        
  316.         for (int i = 0; i < contacts.size(); i++) {
  317.             String[] numbers = contacts.get(i).getNumbers();
  318.             hasPrefix = false;
  319.            
  320.             for (int j = 0; j < numbers.length; j++) {
  321.                 if (numbers[j].substring(0, 3).equals(numberPrefix)) {
  322.                     hasPrefix = true;
  323.                     break;
  324.                 }
  325.             }
  326.            
  327.             if (hasPrefix) contactsWithPrefix.add(contacts.get(i));
  328.         }
  329.        
  330.         Contact[] temp = new Contact[contactsWithPrefix.size()];
  331.         temp = contactsWithPrefix.toArray(temp);
  332.        
  333.         return temp;
  334.     }
  335.    
  336.     public boolean equals(Object o) {
  337.         if (o == null) return false;
  338.         if (getClass() != o.getClass()) return false;
  339.        
  340.         PhoneBook that = (PhoneBook) o;
  341.        
  342.         return this.contacts.equals(that.contacts);
  343.     }
  344. }
  345.  
  346. public class PhonebookTester {
  347.  
  348.     public static void main(String[] args) throws Exception {
  349.         Scanner jin = new Scanner(System.in);
  350.         String line = jin.nextLine();
  351.         switch( line ) {
  352.             case "test_contact":
  353.                 testContact(jin);
  354.                 break;
  355.             case "test_phonebook_exceptions":
  356.                 testPhonebookExceptions(jin);
  357.                 break;
  358.             case "test_usage":
  359.                 testUsage(jin);
  360.                 break;
  361.             case "test_file":
  362.                 testFile(jin);
  363.                 break;
  364.         }
  365.     }
  366.  
  367.     private static void testFile(Scanner jin) throws Exception {
  368.         PhoneBook phonebook = new PhoneBook();
  369.         while ( jin.hasNextLine() )
  370.             phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  371.         String text_file = "phonebook.txt";
  372.         PhoneBook.saveAsTextFile(phonebook,text_file);
  373.         PhoneBook pb = PhoneBook.loadFromTextFile(text_file);
  374.         if ( ! pb.equals(phonebook) ) System.out.println("Your file saving and loading doesn't seem to work right");
  375.         else System.out.println("Your file saving and loading works great. Good job!");
  376.     }
  377.  
  378.     private static void testUsage(Scanner jin) throws Exception {
  379.         PhoneBook phonebook = new PhoneBook();
  380.         while ( jin.hasNextLine() ) {
  381.             String command = jin.nextLine();
  382.             switch ( command ) {
  383.                 case "add":
  384.                     phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  385.                     break;
  386.                 case "remove":
  387.                     phonebook.removeContact(jin.nextLine());
  388.                     break;
  389.                 case "print":
  390.                     System.out.println(phonebook.numberOfContacts());
  391.                     //System.out.println("AAAAAAAAAAAAAAA");
  392.                     System.out.println(Arrays.toString(phonebook.getContacts()));
  393.                     //System.out.println("AAAAAAAAAAAAAAA");
  394.                     System.out.println(phonebook.toString());
  395.                     //System.out.println("AAAAAAAAAAAAAAA");
  396.                     break;
  397.                 case "get_name":
  398.                     System.out.println(phonebook.getContactForName(jin.nextLine()));
  399.                     break;
  400.                 case "get_number":
  401.                     System.out.println(Arrays.toString(phonebook.getContactsForNumber(jin.nextLine())));
  402.                     break;
  403.             }          
  404.         }
  405.     }
  406.  
  407.     private static void testPhonebookExceptions(Scanner jin) {
  408.         PhoneBook phonebook = new PhoneBook();
  409.         boolean exception_thrown = false;
  410.         try {
  411.             while ( jin.hasNextLine() ) {
  412.                 phonebook.addContact(new Contact(jin.nextLine()));
  413.             }
  414.         }
  415.         catch ( InvalidNameException e ) {
  416.             System.out.println(e.name);
  417.             exception_thrown = true;
  418.         }
  419.         catch ( Exception e ) {}
  420.         if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw InvalidNameException");
  421.         /*
  422.         exception_thrown = false;
  423.         try {
  424.         phonebook.addContact(new Contact(jin.nextLine()));
  425.         } catch ( MaximumSizeExceddedException e ) {
  426.             exception_thrown = true;
  427.         }
  428.         catch ( Exception e ) {}
  429.         if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw MaximumSizeExcededException");
  430.         */
  431.     }
  432.  
  433.     private static void testContact(Scanner jin) throws Exception {    
  434.         boolean exception_thrown = true;
  435.         String names_to_test[] = { "And\nrej","asd","AAAAAAAAAAAAAAAAAAAAAA","Ð�ндрејA123213","Andrej#","Andrej<3"};
  436.         for ( String name : names_to_test ) {
  437.             try {
  438.                 new Contact(name);
  439.                 exception_thrown = false;
  440.             } catch (InvalidNameException e) {
  441.                 exception_thrown = true;
  442.             }
  443.             if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNameException");
  444.         }
  445.         String numbers_to_test[] = { "+071718028","number","078asdasdasd","070asdqwe","070a56798","07045678a","123456789","074456798","073456798","079456798" };
  446.         for ( String number : numbers_to_test ) {
  447.             try {
  448.                 new Contact("Andrej",number);
  449.                 exception_thrown = false;
  450.             } catch (InvalidNumberException e) {
  451.                 exception_thrown = true;
  452.             }
  453.             if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNumberException");
  454.         }
  455.         String nums[] = new String[10];
  456.         for ( int i = 0 ; i < nums.length ; ++i ) nums[i] = getRandomLegitNumber();
  457.         try {
  458.             new Contact("Andrej",nums);
  459.             exception_thrown = false;
  460.         } catch (MaximumSizeExceddedException e) {
  461.             exception_thrown = true;
  462.         }
  463.         if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw a MaximumSizeExceddedException");
  464.         Random rnd = new Random(5);
  465.         Contact contact = new Contact("Andrej",getRandomLegitNumber(rnd),getRandomLegitNumber(rnd),getRandomLegitNumber(rnd));
  466.         System.out.println(contact.getName());
  467.         System.out.println(Arrays.toString(contact.getNumbers()));
  468.         System.out.println(contact.toString());
  469.         contact.addNumber(getRandomLegitNumber(rnd));
  470.         System.out.println(Arrays.toString(contact.getNumbers()));
  471.         System.out.println(contact.toString());
  472.         contact.addNumber(getRandomLegitNumber(rnd));
  473.         System.out.println(Arrays.toString(contact.getNumbers()));
  474.         System.out.println(contact.toString());
  475.     }
  476.  
  477.     static String[] legit_prefixes = {"070","071","072","075","076","077","078"};
  478.     static Random rnd = new Random();
  479.    
  480.     private static String getRandomLegitNumber() {
  481.         return getRandomLegitNumber(rnd);
  482.     }
  483.    
  484.     private static String getRandomLegitNumber(Random rnd) {
  485.         StringBuilder sb = new StringBuilder(legit_prefixes[rnd.nextInt(legit_prefixes.length)]);
  486.         for ( int i = 3 ; i < 9 ; ++i )
  487.             sb.append(rnd.nextInt(10));
  488.         return sb.toString();
  489.     }
  490.    
  491.  
  492. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement