Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.Random;
- import java.util.Scanner;
- import java.util.stream.IntStream;
- /*
- JSON Builder
- https://pastebin.com/jG70ZZzX
- */
- class InvalidNameException extends Exception {
- //Ovoj isklucok se frla dokolku dolzinata na imeto ne e od 5 do 10 karakteri,
- //ili imeto sodrzi karakteri koi ne se bukvi ili brojki.
- public String name;
- InvalidNameException(String name) {
- this.name = name;
- }
- }
- class InvalidNumberException extends Exception {
- InvalidNumberException() {
- super();
- }
- }
- class MaximumSizeExceddedException extends Exception {
- }
- class InvalidFormatException extends Exception {
- }
- class Contact implements Comparable<Contact> {
- private String name;
- private String phones[];
- private int size;
- Contact(String name, String... phoneNumber) throws InvalidNameException, InvalidNumberException, MaximumSizeExceddedException {
- if (!validName(name)) {
- throw new InvalidNameException(name);
- }
- if (phoneNumber.length > 5) {
- throw new MaximumSizeExceddedException();
- }
- this.name = name;
- this.phones = new String[phoneNumber.length];
- this.size = 0;
- for (int i = 0; i < phoneNumber.length; i++) {
- if (validNumber(phoneNumber[i])) {
- //System.out.println(phoneNumber[i]);
- this.phones[i] = phoneNumber[i];
- this.size++;
- } else {
- throw new InvalidNumberException();
- }
- }
- }
- public boolean validName(String name) {
- if (name.length() < 4 || name.length() > 10) {
- return false;
- }
- for (int i = 0; i < name.length(); i++) {
- if (!(Character.isLetterOrDigit(name.charAt(i)))) {
- return false;
- }
- }
- return true;
- }
- public boolean validNumber(String phoneNumber) {
- /* 0 1 2 5 6 7 8*/
- String prefixes[] = new String[]{"070", "071", "072", "075", "076", "077", "078"};
- if (phoneNumber.length() != 9) {
- return false;
- }
- for (int i = 0; i < phoneNumber.length(); i++) {
- if (!(Character.isDigit(phoneNumber.charAt(i)))) {
- return false;
- }
- }
- String prefix = phoneNumber.substring(0, 3);
- for (int i = 0; i < prefixes.length; i++) {
- if (prefix.equals(prefixes[i])) {
- return true;
- }
- }
- return false;
- }
- public String getName() {
- return name;
- }
- public String[] getNumbers() {
- String temp[] = Arrays.copyOf(phones, size);
- Arrays.sort(temp);
- return temp;
- }
- public void addNumber(String phoneNumber) throws InvalidNumberException {
- if (validNumber(phoneNumber)) {
- String temp[] = Arrays.copyOf(phones, size + 1);
- /* maybe phones.length + 1 */
- temp[size++] = phoneNumber;
- phones = temp;
- } else {
- throw new InvalidNumberException();
- }
- }
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append(name + "\n");
- sb.append(size + "\n");
- String temp[] = getNumbers();
- for (int i = 0; i < size; i++) {
- if (temp[i] != null) {
- sb.append(temp[i] + "\n");
- }
- }
- return sb.toString();
- }
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- Contact contact = (Contact) o;
- if (name != null ? !name.equals(contact.name) : contact.name != null) return false;
- // Probably incorrect - comparing Object[] arrays with Arrays.equals
- return Arrays.equals(phones, contact.phones);
- }
- @Override
- public int hashCode() {
- int result = name != null ? name.hashCode() : 0;
- result = 31 * result + Arrays.hashCode(phones);
- return result;
- }
- /*
- статички метод кој за дадена тексутална репрезентација на контактот ќе врати соодветен објект -
- доколку настане било каков проблем при претварањето од тексутална репрезентација во објект Contact
- треба да се фрли исклучок од тип InvalidFormatException
- */
- public static Contact valueOf(String string) throws InvalidFormatException {
- try {
- Scanner scanner = new Scanner(string);
- String name = scanner.next();
- int length = scanner.nextInt();
- String phones[] = new String[length];
- IntStream.range(0, length)
- .filter(i -> scanner.hasNext())
- .forEach(i -> phones[i] = scanner.next());
- return new Contact(name, phones);
- } catch (Exception e) {
- throw new InvalidFormatException();
- }
- }
- @Override
- public int compareTo(Contact contact) {
- return name.compareTo(contact.name);
- }
- }
- class PhoneBook {
- private Contact contacts[];
- private int size;
- PhoneBook() {
- contacts = new Contact[250];
- size = 0;
- }
- public boolean isUnique(Contact contact) {
- /* Unique name */
- //System.out.println("Inside Unique");
- for (int i = 0; i < size; i++) {
- //System.out.println("Inside Unique For");
- //System.out.println(contacts[i].getName() + " " + contact.getName() + " " + contacts[i].getName().equals(contact.getName()));
- if (contacts[i].getName().equals(contact.getName())) {
- return false;
- }
- }
- return true;
- }
- public void addContact(Contact contact) throws MaximumSizeExceddedException, InvalidNameException {
- if (size >= 250) {
- throw new MaximumSizeExceddedException();
- }
- if (!contact.validName(contact.getName())) {
- throw new InvalidNameException(contact.getName());
- }
- if (isUnique(contact)) {
- contacts[size++] = contact;
- } else {
- throw new InvalidNameException(contact.getName());
- }
- }
- public Contact getContactForName(String name) {
- for (int i = 0; i < size; i++) {
- /* Just name comparison, getName() is a String */
- if (contacts[i].getName().equals(name)) {
- return contacts[i];
- }
- }
- return null;
- }
- public int numberOfContacts() {
- return size;
- }
- public Contact[] getContacts() {
- Contact temp[] = Arrays.copyOf(contacts, size);
- /* Sort by name */
- /*for (int i = 0; i < contacts.length - 1; i++) {
- for (int j = 0; j < contacts.length - i - 1; j++) {
- if (contacts[j].)
- }
- }*/
- //Arrays.sort(temp, Comparator.comparing(Contact::getName));
- Arrays.sort(temp); /* same as above but works because I've implemented compareTo() */
- return temp;
- }
- public int indexContactFromArray(Contact contact) {
- for (int i = 0; i < size; i++) {
- if (contacts[i].equals(contact)) {
- return i;
- }
- }
- return -1;
- }
- public void avoidElement(Object array[], int index) {
- int elementsToMove = size - 1 - index;
- if (elementsToMove > 0) {
- /* This will copy the sub-array over the index element */
- System.arraycopy(array, index + 1, array, index, elementsToMove);
- }
- array[--size] = null;
- }
- public void removeContactFromArray(Contact contact) {
- /* Find its index */
- int index = indexContactFromArray(contact);
- if (index < 0 || index > size) {
- System.out.println("removeContactFromArray index out of bounds");
- }
- avoidElement(contacts, index);
- /*System.arraycopy(contacts, );
- Contact left[] = Arrays.copyOfRange(contacts, 0, index);
- Contact right[] = Arrays.copyOfRange(contacts, index + 1, size);
- Contact result[] = new Contact[left.length + right.length];
- int k = 0;
- for (int i = 0; i < left.length; i++) {
- result[k++] = left[i];
- }
- for (int i = 0; i < right.length; i++) {
- result[k++] = right[i];
- }
- *//* Change the actual array contacts *//*
- contacts = result;*/
- }
- public boolean removeContact(String name) {
- Contact temp = getContactForName(name);
- if (temp != null) {
- removeContactFromArray(temp);
- return true;
- } else {
- return false;
- }
- }
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- Contact sorted[] = getContacts();
- for (int i = 0; i < size; i++) {
- sb.append(sorted[i].toString() + "\n");
- }
- //sb.setLength(sb.length() - 1);
- return sb.toString();
- }
- /*public static boolean saveAsTextFile(PhoneBook phonebook,String path) throws IOException {
- try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(path),StandardOpenOption.CREATE)){
- phonebook.contacts.forEach
- }
- }*/
- static public boolean saveAsTextFile(PhoneBook phonebook, String path) throws IOException, FileNotFoundException {
- //try(PrintWriter pw = new PrintWriter(new FileWriter(path))){}
- try {
- File temp = new File(path);
- temp.createNewFile(); // if file already exists will do nothing
- PrintWriter pw = new PrintWriter(temp);
- pw.print(phonebook.toString());
- pw.flush();
- pw.close(); // flushes before close
- } catch (FileNotFoundException e) {
- return false;
- }
- return true;
- }
- static public PhoneBook loadFromTextFile(String path)
- throws IOException, InvalidFormatException, InvalidNumberException, InvalidNameException, MaximumSizeExceddedException {
- try (BufferedReader br = new BufferedReader(new FileReader(new File(path)))) {
- String current;
- PhoneBook phoneBook = new PhoneBook();
- while ((current = br.readLine()) != null) {
- String name = current;
- int len = Integer.parseInt(br.readLine());
- String phoneNumbers[] = new String[len];
- for (int i = 0; i < len; i++) {
- phoneNumbers[i] = br.readLine();
- }
- Contact contact = new Contact(name, phoneNumbers);
- phoneBook.addContact(contact);
- br.readLine();
- }
- return phoneBook;
- }
- }
- public Contact[] getContactsForNumber(String number_prefix) {
- Contact temp[] = new Contact[size];
- int k = 0;
- for (int i = 0; i < size; i++) {
- String numbers[] = contacts[i].getNumbers();
- for (int j = 0; j < numbers.length; j++) {
- String prefix = numbers[j].substring(0, 3);
- if (prefix.equals(number_prefix)) {
- /* Add the number to result, but check if it's unique */
- /* Unique name */
- temp[k++] = contacts[i];
- /* To avoid duplicates we should break */
- /* The phonebook should already be unique only */
- break;
- }
- }
- }
- Contact result[] = new Contact[k];
- for (int i = 0; i < k; i++) {
- result[i] = temp[i];
- }
- return result;
- }
- }
- public class PhonebookTester {
- public static void main(String[] args) throws Exception {
- Scanner jin = new Scanner(System.in);
- String line = jin.nextLine();
- switch (line) {
- case "test_contact":
- testContact(jin);
- break;
- case "test_phonebook_exceptions":
- testPhonebookExceptions(jin);
- break;
- case "test_usage":
- testUsage(jin);
- break;
- }
- }
- private static void testFile(Scanner jin) throws Exception {
- PhoneBook phonebook = new PhoneBook();
- while (jin.hasNextLine())
- phonebook.addContact(new Contact(jin.nextLine(), jin.nextLine().split("\\s++")));
- String text_file = "phonebook.txt";
- PhoneBook.saveAsTextFile(phonebook, text_file);
- PhoneBook pb = PhoneBook.loadFromTextFile(text_file);
- if (!pb.equals(phonebook)) System.out.println("Your file saving and loading doesn't seem to work right");
- else System.out.println("Your file saving and loading works great. Good job!");
- }
- private static void testUsage(Scanner jin) throws Exception {
- PhoneBook phonebook = new PhoneBook();
- while (jin.hasNextLine()) {
- String command = jin.nextLine();
- switch (command) {
- case "add":
- //System.out.println("\nADDING\n");
- phonebook.addContact(new Contact(jin.nextLine(), jin.nextLine().split("\\s++")));
- break;
- case "remove":
- phonebook.removeContact(jin.nextLine());
- break;
- case "print":
- //System.out.println("\nPRINTING\n");
- System.out.println(phonebook.numberOfContacts());
- System.out.println(Arrays.toString(phonebook.getContacts()));
- System.out.println(phonebook.toString());
- break;
- case "get_name":
- System.out.println(phonebook.getContactForName(jin.nextLine()));
- break;
- case "get_number":
- System.out.println(Arrays.toString(phonebook.getContactsForNumber(jin.nextLine())));
- break;
- }
- }
- }
- private static void testPhonebookExceptions(Scanner jin) {
- PhoneBook phonebook = new PhoneBook();
- boolean exception_thrown = false;
- try {
- while (jin.hasNextLine()) {
- phonebook.addContact(new Contact(jin.nextLine()));
- }
- } catch (InvalidNameException e) {
- System.out.println(e.name);
- exception_thrown = true;
- } catch (Exception e) {
- }
- if (!exception_thrown) System.out.println("Your addContact method doesn't throw InvalidNameException");
- /*
- exception_thrown = false;
- try {
- phonebook.addContact(new Contact(jin.nextLine()));
- } catch ( MaximumSizeExceddedException e ) {
- exception_thrown = true;
- }
- catch ( Exception e ) {}
- if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw MaximumSizeExcededException");
- */
- }
- private static void testContact(Scanner jin) throws Exception {
- boolean exception_thrown = true;
- String names_to_test[] = {"And\nrej", "asd", "AAAAAAAAAAAAAAAAAAAAAA", "�ндрејA123213", "Andrej#", "Andrej<3"};
- for (String name : names_to_test) {
- try {
- new Contact(name);
- exception_thrown = false;
- } catch (InvalidNameException e) {
- exception_thrown = true;
- }
- if (!exception_thrown) System.out.println("Your Contact constructor doesn't throw an InvalidNameException");
- }
- String numbers_to_test[] = {"+071718028", "number", "078asdasdasd", "070asdqwe", "070a56798", "07045678a", "123456789", "074456798", "073456798", "079456798"};
- for (String number : numbers_to_test) {
- try {
- new Contact("Andrej", number);
- exception_thrown = false;
- } catch (InvalidNumberException e) {
- exception_thrown = true;
- }
- if (!exception_thrown)
- System.out.println("Your Contact constructor doesn't throw an InvalidNumberException");
- }
- String nums[] = new String[10];
- for (int i = 0; i < nums.length; ++i) nums[i] = getRandomLegitNumber();
- try {
- new Contact("Andrej", nums);
- exception_thrown = false;
- } catch (MaximumSizeExceddedException e) {
- exception_thrown = true;
- }
- if (!exception_thrown)
- System.out.println("Your Contact constructor doesn't throw a MaximumSizeExceddedException");
- Random rnd = new Random(5);
- Contact contact = new Contact("Andrej", getRandomLegitNumber(rnd), getRandomLegitNumber(rnd), getRandomLegitNumber(rnd));
- System.out.println(contact.getName());
- System.out.println(Arrays.toString(contact.getNumbers()));
- System.out.println(contact.toString());
- contact.addNumber(getRandomLegitNumber(rnd));
- System.out.println(Arrays.toString(contact.getNumbers()));
- System.out.println(contact.toString());
- contact.addNumber(getRandomLegitNumber(rnd));
- System.out.println(Arrays.toString(contact.getNumbers()));
- System.out.println(contact.toString());
- }
- static String[] legit_prefixes = {"070", "071", "072", "075", "076", "077", "078"};
- static Random rnd = new Random();
- private static String getRandomLegitNumber() {
- return getRandomLegitNumber(rnd);
- }
- private static String getRandomLegitNumber(Random rnd) {
- StringBuilder sb = new StringBuilder(legit_prefixes[rnd.nextInt(legit_prefixes.length)]);
- for (int i = 3; i < 9; ++i)
- sb.append(rnd.nextInt(10));
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement