Advertisement
SashkoKlincharov

[JAVA][НП] - Телефонски именик

Jan 28th, 2021
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.97 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. import java.util.Arrays;
  4.  
  5. class InvalidFormatException extends Exception {
  6. public InvalidFormatException() {
  7. super();
  8. }
  9. }
  10.  
  11. class InvalidNameException extends Exception {
  12.  
  13. public String name;
  14.  
  15. public InvalidNameException() {
  16. super();
  17. }
  18.  
  19. public InvalidNameException(String name) {
  20. super();
  21. this.name = name;
  22. }
  23. }
  24.  
  25. class MaximumSizeExceddedException extends Exception {
  26.  
  27. public MaximumSizeExceddedException() {
  28. super();
  29. }
  30.  
  31. }
  32.  
  33. class InvalidNumberException extends Exception {
  34.  
  35. public InvalidNumberException() {
  36. super();
  37. }
  38.  
  39. }
  40.  
  41. class Contact implements Comparable<Contact> {
  42.  
  43. private String Name;
  44. private List<String> Numbers;
  45.  
  46. public Contact(String name, String... phonenumber) throws InvalidNameException, InvalidNumberException, MaximumSizeExceddedException {
  47. checkName(name);
  48. checkPhoneNumbers(phonenumber);
  49. this.Name = name;
  50. this.Numbers = new ArrayList<>();
  51. this.Numbers.addAll(Arrays.asList(phonenumber));
  52. }
  53.  
  54. private void checkPhoneNumbers(String[] phonenumber) throws InvalidNumberException, MaximumSizeExceddedException {
  55. if (phonenumber.length > 5)
  56. throw new MaximumSizeExceddedException();
  57. for (int i = 0; i < phonenumber.length; i++) {
  58. checkPhoneNumberPrefix(phonenumber[i]);
  59. }
  60. }
  61.  
  62. private void checkPhoneNumberPrefix(String s) throws InvalidNumberException {
  63. if (s.length() != 9)
  64. throw new InvalidNumberException();
  65. String prefix = s.substring(0, 3);
  66. if (!(prefix.equals("070") || (prefix.equals("071")) || (prefix.equals("072"))
  67. || (prefix.equals("075")) || (prefix.equals("076")) || (prefix.equals("077")) || (prefix.equals("078"))))
  68. throw new InvalidNumberException();
  69.  
  70. for (int i = 0; i < s.length(); i++) {
  71. if (!Character.isDigit(s.charAt(i)))
  72. throw new InvalidNumberException();
  73. }
  74.  
  75. }
  76.  
  77.  
  78. private void checkName(String name) throws InvalidNameException {
  79. if (name.length() < 5 || name.length() > 10)
  80. throw new InvalidNameException(name);
  81. for (int i = 0; i < name.length(); i++) {
  82. if (!Character.isLetterOrDigit(name.charAt(i)))
  83. throw new InvalidNameException(name);
  84. }
  85. }
  86.  
  87. public String getName() {
  88. return this.Name;
  89. }
  90.  
  91. public String[] getNumbers() {
  92. List<String> copy = new ArrayList<>(Numbers);
  93. Collections.sort(copy);
  94. return copy.stream().toArray(String[]::new);////////////////????????????
  95.  
  96. }
  97.  
  98. @Override
  99. public int compareTo(Contact o) {
  100. return this.getName().compareTo(o.getName());
  101. }
  102.  
  103. public void addNumber(String phonenumber) throws InvalidNumberException, MaximumSizeExceddedException {
  104. checkPhoneNumbers(new String[] {phonenumber});
  105. this.Numbers.add(phonenumber);
  106. }
  107.  
  108. @Override
  109. public String toString() {
  110. StringBuilder sb = new StringBuilder();
  111. sb.append(getName()).append("\n");
  112. sb.append(Numbers.size()).append("\n");
  113. String[] getNumbersSorted = getNumbers();
  114. for (String s : getNumbersSorted) {
  115. sb.append(s).append("\n");
  116. }
  117. return sb.toString();
  118. }
  119. }
  120.  
  121.  
  122. class PhoneBook {
  123.  
  124. private List<Contact> Contacts;
  125. private int NumberOfContacts;
  126.  
  127. public PhoneBook() {
  128. this.Contacts = new ArrayList<>();
  129. this.NumberOfContacts = 0;
  130. }
  131.  
  132. public void addContact(Contact contact) throws InvalidNameException, MaximumSizeExceddedException {
  133. if(Contacts.stream().anyMatch(i -> i.getName().equals(contact.getName())))
  134. throw new InvalidNameException(contact.getName());
  135. if(NumberOfContacts==250)
  136. throw new MaximumSizeExceddedException();
  137. Contacts.add(contact);
  138. NumberOfContacts++;
  139. }
  140.  
  141. public Contact getContactForName(String name) {
  142. Contact c = null;
  143. for (int i = 0; i < Contacts.size(); i++) {
  144. if(Contacts.get(i).getName().equals(name))
  145. c = Contacts.get(i);
  146. }
  147. return c;
  148. // if(Contacts.stream().anyMatch(i -> i.getName().equals(name)))
  149. // return null;
  150. // return Contacts.stream().filter(i -> i.getName().equals(name)).findFirst().get();
  151. // return Contacts.stream()
  152. // .filter(i -> i.getName().equals(name))
  153. // .findFirst()
  154. // .get();
  155.  
  156. }
  157.  
  158.  
  159. public int numberOfContacts() {
  160. return this.NumberOfContacts;
  161. }
  162.  
  163. public Contact[] getContacts() {
  164. List<Contact> arrayCopy = new ArrayList<>(Contacts);
  165. arrayCopy.sort(Comparator.comparing(Contact::getName));
  166. return arrayCopy.stream().toArray(Contact[]::new);///////////????????
  167. }
  168.  
  169.  
  170. public boolean removeContact(String name) {
  171. int i;
  172. Contact c = null;
  173. for (i = 0; i < Contacts.size(); i++) {
  174. if(Contacts.get(i).getName().equals(name)) {
  175. c = Contacts.get(i);
  176. break;
  177. }
  178. }
  179. if(c==null)
  180. return false;
  181. Contacts.remove(i);
  182. NumberOfContacts--;
  183. return true;
  184. }
  185.  
  186. public String toString() {
  187. StringBuilder sb = new StringBuilder();
  188. for(int i=0; i<getContacts().length; i++)
  189. if(getContacts()[i]!=null)
  190. sb.append(getContacts()[i]).append('\n');
  191. return sb.toString();
  192. }
  193.  
  194. public static boolean saveAsTextFile(PhoneBook phonenook, String path) throws IOException {
  195. File f = new File(path);
  196. if (phonenook == null)
  197. return false;
  198. if (!f.exists())
  199. f.createNewFile();
  200. try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
  201. oos.writeObject(phonenook);
  202. oos.close();
  203. }
  204. return true;
  205. }
  206.  
  207. public static PhoneBook loadFromTextFile(String path) throws IOException, ClassNotFoundException, InvalidFormatException {
  208. File f = new File(path);
  209. if (!f.exists())
  210. throw new IOException();
  211. if (!f.canWrite())
  212. throw new InvalidFormatException();
  213. PhoneBook p = null;
  214. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
  215. p = (PhoneBook) ois.readObject();
  216. ois.close();
  217. }
  218. return p;
  219. }
  220.  
  221. public Contact[] getContactsForNumber(String number_prefix) {
  222. List<Contact> fillIt = new ArrayList<>();
  223. for (int i = 0; i < Contacts.size(); i++) {
  224. Contact c = Contacts.get(i);
  225. for(String number : c.getNumbers()) {
  226. if(number.startsWith(number_prefix)) {
  227. fillIt.add(c);
  228. }
  229. }
  230.  
  231. }
  232. fillIt.sort(Comparator.comparing(Contact::getName));
  233. return fillIt.stream().toArray(Contact[]::new);
  234. }
  235. }
  236.  
  237. public class PhonebookTester {
  238.  
  239. public static void main(String[] args) throws Exception {
  240. Scanner jin = new Scanner(System.in);
  241. String line = jin.nextLine();
  242. switch( line ) {
  243. case "test_contact":
  244. testContact(jin);
  245. break;
  246. case "test_phonebook_exceptions":
  247. testPhonebookExceptions(jin);
  248. break;
  249. case "test_usage":
  250. testUsage(jin);
  251. break;
  252. }
  253. }
  254.  
  255. private static void testFile(Scanner jin) throws Exception {
  256. PhoneBook phonebook = new PhoneBook();
  257. while ( jin.hasNextLine() )
  258. phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  259. String text_file = "phonebook.txt";
  260. PhoneBook.saveAsTextFile(phonebook,text_file);
  261. PhoneBook pb = PhoneBook.loadFromTextFile(text_file);
  262. if ( ! pb.equals(phonebook) ) System.out.println("Your file saving and loading doesn't seem to work right");
  263. else System.out.println("Your file saving and loading works great. Good job!");
  264. }
  265.  
  266. private static void testUsage(Scanner jin) throws Exception {
  267. PhoneBook phonebook = new PhoneBook();
  268. while ( jin.hasNextLine() ) {
  269. String command = jin.nextLine();
  270. switch ( command ) {
  271. case "add":
  272. phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  273. break;
  274. case "remove":
  275. phonebook.removeContact(jin.nextLine());
  276. break;
  277. case "print":
  278. System.out.println(phonebook.numberOfContacts());
  279. System.out.println(Arrays.toString(phonebook.getContacts()));
  280. System.out.println(phonebook.toString());
  281. break;
  282. case "get_name":
  283. System.out.println(phonebook.getContactForName(jin.nextLine()));
  284. break;
  285. case "get_number":
  286. System.out.println(Arrays.toString(phonebook.getContactsForNumber(jin.nextLine())));
  287. break;
  288. }
  289. }
  290. }
  291.  
  292. private static void testPhonebookExceptions(Scanner jin) {
  293. PhoneBook phonebook = new PhoneBook();
  294. boolean exception_thrown = false;
  295. try {
  296. while ( jin.hasNextLine() ) {
  297. phonebook.addContact(new Contact(jin.nextLine()));
  298. }
  299. } catch ( InvalidNameException e ) {
  300. System.out.println(e.name);
  301. exception_thrown = true;
  302. } catch ( Exception e ) {}
  303. if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw InvalidNameException");
  304. /*
  305. exception_thrown = false;
  306. try {
  307. phonebook.addContact(new Contact(jin.nextLine()));
  308. } catch ( MaximumSizeExceddedException e ) {
  309. exception_thrown = true;
  310. }
  311. catch ( Exception e ) {}
  312. if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw MaximumSizeExcededException");
  313. */
  314. }
  315.  
  316. private static void testContact(Scanner jin) throws Exception {
  317. boolean exception_thrown = true;
  318. String names_to_test[] = { "And\nrej","asd","AAAAAAAAAAAAAAAAAAAAAA","�ндрејA123213","Andrej#","Andrej<3"};
  319. for ( String name : names_to_test ) {
  320. try {
  321. new Contact(name);
  322. exception_thrown = false;
  323. } catch (InvalidNameException e) {
  324. exception_thrown = true;
  325. }
  326. if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNameException");
  327. }
  328. String numbers_to_test[] = { "+071718028","number","078asdasdasd","070asdqwe","070a56798","07045678a","123456789","074456798","073456798","079456798" };
  329. for ( String number : numbers_to_test ) {
  330. try {
  331. new Contact("Andrej",number);
  332. exception_thrown = false;
  333. } catch (InvalidNumberException e) {
  334. exception_thrown = true;
  335. }
  336. if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNumberException");
  337. }
  338. String nums[] = new String[10];
  339. for ( int i = 0 ; i < nums.length ; ++i ) nums[i] = getRandomLegitNumber();
  340. try {
  341. new Contact("Andrej",nums);
  342. exception_thrown = false;
  343. } catch (MaximumSizeExceddedException e) {
  344. exception_thrown = true;
  345. }
  346. if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw a MaximumSizeExceddedException");
  347. Random rnd = new Random(5);
  348. Contact contact = new Contact("Andrej",getRandomLegitNumber(rnd),getRandomLegitNumber(rnd),getRandomLegitNumber(rnd));
  349. System.out.println(contact.getName());
  350. System.out.println(Arrays.toString(contact.getNumbers()));
  351. System.out.println(contact.toString());
  352. contact.addNumber(getRandomLegitNumber(rnd));
  353. System.out.println(Arrays.toString(contact.getNumbers()));
  354. System.out.println(contact.toString());
  355. contact.addNumber(getRandomLegitNumber(rnd));
  356. System.out.println(Arrays.toString(contact.getNumbers()));
  357. System.out.println(contact.toString());
  358. }
  359.  
  360. static String[] legit_prefixes = {"070","071","072","075","076","077","078"};
  361. static Random rnd = new Random();
  362.  
  363. private static String getRandomLegitNumber() {
  364. return getRandomLegitNumber(rnd);
  365. }
  366.  
  367. private static String getRandomLegitNumber(Random rnd) {
  368. StringBuilder sb = new StringBuilder(legit_prefixes[rnd.nextInt(legit_prefixes.length)]);
  369. for ( int i = 3 ; i < 9 ; ++i )
  370. sb.append(rnd.nextInt(10));
  371. return sb.toString();
  372. }
  373.  
  374.  
  375. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement