From 14ecb8dd65cd2aba47aec27b4220dadbf964aaea Mon Sep 17 00:00:00 2001 From: Drozdov Date: Sun, 11 Jul 2021 11:01:10 +0300 Subject: [PATCH 01/57] add homework_1 --- gradlew | 0 src/main/java/homework_1/Main.java | 13 +++++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) mode change 100644 => 100755 gradlew diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..6eecd089 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -2,8 +2,13 @@ public class Main { - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - + public static void main(String[] args) { + for (String arg : args) { + if (arg.equals("ошибка")) { + System.err.println("Тревога!"); + return; + } + System.out.println(arg + ": " + arg.length() + " букв"); + } + } } From c36f3b8bc4b75622cb861f9c6f471f59762fb016 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Sun, 11 Jul 2021 11:02:20 +0300 Subject: [PATCH 02/57] refactor README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5d686e9f..73d4a3d1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Drozdov Nikita* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From caa0d07456df9e8bc7353bcb903d1d61348d8a6f Mon Sep 17 00:00:00 2001 From: Drozdov Date: Sun, 11 Jul 2021 23:55:03 +0300 Subject: [PATCH 03/57] update homework_1 --- src/main/java/homework_1/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 6eecd089..e4933f45 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -6,7 +6,7 @@ public static void main(String[] args) { for (String arg : args) { if (arg.equals("ошибка")) { System.err.println("Тревога!"); - return; + break; } System.out.println(arg + ": " + arg.length() + " букв"); } From 0939a720e653e4984aff5f13fec91be33a76c790 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Mon, 12 Jul 2021 13:36:30 +0300 Subject: [PATCH 04/57] del serr, add "\033[0;31m" in sout --- src/main/java/homework_1/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index e4933f45..9830c089 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -5,7 +5,7 @@ public class Main { public static void main(String[] args) { for (String arg : args) { if (arg.equals("ошибка")) { - System.err.println("Тревога!"); + System.out.println("\033[0;31m" + "Тревога!" + "\033[0m"); break; } System.out.println(arg + ": " + arg.length() + " букв"); From 5321ff5569eb6694e1dc111f81b8dbad651ea736 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Thu, 15 Jul 2021 20:34:48 +0300 Subject: [PATCH 05/57] homework_2, 1st task done --- src/main/java/homework_2/task_1/Main.java | 30 ++++++++++ .../java/homework_2/task_1/TrafficLight.java | 56 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/main/java/homework_2/task_1/Main.java create mode 100644 src/main/java/homework_2/task_1/TrafficLight.java diff --git a/src/main/java/homework_2/task_1/Main.java b/src/main/java/homework_2/task_1/Main.java new file mode 100644 index 00000000..2b9aeb1a --- /dev/null +++ b/src/main/java/homework_2/task_1/Main.java @@ -0,0 +1,30 @@ +package homework_2.task_1; + +import java.util.Scanner; + +import static homework_2.task_1.TrafficLight.ANSI_RED; +import static homework_2.task_1.TrafficLight.ANSI_RESET; + +public class Main { + public static void main(String[] args) { + TrafficLight trafficLight = new TrafficLight(); + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter the number (-1 for exit)"); + while (scanner.hasNext()) { + if (scanner.hasNextInt()) { + trafficLight.setNumberOfSeconds(scanner.nextInt()); + if (!trafficLight.go()) { + break; + } + } else { + String s = scanner.next(); + //TODO hh:mm:ss input format + + System.out.println(ANSI_RED + "Please, enter the valid number" + ANSI_RESET); + } + System.out.println("Enter the number (-1 for exit)"); + } + scanner.close(); + } +} diff --git a/src/main/java/homework_2/task_1/TrafficLight.java b/src/main/java/homework_2/task_1/TrafficLight.java new file mode 100644 index 00000000..e4e530c8 --- /dev/null +++ b/src/main/java/homework_2/task_1/TrafficLight.java @@ -0,0 +1,56 @@ +package homework_2.task_1; + +public class TrafficLight { + + public static final String ANSI_RESET = "\033[0m"; + public static final String ANSI_RED_BACKGROUND = "\u001B[41m"; + public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; + public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; + public static final String ANSI_RED = "\u001B[31m"; + + private int numberOfSeconds; + + public TrafficLight() { + } + + public TrafficLight(int numberOfSeconds) { + } + + public void setNumberOfSeconds(int numberOfSeconds) { + this.numberOfSeconds = numberOfSeconds; + } + + public boolean go() { + return checkEnter(); + } + + private boolean checkEnter() { + if (numberOfSeconds == -1) { + return false; + } + if (numberOfSeconds < 0) { + System.out.println(ANSI_RED + "Number must be positive" + ANSI_RESET); + return true; + } + if (numberOfSeconds > 86399) { + System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); + return true; + } + getTrafficLight(numberOfSeconds); + return true; + } + + private void getTrafficLight(int light) { + light -= 60 * (light / 60); + if (light >= 0 && light < 35) { + System.out.println(ANSI_GREEN_BACKGROUND + "Green light" + ANSI_RESET); + } + if ((light >= 35 && light < 40) || (light >= 55 && light < 60)) { + System.out.println(ANSI_YELLOW_BACKGROUND + "Yellow light" + ANSI_RESET); + } + if (light >= 40 && light < 55) { + System.out.println(ANSI_RED_BACKGROUND + "Red light" + ANSI_RESET); + } + } +} + From b1fda1f6a469c6d780016232ab19c5200d8a3831 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Thu, 15 Jul 2021 20:35:10 +0300 Subject: [PATCH 06/57] homework_2, 2nd task done --- src/main/java/homework_2/task_2/Main.java | 29 +++++++++++++++++++ .../homework_2/task_2/PyramidPrinter.java | 20 +++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/main/java/homework_2/task_2/Main.java create mode 100644 src/main/java/homework_2/task_2/PyramidPrinter.java diff --git a/src/main/java/homework_2/task_2/Main.java b/src/main/java/homework_2/task_2/Main.java new file mode 100644 index 00000000..2c52624f --- /dev/null +++ b/src/main/java/homework_2/task_2/Main.java @@ -0,0 +1,29 @@ +package homework_2.task_2; + +import java.util.Scanner; + +/** + * todo Document type Main + */ + +import static homework_2.task_1.TrafficLight.ANSI_RED; +import static homework_2.task_1.TrafficLight.ANSI_RESET; + + +public class Main { + public static void main(String[] args) { + System.out.println("Enter the number"); + Scanner scanner = new Scanner(System.in); + + if (scanner.hasNextInt()) { + int n = scanner.nextInt(); + if (n > 0) { + PyramidPrinter.printPyramid(n); + } else { + System.out.println(ANSI_RED + "Not positive number" + ANSI_RESET); + } + } else { + System.out.println(ANSI_RED + "Not valid number" + ANSI_RESET); + } + } +} diff --git a/src/main/java/homework_2/task_2/PyramidPrinter.java b/src/main/java/homework_2/task_2/PyramidPrinter.java new file mode 100644 index 00000000..2eea280e --- /dev/null +++ b/src/main/java/homework_2/task_2/PyramidPrinter.java @@ -0,0 +1,20 @@ +package homework_2.task_2; + +/** + * todo Document type Pyramid + */ +public class PyramidPrinter { + + private PyramidPrinter() { + throw new IllegalStateException("Utility class"); + } + + public static void printPyramid(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } +} From 95f480ce750aa3a846bc5882b10da66cae0ad929 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 16 Jul 2021 08:38:08 +0300 Subject: [PATCH 07/57] homework_2, 1st task refactor --- src/main/java/homework_2/task_1/Main.java | 5 +++- .../java/homework_2/task_1/TrafficLight.java | 28 ++++++++----------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/main/java/homework_2/task_1/Main.java b/src/main/java/homework_2/task_1/Main.java index 2b9aeb1a..7f77c3fd 100644 --- a/src/main/java/homework_2/task_1/Main.java +++ b/src/main/java/homework_2/task_1/Main.java @@ -14,9 +14,12 @@ public static void main(String[] args) { while (scanner.hasNext()) { if (scanner.hasNextInt()) { trafficLight.setNumberOfSeconds(scanner.nextInt()); - if (!trafficLight.go()) { + if (trafficLight.getNumberOfSeconds() == -1) { break; } + if (trafficLight.checkEnter()) { + trafficLight.getTrafficLight(); + } } else { String s = scanner.next(); //TODO hh:mm:ss input format diff --git a/src/main/java/homework_2/task_1/TrafficLight.java b/src/main/java/homework_2/task_1/TrafficLight.java index e4e530c8..ad7165a4 100644 --- a/src/main/java/homework_2/task_1/TrafficLight.java +++ b/src/main/java/homework_2/task_1/TrafficLight.java @@ -16,39 +16,35 @@ public TrafficLight() { public TrafficLight(int numberOfSeconds) { } - public void setNumberOfSeconds(int numberOfSeconds) { - this.numberOfSeconds = numberOfSeconds; + public int getNumberOfSeconds() { + return numberOfSeconds; } - public boolean go() { - return checkEnter(); + public void setNumberOfSeconds(int numberOfSeconds) { + this.numberOfSeconds = numberOfSeconds; } - private boolean checkEnter() { - if (numberOfSeconds == -1) { - return false; - } + public boolean checkEnter() { if (numberOfSeconds < 0) { System.out.println(ANSI_RED + "Number must be positive" + ANSI_RESET); - return true; + return false; } if (numberOfSeconds > 86399) { System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); - return true; + return false; } - getTrafficLight(numberOfSeconds); return true; } - private void getTrafficLight(int light) { - light -= 60 * (light / 60); - if (light >= 0 && light < 35) { + public void getTrafficLight() { + numberOfSeconds -= 60 * (numberOfSeconds / 60); + if (numberOfSeconds >= 0 && numberOfSeconds < 35) { System.out.println(ANSI_GREEN_BACKGROUND + "Green light" + ANSI_RESET); } - if ((light >= 35 && light < 40) || (light >= 55 && light < 60)) { + if ((numberOfSeconds >= 35 && numberOfSeconds < 40) || (numberOfSeconds >= 55 && numberOfSeconds < 60)) { System.out.println(ANSI_YELLOW_BACKGROUND + "Yellow light" + ANSI_RESET); } - if (light >= 40 && light < 55) { + if (numberOfSeconds >= 40 && numberOfSeconds < 55) { System.out.println(ANSI_RED_BACKGROUND + "Red light" + ANSI_RESET); } } From 7ce3d3c85419c7a773e9d030c81132fc097a62e1 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 16 Jul 2021 10:13:16 +0300 Subject: [PATCH 08/57] homework_2, 3rd task done --- src/main/java/homework_2/task_3/Main.java | 31 ++++++++ .../homework_2/task_3/RandomCharsTable.java | 74 +++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 src/main/java/homework_2/task_3/Main.java create mode 100644 src/main/java/homework_2/task_3/RandomCharsTable.java diff --git a/src/main/java/homework_2/task_3/Main.java b/src/main/java/homework_2/task_3/Main.java new file mode 100644 index 00000000..0a8c8ab5 --- /dev/null +++ b/src/main/java/homework_2/task_3/Main.java @@ -0,0 +1,31 @@ +package homework_2.task_3; + +import java.util.Scanner; + +import static homework_2.task_1.TrafficLight.ANSI_RED; +import static homework_2.task_1.TrafficLight.ANSI_RESET; + +/** + * todo Document type Main + */ +public class Main { + public static void main(String[] args) { + Scanner systemScanner = new Scanner(System.in); + Scanner stringScanner; + RandomCharsTable randomCharsTable; + + System.out.println("Enter width, height and parity"); + while (systemScanner.hasNext()) { + String s = systemScanner.nextLine(); + if (s.matches("^(([1-9][0-9]*\\s){2})(odd|even)")) { + stringScanner = new Scanner(s); + randomCharsTable = new RandomCharsTable(stringScanner.nextInt(), stringScanner.nextInt(), stringScanner.next()); + randomCharsTable.getResult(); + } else { + System.out.println(ANSI_RED + "\nYou entered not valid height, width or parity" + ANSI_RESET); + } + System.out.println("\nEnter width, height and parity"); + } + systemScanner.close(); + } +} diff --git a/src/main/java/homework_2/task_3/RandomCharsTable.java b/src/main/java/homework_2/task_3/RandomCharsTable.java new file mode 100644 index 00000000..e9c25ba2 --- /dev/null +++ b/src/main/java/homework_2/task_3/RandomCharsTable.java @@ -0,0 +1,74 @@ +package homework_2.task_3; + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; +import java.util.Random; + +/** + * todo Document type RandomCharsTable + */ +public class RandomCharsTable { + private int height; + private int width; + private String parity; + private char[][] chars; + private List characterList = new ArrayList<>(); + + public RandomCharsTable() { + } + + public RandomCharsTable(int height, int w, String parity) { + this.height = height; + this.width = w; + this.parity = parity; + initTable(); + } + + public void initTable() { + chars = new char[height][width]; + Random random = new Random(); + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { + chars[i][j] = (char) (random.nextInt(26) + 65); + checkChar(i, j); + } + } + } + + public void printTable() { + for (int i = 0; i < height; i++) { + System.out.print("|"); + for (int j = 0; j < width; j++) { + System.out.print(chars[i][j] + "|"); + } + System.out.println(); + } + } + + public void getResult() { + printTable(); + ListIterator characterListIterator = characterList.listIterator(); + System.out.print(parity + " letter(s) - "); + while (characterListIterator.hasNext()) { + System.out.print(characterListIterator.next()); + if (characterListIterator.hasNext()) { + System.out.print(", "); + } else { + System.out.println(); + } + } + } + + private void checkChar(int i, int j) { + if (parity.equals("even")) { + if (chars[i][j] % 2 == 0) { + characterList.add(chars[i][j]); + } + } else { + if (chars[i][j] % 2 == 1) { + characterList.add(chars[i][j]); + } + } + } +} From f5158aba09c4e289aadfb941039f0c7fb81e0274 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 16 Jul 2021 11:09:42 +0300 Subject: [PATCH 09/57] update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 73d4a3d1..611d0922 100644 --- a/README.md +++ b/README.md @@ -5,5 +5,6 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_1)
[PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_2)
[RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_3)| The app that reads input args and prints current traffic light
The app that reads input integer and prints "x" pyramid
The app that reads input arg, generate chars table and prints odd/even letters | [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 342868e48b63cd765b3c121fcf325d203c26c497 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Mon, 19 Jul 2021 22:49:38 +0300 Subject: [PATCH 10/57] update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 611d0922..15275edf 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,5 @@ | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | | HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_1)
[PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_2)
[RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_3)| The app that reads input args and prints current traffic light
The app that reads input integer and prints "x" pyramid
The app that reads input arg, generate chars table and prints odd/even letters | -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)
+[Link to сodingBat](https://codingbat.com/done?user=ndrozdov9@gmail.com&tag=8408048475) From e39ae9ab8ad9acd2003f861164d976c99f96fa8a Mon Sep 17 00:00:00 2001 From: Drozdov Date: Wed, 21 Jul 2021 04:35:33 +0300 Subject: [PATCH 11/57] refactor TrafficLight --- src/main/java/homework_2/task_1/Main.java | 33 ------------ .../java/homework_2/task_1/TrafficLight.java | 52 ------------------- .../java/homework_2/traffic_light/Main.java | 8 +++ .../traffic_light/TrafficLight.java | 51 ++++++++++++++++++ .../traffic_light/TrafficLightExtraMode.java | 33 ++++++++++++ 5 files changed, 92 insertions(+), 85 deletions(-) delete mode 100644 src/main/java/homework_2/task_1/Main.java delete mode 100644 src/main/java/homework_2/task_1/TrafficLight.java create mode 100644 src/main/java/homework_2/traffic_light/Main.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLight.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java diff --git a/src/main/java/homework_2/task_1/Main.java b/src/main/java/homework_2/task_1/Main.java deleted file mode 100644 index 7f77c3fd..00000000 --- a/src/main/java/homework_2/task_1/Main.java +++ /dev/null @@ -1,33 +0,0 @@ -package homework_2.task_1; - -import java.util.Scanner; - -import static homework_2.task_1.TrafficLight.ANSI_RED; -import static homework_2.task_1.TrafficLight.ANSI_RESET; - -public class Main { - public static void main(String[] args) { - TrafficLight trafficLight = new TrafficLight(); - Scanner scanner = new Scanner(System.in); - - System.out.println("Enter the number (-1 for exit)"); - while (scanner.hasNext()) { - if (scanner.hasNextInt()) { - trafficLight.setNumberOfSeconds(scanner.nextInt()); - if (trafficLight.getNumberOfSeconds() == -1) { - break; - } - if (trafficLight.checkEnter()) { - trafficLight.getTrafficLight(); - } - } else { - String s = scanner.next(); - //TODO hh:mm:ss input format - - System.out.println(ANSI_RED + "Please, enter the valid number" + ANSI_RESET); - } - System.out.println("Enter the number (-1 for exit)"); - } - scanner.close(); - } -} diff --git a/src/main/java/homework_2/task_1/TrafficLight.java b/src/main/java/homework_2/task_1/TrafficLight.java deleted file mode 100644 index ad7165a4..00000000 --- a/src/main/java/homework_2/task_1/TrafficLight.java +++ /dev/null @@ -1,52 +0,0 @@ -package homework_2.task_1; - -public class TrafficLight { - - public static final String ANSI_RESET = "\033[0m"; - public static final String ANSI_RED_BACKGROUND = "\u001B[41m"; - public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; - public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; - public static final String ANSI_RED = "\u001B[31m"; - - private int numberOfSeconds; - - public TrafficLight() { - } - - public TrafficLight(int numberOfSeconds) { - } - - public int getNumberOfSeconds() { - return numberOfSeconds; - } - - public void setNumberOfSeconds(int numberOfSeconds) { - this.numberOfSeconds = numberOfSeconds; - } - - public boolean checkEnter() { - if (numberOfSeconds < 0) { - System.out.println(ANSI_RED + "Number must be positive" + ANSI_RESET); - return false; - } - if (numberOfSeconds > 86399) { - System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); - return false; - } - return true; - } - - public void getTrafficLight() { - numberOfSeconds -= 60 * (numberOfSeconds / 60); - if (numberOfSeconds >= 0 && numberOfSeconds < 35) { - System.out.println(ANSI_GREEN_BACKGROUND + "Green light" + ANSI_RESET); - } - if ((numberOfSeconds >= 35 && numberOfSeconds < 40) || (numberOfSeconds >= 55 && numberOfSeconds < 60)) { - System.out.println(ANSI_YELLOW_BACKGROUND + "Yellow light" + ANSI_RESET); - } - if (numberOfSeconds >= 40 && numberOfSeconds < 55) { - System.out.println(ANSI_RED_BACKGROUND + "Red light" + ANSI_RESET); - } - } -} - diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..f32d7f1f --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,8 @@ +package homework_2.traffic_light; + +public class Main { + + public static void main(String[] args) { + new TrafficLight().start(); + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..4efd31bb --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,51 @@ +package homework_2.traffic_light; + +import java.util.Scanner; + +public class TrafficLight { + + protected static final String ANSI_RESET = "\033[0m"; + protected static final String ANSI_RED = "\u001B[31m"; + protected static final String ANSI_RED_BACKGROUND = "\u001B[41m"; + protected static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; + protected static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; + + public void start() { + System.out.println("Enter the number"); + Scanner scanner = new Scanner(System.in); + String inputStr = scanner.nextLine(); + if (isValid(inputStr)) { + inputStr = inputStr.replaceAll("\\s+", ""); + System.out.println(getTrafficLight(Integer.parseInt(inputStr))); + } + scanner.close(); + } + + protected boolean isValid(String arg) { + if (!arg.matches("^\\s*[+]?[1-9][0-9]*\\s*$")) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter" + ANSI_RESET); + return false; + } + + if (Integer.parseInt(arg) > 86399) { + System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); + return false; + } + return true; + } + + protected String getTrafficLight(int numberOfSeconds) { + int cutNumberOfSeconds = numberOfSeconds - 60 * (numberOfSeconds / 60); + if (cutNumberOfSeconds >= 0 && cutNumberOfSeconds < 35) { + return ANSI_GREEN_BACKGROUND + "Green light" + ANSI_RESET; + } + if ((cutNumberOfSeconds >= 35 && cutNumberOfSeconds < 40) || (cutNumberOfSeconds >= 55 && cutNumberOfSeconds < 60)) { + return ANSI_YELLOW_BACKGROUND + "Yellow light" + ANSI_RESET; + } + if (cutNumberOfSeconds >= 40 && cutNumberOfSeconds < 55) { + return ANSI_RED_BACKGROUND + "Red light" + ANSI_RESET; + } + return "Something went wrong"; + } +} + diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java new file mode 100644 index 00000000..df478da2 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -0,0 +1,33 @@ +package homework_2.traffic_light; + +import java.time.DateTimeException; +import java.time.LocalTime; +import java.util.Scanner; + +/** + * todo Document type TrafficLightExtraMode + */ +public class TrafficLightExtraMode extends TrafficLight { + + @Override + public void start() { + System.out.println("Enter the number"); + Scanner scanner = new Scanner(System.in); + String inputStr = scanner.nextLine(); + if (isValid(inputStr)) { + System.out.println(getTrafficLight(LocalTime.parse(inputStr).toSecondOfDay())); + } + scanner.close(); + } + + @Override + public boolean isValid(String arg) { + try { + LocalTime.parse(arg).toSecondOfDay(); + return true; + } catch (DateTimeException exception) { + System.out.println(ANSI_RED + "Only hh:mm:ss input format (hh < 24, mm < 60, ss < 60)" + ANSI_RESET); + return false; + } + } +} From 9bfa59f4b584f46cdf952bc6e6463cafebc909a1 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Wed, 21 Jul 2021 04:36:24 +0300 Subject: [PATCH 12/57] refactor PyramidPrinter --- .../java/homework_2/pyramid_printer/Main.java | 8 +++++ .../pyramid_printer/PyramidPrinter.java | 36 +++++++++++++++++++ src/main/java/homework_2/task_2/Main.java | 29 --------------- .../homework_2/task_2/PyramidPrinter.java | 20 ----------- 4 files changed, 44 insertions(+), 49 deletions(-) create mode 100644 src/main/java/homework_2/pyramid_printer/Main.java create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinter.java delete mode 100644 src/main/java/homework_2/task_2/Main.java delete mode 100644 src/main/java/homework_2/task_2/PyramidPrinter.java diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..b75b7821 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,8 @@ +package homework_2.pyramid_printer; + +public class Main { + + public static void main(String[] args) { + new PyramidPrinter().start(); + } +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java new file mode 100644 index 00000000..baa930a2 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,36 @@ +package homework_2.pyramid_printer; + +import java.util.Scanner; + +public class PyramidPrinter { + + protected static final String ANSI_RESET = "\033[0m"; + protected static final String ANSI_RED = "\u001B[31m"; + + public void start() { + System.out.println("Enter the number"); + Scanner scanner = new Scanner(System.in); + String inputStr = scanner.nextLine(); + if (isValid(inputStr)) { + printPyramid(Integer.parseInt(inputStr)); + } + scanner.close(); + } + + private boolean isValid(String arg) { + if (!arg.matches("^\\s*[+]?[0-9]+\\s*$")) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter" + ANSI_RESET); + return false; + } + return true; + } + + private void printPyramid(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } +} diff --git a/src/main/java/homework_2/task_2/Main.java b/src/main/java/homework_2/task_2/Main.java deleted file mode 100644 index 2c52624f..00000000 --- a/src/main/java/homework_2/task_2/Main.java +++ /dev/null @@ -1,29 +0,0 @@ -package homework_2.task_2; - -import java.util.Scanner; - -/** - * todo Document type Main - */ - -import static homework_2.task_1.TrafficLight.ANSI_RED; -import static homework_2.task_1.TrafficLight.ANSI_RESET; - - -public class Main { - public static void main(String[] args) { - System.out.println("Enter the number"); - Scanner scanner = new Scanner(System.in); - - if (scanner.hasNextInt()) { - int n = scanner.nextInt(); - if (n > 0) { - PyramidPrinter.printPyramid(n); - } else { - System.out.println(ANSI_RED + "Not positive number" + ANSI_RESET); - } - } else { - System.out.println(ANSI_RED + "Not valid number" + ANSI_RESET); - } - } -} diff --git a/src/main/java/homework_2/task_2/PyramidPrinter.java b/src/main/java/homework_2/task_2/PyramidPrinter.java deleted file mode 100644 index 2eea280e..00000000 --- a/src/main/java/homework_2/task_2/PyramidPrinter.java +++ /dev/null @@ -1,20 +0,0 @@ -package homework_2.task_2; - -/** - * todo Document type Pyramid - */ -public class PyramidPrinter { - - private PyramidPrinter() { - throw new IllegalStateException("Utility class"); - } - - public static void printPyramid(int n) { - for (int i = 1; i <= n; i++) { - for (int j = 1; j <= i; j++) { - System.out.print("x"); - } - System.out.println(); - } - } -} From 248fc444cd613a5c51a05af7663757c8bd1d4c8f Mon Sep 17 00:00:00 2001 From: Drozdov Date: Wed, 21 Jul 2021 04:37:06 +0300 Subject: [PATCH 13/57] refactor RandomCharsTable --- .../homework_2/random_chars_table/Main.java | 13 +++ .../random_chars_table/RandomCharsTable.java | 79 +++++++++++++++++++ .../RandomCharsTableCreator.java | 26 ++++++ src/main/java/homework_2/task_3/Main.java | 31 -------- .../homework_2/task_3/RandomCharsTable.java | 74 ----------------- 5 files changed, 118 insertions(+), 105 deletions(-) create mode 100644 src/main/java/homework_2/random_chars_table/Main.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTable.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java delete mode 100644 src/main/java/homework_2/task_3/Main.java delete mode 100644 src/main/java/homework_2/task_3/RandomCharsTable.java diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..57caf02b --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,13 @@ +package homework_2.random_chars_table; + +import java.util.Scanner; + +/** + * todo Document type Main + */ +public class Main { + + public static void main(String[] args) { + new RandomCharsTable().start(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..9998f94e --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,79 @@ +package homework_2.random_chars_table; + +import java.util.*; + +public class RandomCharsTable { + + protected static final String ANSI_RED = "\u001B[31m"; + protected static final String ANSI_RESET = "\033[0m"; + + public void start() { + Scanner systemScanner = new Scanner(System.in); + Scanner stringScanner; + char[][] chars; + String parity; + List characterList; + + System.out.println("Enter width, height and parity"); + String s = systemScanner.nextLine(); + if (s.matches("^(([1-9][0-9]*\\s){2})(odd|even)")) { + stringScanner = new Scanner(s); + chars = RandomCharsTableCreator.initTable(stringScanner.nextInt(), stringScanner.nextInt()); + parity = stringScanner.next(); + characterList = checkChars(chars, parity); + + printTable(chars); + System.out.println(parity + " letter(s) - " + getResult(characterList)); + stringScanner.close(); + } else { + System.out.println(ANSI_RED + "Passed parameters should match the format [positive integer] [positive integer] [even|odd]" + ANSI_RESET); + } + + systemScanner.close(); + } + + public void printTable(char[][] chars) { + for (char[] aChar : chars) { + System.out.print("|"); + for (char c : aChar) { + System.out.print(c + "|"); + } + System.out.println(); + } + } + + protected String getResult(List characterList) { + StringBuilder stringBuilder = new StringBuilder(); + ListIterator characterListIterator = characterList.listIterator(); + + while (characterListIterator.hasNext()) { + stringBuilder.append(characterListIterator.next()); + if (characterListIterator.hasNext()) { + stringBuilder.append(", "); + } else { + stringBuilder.append("\n"); + } + } + return stringBuilder.toString(); + } + + protected List checkChars(char[][] chars, String parity) { + List characterList = new ArrayList<>(); + + for (char[] aChar : chars) { + for (char c : aChar) { + if (parity.equals("even")) { + if (c % 2 == 0) { + characterList.add(c); + } + } else { + if (c % 2 == 1) { + characterList.add(c); + } + } + } + } + + return characterList; + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java new file mode 100644 index 00000000..48ab9359 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -0,0 +1,26 @@ +package homework_2.random_chars_table; + +import java.util.Random; + +/** + * todo Document type RandomCharsTableCreator + */ +public class RandomCharsTableCreator { + + private RandomCharsTableCreator() { + throw new IllegalStateException("Utility class"); + } + + public static char[][] initTable(int height, int width) { + char[][] chars = new char[height][width]; + Random random = new Random(); + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { + chars[i][j] = (char) (random.nextInt(26) + 65); + } + } + + return chars; + } + +} diff --git a/src/main/java/homework_2/task_3/Main.java b/src/main/java/homework_2/task_3/Main.java deleted file mode 100644 index 0a8c8ab5..00000000 --- a/src/main/java/homework_2/task_3/Main.java +++ /dev/null @@ -1,31 +0,0 @@ -package homework_2.task_3; - -import java.util.Scanner; - -import static homework_2.task_1.TrafficLight.ANSI_RED; -import static homework_2.task_1.TrafficLight.ANSI_RESET; - -/** - * todo Document type Main - */ -public class Main { - public static void main(String[] args) { - Scanner systemScanner = new Scanner(System.in); - Scanner stringScanner; - RandomCharsTable randomCharsTable; - - System.out.println("Enter width, height and parity"); - while (systemScanner.hasNext()) { - String s = systemScanner.nextLine(); - if (s.matches("^(([1-9][0-9]*\\s){2})(odd|even)")) { - stringScanner = new Scanner(s); - randomCharsTable = new RandomCharsTable(stringScanner.nextInt(), stringScanner.nextInt(), stringScanner.next()); - randomCharsTable.getResult(); - } else { - System.out.println(ANSI_RED + "\nYou entered not valid height, width or parity" + ANSI_RESET); - } - System.out.println("\nEnter width, height and parity"); - } - systemScanner.close(); - } -} diff --git a/src/main/java/homework_2/task_3/RandomCharsTable.java b/src/main/java/homework_2/task_3/RandomCharsTable.java deleted file mode 100644 index e9c25ba2..00000000 --- a/src/main/java/homework_2/task_3/RandomCharsTable.java +++ /dev/null @@ -1,74 +0,0 @@ -package homework_2.task_3; - -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; -import java.util.Random; - -/** - * todo Document type RandomCharsTable - */ -public class RandomCharsTable { - private int height; - private int width; - private String parity; - private char[][] chars; - private List characterList = new ArrayList<>(); - - public RandomCharsTable() { - } - - public RandomCharsTable(int height, int w, String parity) { - this.height = height; - this.width = w; - this.parity = parity; - initTable(); - } - - public void initTable() { - chars = new char[height][width]; - Random random = new Random(); - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j++) { - chars[i][j] = (char) (random.nextInt(26) + 65); - checkChar(i, j); - } - } - } - - public void printTable() { - for (int i = 0; i < height; i++) { - System.out.print("|"); - for (int j = 0; j < width; j++) { - System.out.print(chars[i][j] + "|"); - } - System.out.println(); - } - } - - public void getResult() { - printTable(); - ListIterator characterListIterator = characterList.listIterator(); - System.out.print(parity + " letter(s) - "); - while (characterListIterator.hasNext()) { - System.out.print(characterListIterator.next()); - if (characterListIterator.hasNext()) { - System.out.print(", "); - } else { - System.out.println(); - } - } - } - - private void checkChar(int i, int j) { - if (parity.equals("even")) { - if (chars[i][j] % 2 == 0) { - characterList.add(chars[i][j]); - } - } else { - if (chars[i][j] % 2 == 1) { - characterList.add(chars[i][j]); - } - } - } -} From a24124ed5a2db572b9ab37e74767f3886949735e Mon Sep 17 00:00:00 2001 From: Drozdov Date: Wed, 21 Jul 2021 05:22:40 +0300 Subject: [PATCH 14/57] add ImmutableClass --- .../java/homework_3/MyImmutableClass.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/main/java/homework_3/MyImmutableClass.java diff --git a/src/main/java/homework_3/MyImmutableClass.java b/src/main/java/homework_3/MyImmutableClass.java new file mode 100644 index 00000000..1e37380e --- /dev/null +++ b/src/main/java/homework_3/MyImmutableClass.java @@ -0,0 +1,55 @@ +package homework_3; + +import java.time.LocalDate; + +public final class MyImmutableClass { + private final String myName; + private final int myAge; + private final LocalDate myBirthday; + + public MyImmutableClass(String myName) { + this.myName = myName; + this.myAge = LocalDate.now().getYear(); + this.myBirthday = LocalDate.now(); + } + + public MyImmutableClass(String myName, int myAge) { + this.myName = myName; + this.myAge = myAge; + this.myBirthday = LocalDate.now(); + } + + public MyImmutableClass(String myName, int myAge, LocalDate myBirthday) { + this.myName = myName; + this.myAge = myAge; + this.myBirthday = myBirthday; + } + + public String getMyName() { + return myName; + } + + public int getMyAge() { + return myAge; + } + + public LocalDate getMyBirthday() { + return myBirthday; + } + + public MyImmutableClass myClone(MyImmutableClass myOldImmutableClass, String myNewName) { + return new MyImmutableClass(myNewName, myOldImmutableClass.getMyAge(), myOldImmutableClass.getMyBirthday()); + } + + public MyImmutableClass myClone(MyImmutableClass myOldImmutableClass, int myNewAge) { + return new MyImmutableClass(myOldImmutableClass.getMyName(), myNewAge, myOldImmutableClass.getMyBirthday()); + } + + public MyImmutableClass myClone(MyImmutableClass myOldImmutableClass, LocalDate myNewBirthday) { + return new MyImmutableClass(myOldImmutableClass.getMyName(), myOldImmutableClass.getMyAge(), myNewBirthday); + } + + public MyImmutableClass myClone(String myNewName, int myNewAge, LocalDate myNewBirthday) { + return new MyImmutableClass(myNewName, myNewAge, myNewBirthday); + } +} From eab5371d47ad02f554e5009f36beee743855fa18 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Thu, 22 Jul 2021 18:26:38 +0300 Subject: [PATCH 15/57] update TrafficLight --- .../java/homework_2/traffic_light/Main.java | 2 +- .../traffic_light/TrafficLight.java | 28 ++++++++++--------- .../traffic_light/TrafficLightExtraMode.java | 2 +- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index f32d7f1f..3ff7f428 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -3,6 +3,6 @@ public class Main { public static void main(String[] args) { - new TrafficLight().start(); + new TrafficLight().run(); } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 4efd31bb..4035ddfb 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -9,33 +9,35 @@ public class TrafficLight { protected static final String ANSI_RED_BACKGROUND = "\u001B[41m"; protected static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; protected static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; + private static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; - public void start() { + public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); String inputStr = scanner.nextLine(); if (isValid(inputStr)) { inputStr = inputStr.replaceAll("\\s+", ""); - System.out.println(getTrafficLight(Integer.parseInt(inputStr))); + try { + if (Integer.parseInt(inputStr) < 86400) { + System.out.println(getTrafficLight(Integer.parseInt(inputStr))); + } else { + System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); + } + } catch (NumberFormatException exception) { + System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); + } + } else { + System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); } scanner.close(); } protected boolean isValid(String arg) { - if (!arg.matches("^\\s*[+]?[1-9][0-9]*\\s*$")) { - System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter" + ANSI_RESET); - return false; - } - - if (Integer.parseInt(arg) > 86399) { - System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); - return false; - } - return true; + return arg.matches("^\\s*[+]?[0-9]*\\s*$"); } protected String getTrafficLight(int numberOfSeconds) { - int cutNumberOfSeconds = numberOfSeconds - 60 * (numberOfSeconds / 60); + int cutNumberOfSeconds = numberOfSeconds % 60; if (cutNumberOfSeconds >= 0 && cutNumberOfSeconds < 35) { return ANSI_GREEN_BACKGROUND + "Green light" + ANSI_RESET; } diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index df478da2..17f9f349 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -10,7 +10,7 @@ public class TrafficLightExtraMode extends TrafficLight { @Override - public void start() { + public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); String inputStr = scanner.nextLine(); From 2eabb9284212f0bfcb6c1d83b9967253af42cc4f Mon Sep 17 00:00:00 2001 From: Drozdov Date: Thu, 22 Jul 2021 18:27:06 +0300 Subject: [PATCH 16/57] update PyramidPrinter --- .../java/homework_2/pyramid_printer/Main.java | 2 +- .../pyramid_printer/PyramidPrinter.java | 26 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index b75b7821..71e33035 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -3,6 +3,6 @@ public class Main { public static void main(String[] args) { - new PyramidPrinter().start(); + new PyramidPrinter().run(); } } diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index baa930a2..3887404a 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -4,30 +4,34 @@ public class PyramidPrinter { - protected static final String ANSI_RESET = "\033[0m"; - protected static final String ANSI_RED = "\u001B[31m"; + private static final String ANSI_RESET = "\033[0m"; + private static final String ANSI_RED = "\u001B[31m"; + private static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; - public void start() { + public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); String inputStr = scanner.nextLine(); if (isValid(inputStr)) { - printPyramid(Integer.parseInt(inputStr)); + inputStr = inputStr.replaceAll("\\s+", ""); + try { + printPyramid(Integer.parseInt(inputStr)); + } catch (NumberFormatException exception) { + System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); + } + } else { + System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); } scanner.close(); } private boolean isValid(String arg) { - if (!arg.matches("^\\s*[+]?[0-9]+\\s*$")) { - System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter" + ANSI_RESET); - return false; - } - return true; + return arg.matches("^\\s*[+]?[0-9]+\\s*$"); } private void printPyramid(int n) { - for (int i = 1; i <= n; i++) { - for (int j = 1; j <= i; j++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < i + 1; j++) { System.out.print("x"); } System.out.println(); From 49edb4045252b20794d5e43c5009b01b660835ff Mon Sep 17 00:00:00 2001 From: Drozdov Date: Thu, 22 Jul 2021 18:28:02 +0300 Subject: [PATCH 17/57] update RandomCharsTable --- .../homework_2/random_chars_table/Main.java | 7 +-- .../random_chars_table/RandomCharsTable.java | 47 +++++++++---------- .../RandomCharsTableCreator.java | 3 -- 3 files changed, 23 insertions(+), 34 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java index 57caf02b..be586c4b 100644 --- a/src/main/java/homework_2/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -1,13 +1,8 @@ package homework_2.random_chars_table; -import java.util.Scanner; - -/** - * todo Document type Main - */ public class Main { public static void main(String[] args) { - new RandomCharsTable().start(); + new RandomCharsTable().run(); } } diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 9998f94e..7d3dc0ae 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -4,45 +4,42 @@ public class RandomCharsTable { - protected static final String ANSI_RED = "\u001B[31m"; - protected static final String ANSI_RESET = "\033[0m"; + private static final String ANSI_RED = "\u001B[31m"; + private static final String ANSI_RESET = "\033[0m"; + private static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; - public void start() { + public void run() { Scanner systemScanner = new Scanner(System.in); - Scanner stringScanner; - char[][] chars; - String parity; - List characterList; System.out.println("Enter width, height and parity"); String s = systemScanner.nextLine(); if (s.matches("^(([1-9][0-9]*\\s){2})(odd|even)")) { - stringScanner = new Scanner(s); - chars = RandomCharsTableCreator.initTable(stringScanner.nextInt(), stringScanner.nextInt()); - parity = stringScanner.next(); - characterList = checkChars(chars, parity); + Scanner stringScanner = new Scanner(s); + char[][] chars = RandomCharsTableCreator.initTable(stringScanner.nextInt(), stringScanner.nextInt()); + String parity = stringScanner.next(); + List characterList = getValidChars(chars, parity); printTable(chars); - System.out.println(parity + " letter(s) - " + getResult(characterList)); + System.out.println(parity + " letters - " + getResult(characterList)); stringScanner.close(); } else { - System.out.println(ANSI_RED + "Passed parameters should match the format [positive integer] [positive integer] [even|odd]" + ANSI_RESET); + System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); } systemScanner.close(); } - public void printTable(char[][] chars) { - for (char[] aChar : chars) { + public void printTable(char[][] arrayOfChars) { + for (char[] chars : arrayOfChars) { System.out.print("|"); - for (char c : aChar) { - System.out.print(c + "|"); + for (char ch : chars) { + System.out.print(ch + "|"); } System.out.println(); } } - protected String getResult(List characterList) { + private String getResult(List characterList) { StringBuilder stringBuilder = new StringBuilder(); ListIterator characterListIterator = characterList.listIterator(); @@ -57,18 +54,18 @@ protected String getResult(List characterList) { return stringBuilder.toString(); } - protected List checkChars(char[][] chars, String parity) { + private List getValidChars(char[][] arrayOfChars, String parity) { List characterList = new ArrayList<>(); - for (char[] aChar : chars) { - for (char c : aChar) { + for (char[] chars : arrayOfChars) { + for (char ch : chars) { if (parity.equals("even")) { - if (c % 2 == 0) { - characterList.add(c); + if (ch % 2 == 0) { + characterList.add(ch); } } else { - if (c % 2 == 1) { - characterList.add(c); + if (ch % 2 == 1) { + characterList.add(ch); } } } diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java index 48ab9359..049a24dc 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -2,9 +2,6 @@ import java.util.Random; -/** - * todo Document type RandomCharsTableCreator - */ public class RandomCharsTableCreator { private RandomCharsTableCreator() { From 34779e9627b68111cd777dffc773e1e0555681bb Mon Sep 17 00:00:00 2001 From: Drozdov Date: Thu, 22 Jul 2021 18:28:27 +0300 Subject: [PATCH 18/57] update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 15275edf..c6f7f2a9 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | | HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_1)
[PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_2)
[RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_3)| The app that reads input args and prints current traffic light
The app that reads input integer and prints "x" pyramid
The app that reads input arg, generate chars table and prints odd/even letters | +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/DrozdovNikita/src/main/java/homework_3/MyImmutableClass.java) | | [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)
[Link to сodingBat](https://codingbat.com/done?user=ndrozdov9@gmail.com&tag=8408048475) From ceff88c0578d9f320976e20dd0a3cae45590cb97 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 23 Jul 2021 04:01:42 +0300 Subject: [PATCH 19/57] add UnitBaseMode.java --- src/test/java/base/UnitBaseMode.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/test/java/base/UnitBaseMode.java diff --git a/src/test/java/base/UnitBaseMode.java b/src/test/java/base/UnitBaseMode.java new file mode 100644 index 00000000..21d130b4 --- /dev/null +++ b/src/test/java/base/UnitBaseMode.java @@ -0,0 +1,24 @@ +package base; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * todo Document type UnitBaseMode + */ +public abstract class UnitBaseMode extends UnitBase { + + // can be used to invoke method for object your class under test + // 1st arg - obj your class under test, 2nd arg - called method, 3rd arg - message to remove from output + protected void run(Object object, String methodName, String stringToDel) { + try { + Method method = object.getClass().getMethod(methodName); + method.invoke(object); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + e.printStackTrace(); + } + + removeFromOutput(stringToDel); + } + +} From 2ba110a65e19d146646893cf035d85b30678018b Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 23 Jul 2021 04:02:47 +0300 Subject: [PATCH 20/57] add junit tests for TrafficLight, TrafficLightExtraMode --- .../TrafficLightExtraModeTest.java | 78 +++++++++++++++++++ .../traffic_light/TrafficLightTest.java | 65 ++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 src/test/java/homework_2/traffic_light/TrafficLightExtraModeTest.java create mode 100644 src/test/java/homework_2/traffic_light/TrafficLightTest.java diff --git a/src/test/java/homework_2/traffic_light/TrafficLightExtraModeTest.java b/src/test/java/homework_2/traffic_light/TrafficLightExtraModeTest.java new file mode 100644 index 00000000..f675b2ff --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightExtraModeTest.java @@ -0,0 +1,78 @@ +package homework_2.traffic_light; + +import base.UnitBaseMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +class TrafficLightExtraModeTest extends UnitBaseMode { + + private final TrafficLightExtraMode trafficLightExtraMode = new TrafficLightExtraMode(); + private final String METHOD_NAME = "run"; + private final String STRING_TO_DEL = "Enter the number"; + + @ParameterizedTest + @ValueSource(strings = { + "23:01:00", "15:00:08", "07:00:16", "00:00:24", + "21:02:02", "13:01:10", "05:01:18", "01:50:26", + "19:03:04", "11:02:12", "03:10:20", "10:59:28", + "17:04:06", "09:03:14", "23:00:22", "23:12:32" + }) + void runTestGreenLight(String input) { + setInput(input); + + run(trafficLightExtraMode, METHOD_NAME, STRING_TO_DEL); + + printOut(); + + assertTrue(getOutput().contains("Green light")); + } + + @ParameterizedTest + @ValueSource(strings = { + "23:59:35", "15:59:39", "07:59:58", "00:59:37", + "21:12:36", "13:59:55", "05:59:59", "01:59:38", + "19:34:37", "11:59:56", "03:59:35", "10:59:39", + "17:25:38", "09:59:57", "23:59:36", "12:59:35" + }) + void runTestYellowLight(String input) { + setInput(input); + + run(trafficLightExtraMode, METHOD_NAME, STRING_TO_DEL); + + printOut(); + + assertTrue(getOutput().contains("Yellow light")); + } + + @ParameterizedTest + @ValueSource(strings = { + "23:59:40", "15:59:44", "07:59:48", "00:59:52", + "21:12:41", "13:59:45", "05:59:49", "01:59:53", + "19:34:42", "11:59:46", "03:59:50", "10:59:54", + "17:25:43", "09:59:47", "23:59:51", "12:59:40" + }) + void runTestRedLight(String input) { + setInput(input); + + run(trafficLightExtraMode, METHOD_NAME, STRING_TO_DEL); + + printOut(); + + assertTrue(getOutput().contains("Red light")); + } + + @ParameterizedTest + @ValueSource(strings = { + "24:00:00", "00:60:01", "00:01:60", "01:0:00", "3:59:59", + "3:59:9", "359:59", "35959", "asd", ":59:59" + }) + void runTestInvalidArg(String input) { + setInput(input); + + run(trafficLightExtraMode, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Only hh:mm:ss input format (hh < 24, mm < 60, ss < 60)")); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java new file mode 100644 index 00000000..b6593e1c --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,65 @@ +package homework_2.traffic_light; + +import base.UnitBaseMode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * todo Document type TrafficLightTest + */ +class TrafficLightTest extends UnitBaseMode { + + private final TrafficLight trafficLight = new TrafficLight(); + private final String METHOD_NAME = "run"; + private final String STRING_TO_DEL = "Enter the number"; + + @ParameterizedTest + @ValueSource(strings = {"0", "5"}) + void runTestValidArg1(String input) { + setInput(input); + + run(trafficLight, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Green light")); + } + + @Test + void runTestValidArg2() { + setInput("35"); + + run(trafficLight, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Yellow light")); + } + + @Test + void runTestValidArg3() { + setInput("54"); + + run(trafficLight, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Red light")); + } + + @Test + void runTestValidArg4() { + setInput("86401"); + + run(trafficLight, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Day is over")); + } + + @ParameterizedTest + @ValueSource(strings = {"-12", "12345678901234567890123456", "asd"}) + void runTestInvalidArg(String inputString) { + setInput(inputString); + + run(trafficLight, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } +} \ No newline at end of file From a3548a920960b38e2de4ff2a161f6ab30f32d6d7 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 23 Jul 2021 04:03:20 +0300 Subject: [PATCH 21/57] add junit tests for 1st homework --- build.gradle | 1 + src/test/java/homework_1/MainTest.java | 60 ++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 src/test/java/homework_1/MainTest.java diff --git a/build.gradle b/build.gradle index b91dc843..522c2e14 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testCompile 'org.junit.jupiter:junit-jupiter-params:5.7.0' } test { diff --git a/src/test/java/homework_1/MainTest.java b/src/test/java/homework_1/MainTest.java new file mode 100644 index 00000000..a218bc8c --- /dev/null +++ b/src/test/java/homework_1/MainTest.java @@ -0,0 +1,60 @@ +package homework_1; + +import base.UnitBase; +import base.UnitBaseMode; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MainTest extends UnitBase { + + @Test + void mainTestValidArg() { + String[] inputArg = {"a", "aa", "aaa", "aaaa", "aaaaa"}; + + String[] expectedArray = { + "a: 1 букв", + "aa: 2 букв", + "aaa: 3 букв", + "aaaa: 4 букв", + "aaaaa: 5 букв"}; + Main.main(inputArg); + + assertArrayEquals(expectedArray, getOutputLines()); + } + + @Test + void mainTestValidArg2() { + String[] inputArg = {"1"}; + + String[] expectedArray = {"1: 1 букв"}; + Main.main(inputArg); + + assertArrayEquals(expectedArray, getOutputLines()); + } + + @Test + void mainTestEmptyArg() { + String[] inputArg = {}; + + Main.main(inputArg); + printOut(); + + assertEquals("", getOutput()); + } + + @Test + void mainTestWithErr() { + String[] inputArg = {"a", "aa", "aaa", "ошибка", "ааааа"}; + + String[] expectedArray = { + "a: 1 букв", + "aa: 2 букв", + "aaa: 3 букв", + "\033[0;31mТревога!\033[0m"}; + Main.main(inputArg); + + assertArrayEquals(expectedArray, getOutputLines()); + } +} \ No newline at end of file From f6e138f002fad5a479a32dfd54ab586eed2c3969 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 23 Jul 2021 04:04:29 +0300 Subject: [PATCH 22/57] add junit tests for PyramidPrinter --- .../pyramid_printer/PyramidPrinterTest.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..0fe17d85 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,67 @@ +package homework_2.pyramid_printer; + +import base.UnitBaseMode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * todo Document type PyramidPrinterTest + */ +class PyramidPrinterTest extends UnitBaseMode { + + private final PyramidPrinter pyramidPrinter = new PyramidPrinter(); + private final String METHOD_NAME = "run"; + private final String STRING_TO_DEL = "Enter the number"; + + @Test + void runTest() { + setInput("0"); + + run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); + + assertEquals("", getOutput()); + } + + @Test + void runTest1() { + setInput("1"); + + run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); + String[] expectedArray = {"x"}; + + assertArrayEquals(expectedArray, getOutputLines()); + } + + @Test + void runTest2() { + setInput("2"); + + run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); + String[] expectedArray = {"x", "xx"}; + + assertArrayEquals(expectedArray, getOutputLines()); + } + + @Test + void runTest10() { + setInput("10"); + + run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); + String[] expectedArray = {"x", "xx", "xxx", "xxxx", "xxxxx", "xxxxxx", "xxxxxxx", "xxxxxxxx", "xxxxxxxxx", "xxxxxxxxxx"}; + + assertArrayEquals(expectedArray, getOutputLines()); + } + + @ParameterizedTest + @ValueSource(strings = {"-1", "asd", "123456789012345678901234567890"}) + void runTestInvalidArg(String input) { + setInput(input); + + run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } +} \ No newline at end of file From c6cb7228a76b83d15b4e606f4b414599e3c62fa7 Mon Sep 17 00:00:00 2001 From: Drozdov Date: Fri, 23 Jul 2021 04:04:49 +0300 Subject: [PATCH 23/57] add junit tests for RandomCharsTable, RandomCharsTableCreator --- .../RandomCharsTableCreatorTest.java | 50 ++++++ .../RandomCharsTableTest.java | 163 ++++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java create mode 100644 src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java new file mode 100644 index 00000000..8440f7fd --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java @@ -0,0 +1,50 @@ +package homework_2.random_chars_table; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * todo Document type RandomCharsTableCreatorTest + */ +class RandomCharsTableCreatorTest { + + private List evenLettersArrayList; + private List oddLettersArrayList; + + @BeforeEach + void setUp() { + evenLettersArrayList = Arrays.asList(new Character[]{66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90}); + oddLettersArrayList = Arrays.asList(new Character[]{65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89}); + } + + @Test + void initTableTest1() { + char[][] charsTable = RandomCharsTableCreator.initTable(10, 20); + + assertEquals(10, charsTable.length); + for (char[] chars : charsTable) { + assertEquals(20, chars.length); + for (char ch : chars) { + assertTrue(evenLettersArrayList.contains(ch) || oddLettersArrayList.contains(ch)); + } + } + } + + @Test + void initTableTest2() { + char[][] charsTable = RandomCharsTableCreator.initTable(14, 124); + + assertEquals(14, charsTable.length); + for (char[] chars : charsTable) { + assertEquals(124, chars.length); + for (char ch : chars) { + assertTrue(evenLettersArrayList.contains(ch) || oddLettersArrayList.contains(ch)); + } + } + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..995d2a99 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,163 @@ +package homework_2.random_chars_table; + +import base.UnitBaseMode; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class RandomCharsTableTest extends UnitBaseMode { + + private final RandomCharsTable randomCharsTable = new RandomCharsTable(); + private final String METHOD_NAME = "run"; + private final String STRING_TO_DEL = "Enter width, height and parity"; + private List evenLettersArrayList; + private List oddLettersArrayList; + + @BeforeEach + void setUp() { + evenLettersArrayList = Arrays.asList(new Character[]{66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90}); + oddLettersArrayList = Arrays.asList(new Character[]{65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89}); + } + + @Test + void runTestValidArg() { + setInput("2 1 even"); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + printOut(); + + assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 1)); + assertTrue(isEvenLetters(getOutputLines()[getOutputLines().length - 1])); + assertEquals(2 + 1, getOutputLines().length); + assertTrue(getOutput().contains("even letters -")); + } + + @Test + void runTestValidArg2() { + setInput("1 2 even"); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + printOut(); + + assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 2)); + assertTrue(isEvenLetters(getOutputLines()[getOutputLines().length - 1])); + assertEquals(1 + 1, getOutputLines().length); + assertTrue(getOutput().contains("even letters -")); + } + + @Test + void runTestValidArg3() { + setInput("2 3 even"); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + printOut(); + + assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 3)); + assertTrue(isEvenLetters(getOutputLines()[getOutputLines().length - 1])); + assertEquals(2 + 1, getOutputLines().length); + assertTrue(getOutput().contains("even letters - ")); + } + + @Test + void runTestValidArg4() { + setInput("2 1 odd"); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + printOut(); + + assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 1)); + assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); + assertEquals(2 + 1, getOutputLines().length); + assertTrue(getOutput().contains("odd letters -")); + } + + @Test + void runTestValidArg5() { + setInput("1 2 odd"); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + printOut(); + + assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 2)); + assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); + assertEquals(1 + 1, getOutputLines().length); + assertTrue(getOutput().contains("odd letters -")); + } + + @Test + void runTestValidArg6() { + setInput("2 3 odd"); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + printOut(); + + assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 3)); + assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); + assertEquals(2 + 1, getOutputLines().length); + assertTrue(getOutput().contains("odd letters -")); + } + + @Test + void runTestValidArg7() { + setInput("10 20 odd"); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + printOut(); + + assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 20)); + assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); + assertEquals(10 + 1, getOutputLines().length); + assertTrue(getOutput().contains("odd letters -")); + } + + @ParameterizedTest + @ValueSource(strings = {"0 1 odd", "1 0 odd", "0 1 even", "1 0 even", "1 1 od", "0 odd", "odd", "-1 3 odd", "3 -1 even"}) + void runTestInvalidArg(String input) { + setInput(input); + + run(randomCharsTable, METHOD_NAME, STRING_TO_DEL); + + assertTrue(getOutput().contains("Passed parameters should match the format [positive integer] [positive integer] [even|odd]")); + } + + private boolean isValidLetters(String[] outputLines, int width) { + for (String s : outputLines) { + s = s.replaceAll("\\|+", ""); + if (s.length() != width) { + return false; + } + for (int i = 0; i < s.length(); i++) { + if (!evenLettersArrayList.contains(s.charAt(i)) && !oddLettersArrayList.contains(s.charAt(i))) { + return false; + } + } + } + return true; + } + + private boolean isEvenLetters(String lastString) { + lastString = lastString.replaceAll("(even letters -)|(\\s+)|(,+)", ""); + for (int i = 0; i < lastString.length(); i++) { + if (!evenLettersArrayList.contains(lastString.charAt(i)) && oddLettersArrayList.contains(lastString.charAt(i))) { + return false; + } + } + return true; + } + + private boolean isOddLetters(String lastString) { + lastString = lastString.replaceAll("(odd letters -)|(\\s+)|(,+)", ""); + for (int i = 0; i < lastString.length(); i++) { + if (!oddLettersArrayList.contains(lastString.charAt(i)) && evenLettersArrayList.contains(lastString.charAt(i))) { + return false; + } + } + return true; + } +} \ No newline at end of file From a1de00735ae4063230a9172f5a302564e736b5cf Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sun, 1 Aug 2021 03:10:04 +0300 Subject: [PATCH 24/57] refactor hw2 --- .../pyramid_printer/PyramidPrinter.java | 19 ++++++----- .../random_chars_table/RandomCharsTable.java | 12 ++++--- .../RandomCharsTableCreator.java | 10 +++--- .../traffic_light/TrafficLight.java | 33 +++++++++++-------- .../traffic_light/TrafficLightExtraMode.java | 12 +++---- 5 files changed, 49 insertions(+), 37 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 3887404a..017263d9 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -11,14 +11,9 @@ public class PyramidPrinter { public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); - String inputStr = scanner.nextLine(); + String inputStr = scanner.nextLine().trim(); if (isValid(inputStr)) { - inputStr = inputStr.replaceAll("\\s+", ""); - try { - printPyramid(Integer.parseInt(inputStr)); - } catch (NumberFormatException exception) { - System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); - } + printPyramid(Integer.parseInt(inputStr)); } else { System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); } @@ -26,7 +21,15 @@ public void run() { } private boolean isValid(String arg) { - return arg.matches("^\\s*[+]?[0-9]+\\s*$"); + if (arg.matches("^\\s*[+]?[0-9]+\\s*$")) { + try { + Integer.parseInt(arg); + } catch (NumberFormatException exception) { + return false; + } + return true; + } + return false; } private void printPyramid(int n) { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 7d3dc0ae..9d2f3a34 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -13,13 +13,13 @@ public void run() { System.out.println("Enter width, height and parity"); String s = systemScanner.nextLine(); - if (s.matches("^(([1-9][0-9]*\\s){2})(odd|even)")) { + if (isValid(s)) { Scanner stringScanner = new Scanner(s); - char[][] chars = RandomCharsTableCreator.initTable(stringScanner.nextInt(), stringScanner.nextInt()); + char[][] table = RandomCharsTableCreator.initAndFillTable(stringScanner.nextInt(), stringScanner.nextInt()); String parity = stringScanner.next(); - List characterList = getValidChars(chars, parity); + List characterList = getValidChars(table, parity); - printTable(chars); + printTable(table); System.out.println(parity + " letters - " + getResult(characterList)); stringScanner.close(); } else { @@ -29,6 +29,10 @@ public void run() { systemScanner.close(); } + private boolean isValid(String inputStr) { + return inputStr.matches("^(([1-9][0-9]*\\s){2})(odd|even)"); + } + public void printTable(char[][] arrayOfChars) { for (char[] chars : arrayOfChars) { System.out.print("|"); diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java index 049a24dc..36f5fc61 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -2,22 +2,22 @@ import java.util.Random; -public class RandomCharsTableCreator { +public final class RandomCharsTableCreator { private RandomCharsTableCreator() { throw new IllegalStateException("Utility class"); } - public static char[][] initTable(int height, int width) { - char[][] chars = new char[height][width]; + public static char[][] initAndFillTable(int height, int width) { + char[][] table = new char[height][width]; Random random = new Random(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { - chars[i][j] = (char) (random.nextInt(26) + 65); + table[i][j] = (char) (random.nextInt(26) + 65); } } - return chars; + return table; } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 4035ddfb..81dc6460 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -14,17 +14,14 @@ public class TrafficLight { public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); - String inputStr = scanner.nextLine(); + String inputStr = scanner.nextLine().trim(); if (isValid(inputStr)) { - inputStr = inputStr.replaceAll("\\s+", ""); - try { - if (Integer.parseInt(inputStr) < 86400) { - System.out.println(getTrafficLight(Integer.parseInt(inputStr))); - } else { - System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); - } - } catch (NumberFormatException exception) { - System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); + if (Integer.parseInt(inputStr) < 86400) { + int seconds = Integer.parseInt(inputStr); + String result = getTrafficLight(seconds); + System.out.println(result); + } else { + System.out.println(ANSI_RED + "Day is over" + ANSI_RESET); } } else { System.out.println(ANSI_RED + ERROR_MESSAGE + ANSI_RESET); @@ -33,18 +30,26 @@ public void run() { } protected boolean isValid(String arg) { - return arg.matches("^\\s*[+]?[0-9]*\\s*$"); + if (arg.matches("^\\s*[+]?[0-9]*\\s*$")) { + try { + Integer.parseInt(arg); + } catch (NumberFormatException exception) { + return false; + } + return true; + } + return false; } protected String getTrafficLight(int numberOfSeconds) { int cutNumberOfSeconds = numberOfSeconds % 60; - if (cutNumberOfSeconds >= 0 && cutNumberOfSeconds < 35) { + if (0 <= cutNumberOfSeconds && cutNumberOfSeconds < 35) { return ANSI_GREEN_BACKGROUND + "Green light" + ANSI_RESET; } - if ((cutNumberOfSeconds >= 35 && cutNumberOfSeconds < 40) || (cutNumberOfSeconds >= 55 && cutNumberOfSeconds < 60)) { + if (35 <= cutNumberOfSeconds && cutNumberOfSeconds < 40 || cutNumberOfSeconds >= 55) { return ANSI_YELLOW_BACKGROUND + "Yellow light" + ANSI_RESET; } - if (cutNumberOfSeconds >= 40 && cutNumberOfSeconds < 55) { + if (cutNumberOfSeconds >= 40) { return ANSI_RED_BACKGROUND + "Red light" + ANSI_RESET; } return "Something went wrong"; diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index 17f9f349..790e19c9 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -4,18 +4,18 @@ import java.time.LocalTime; import java.util.Scanner; -/** - * todo Document type TrafficLightExtraMode - */ public class TrafficLightExtraMode extends TrafficLight { + private int secondsParsed; + @Override public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); String inputStr = scanner.nextLine(); if (isValid(inputStr)) { - System.out.println(getTrafficLight(LocalTime.parse(inputStr).toSecondOfDay())); + String result = getTrafficLight(secondsParsed); + System.out.println(result); } scanner.close(); } @@ -23,11 +23,11 @@ public void run() { @Override public boolean isValid(String arg) { try { - LocalTime.parse(arg).toSecondOfDay(); - return true; + secondsParsed = LocalTime.parse(arg).toSecondOfDay(); } catch (DateTimeException exception) { System.out.println(ANSI_RED + "Only hh:mm:ss input format (hh < 24, mm < 60, ss < 60)" + ANSI_RESET); return false; } + return true; } } From f56c19855d47ff5ec10d85547eb4934a53ef8d80 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sun, 1 Aug 2021 03:10:09 +0300 Subject: [PATCH 25/57] refactor hw3 --- .../java/homework_3/MyImmutableClass.java | 45 ++++++++++++------- src/test/java/homework_1/MainTest.java | 1 - .../pyramid_printer/PyramidPrinterTest.java | 11 ++--- .../RandomCharsTableCreatorTest.java | 4 +- .../RandomCharsTableTest.java | 16 +++---- .../traffic_light/TrafficLightTest.java | 4 +- 6 files changed, 46 insertions(+), 35 deletions(-) diff --git a/src/main/java/homework_3/MyImmutableClass.java b/src/main/java/homework_3/MyImmutableClass.java index 1e37380e..db5d93fb 100644 --- a/src/main/java/homework_3/MyImmutableClass.java +++ b/src/main/java/homework_3/MyImmutableClass.java @@ -1,28 +1,43 @@ package homework_3; import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +/* +The class and his fields must have a final modifier +The class don't must have setters +Fields must have a private modifier +The constructor should do defensive copy for reference object +Defensive copy to reference object should be for getters + */ public final class MyImmutableClass { private final String myName; private final int myAge; - private final LocalDate myBirthday; + private final Map myPassword; public MyImmutableClass(String myName) { this.myName = myName; this.myAge = LocalDate.now().getYear(); - this.myBirthday = LocalDate.now(); + Map map = new HashMap<>(); + map.put("epam", "12345"); + map.put("ok.com", "qwerty"); + this.myPassword = map; } public MyImmutableClass(String myName, int myAge) { this.myName = myName; this.myAge = myAge; - this.myBirthday = LocalDate.now(); + Map map = new HashMap<>(); + map.put("epam", "12345"); + map.put("ok.com", "qwerty"); + this.myPassword = map; } - public MyImmutableClass(String myName, int myAge, LocalDate myBirthday) { + public MyImmutableClass(String myName, int myAge, Map myPassword) { this.myName = myName; this.myAge = myAge; - this.myBirthday = myBirthday; + this.myPassword = new HashMap<>(myPassword); } public String getMyName() { @@ -33,23 +48,23 @@ public int getMyAge() { return myAge; } - public LocalDate getMyBirthday() { - return myBirthday; + public Map getMyPassword() { + return new HashMap<>(myPassword); } - public MyImmutableClass myClone(MyImmutableClass myOldImmutableClass, String myNewName) { - return new MyImmutableClass(myNewName, myOldImmutableClass.getMyAge(), myOldImmutableClass.getMyBirthday()); + public MyImmutableClass getNewMyImmutableClass(MyImmutableClass myOldImmutableClass, String myNewName) { + return new MyImmutableClass(myNewName, myOldImmutableClass.getMyAge(), myOldImmutableClass.getMyPassword()); } - public MyImmutableClass myClone(MyImmutableClass myOldImmutableClass, int myNewAge) { - return new MyImmutableClass(myOldImmutableClass.getMyName(), myNewAge, myOldImmutableClass.getMyBirthday()); + public MyImmutableClass getNewMyImmutableClass(MyImmutableClass myOldImmutableClass, int myNewAge) { + return new MyImmutableClass(myOldImmutableClass.getMyName(), myNewAge, myOldImmutableClass.getMyPassword()); } - public MyImmutableClass myClone(MyImmutableClass myOldImmutableClass, LocalDate myNewBirthday) { - return new MyImmutableClass(myOldImmutableClass.getMyName(), myOldImmutableClass.getMyAge(), myNewBirthday); + public MyImmutableClass getNewMyImmutableClass(MyImmutableClass myOldImmutableClass, Map myNewPassword) { + return new MyImmutableClass(myOldImmutableClass.getMyName(), myOldImmutableClass.getMyAge(), myNewPassword); } - public MyImmutableClass myClone(String myNewName, int myNewAge, LocalDate myNewBirthday) { - return new MyImmutableClass(myNewName, myNewAge, myNewBirthday); + public MyImmutableClass getNewMyImmutableClass(String myNewName, int myNewAge, Map myNewPassword) { + return new MyImmutableClass(myNewName, myNewAge, myNewPassword); } } diff --git a/src/test/java/homework_1/MainTest.java b/src/test/java/homework_1/MainTest.java index a218bc8c..ce792d41 100644 --- a/src/test/java/homework_1/MainTest.java +++ b/src/test/java/homework_1/MainTest.java @@ -1,7 +1,6 @@ package homework_1; import base.UnitBase; -import base.UnitBaseMode; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertArrayEquals; diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java index 0fe17d85..56b8cf69 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -7,10 +7,7 @@ import static org.junit.jupiter.api.Assertions.*; -/** - * todo Document type PyramidPrinterTest - */ -class PyramidPrinterTest extends UnitBaseMode { +class PyramidPrinterTest extends UnitBaseMode { private final PyramidPrinter pyramidPrinter = new PyramidPrinter(); private final String METHOD_NAME = "run"; @@ -28,9 +25,9 @@ void runTest() { @Test void runTest1() { setInput("1"); + String[] expectedArray = {"x"}; run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); - String[] expectedArray = {"x"}; assertArrayEquals(expectedArray, getOutputLines()); } @@ -38,9 +35,9 @@ void runTest1() { @Test void runTest2() { setInput("2"); + String[] expectedArray = {"x", "xx"}; run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); - String[] expectedArray = {"x", "xx"}; assertArrayEquals(expectedArray, getOutputLines()); } @@ -48,9 +45,9 @@ void runTest2() { @Test void runTest10() { setInput("10"); + String[] expectedArray = {"x", "xx", "xxx", "xxxx", "xxxxx", "xxxxxx", "xxxxxxx", "xxxxxxxx", "xxxxxxxxx", "xxxxxxxxxx"}; run(pyramidPrinter, METHOD_NAME, STRING_TO_DEL); - String[] expectedArray = {"x", "xx", "xxx", "xxxx", "xxxxx", "xxxxxx", "xxxxxxx", "xxxxxxxx", "xxxxxxxxx", "xxxxxxxxxx"}; assertArrayEquals(expectedArray, getOutputLines()); } diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java index 8440f7fd..950be376 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java @@ -24,7 +24,7 @@ void setUp() { @Test void initTableTest1() { - char[][] charsTable = RandomCharsTableCreator.initTable(10, 20); + char[][] charsTable = RandomCharsTableCreator.initAndFillTable(10, 20); assertEquals(10, charsTable.length); for (char[] chars : charsTable) { @@ -37,7 +37,7 @@ void initTableTest1() { @Test void initTableTest2() { - char[][] charsTable = RandomCharsTableCreator.initTable(14, 124); + char[][] charsTable = RandomCharsTableCreator.initAndFillTable(14, 124); assertEquals(14, charsTable.length); for (char[] chars : charsTable) { diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index 995d2a99..5b16f880 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -47,7 +47,7 @@ void runTestValidArg2() { assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 2)); assertTrue(isEvenLetters(getOutputLines()[getOutputLines().length - 1])); - assertEquals(1 + 1, getOutputLines().length); + assertEquals(2, getOutputLines().length); assertTrue(getOutput().contains("even letters -")); } @@ -60,7 +60,7 @@ void runTestValidArg3() { assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 3)); assertTrue(isEvenLetters(getOutputLines()[getOutputLines().length - 1])); - assertEquals(2 + 1, getOutputLines().length); + assertEquals(3, getOutputLines().length); assertTrue(getOutput().contains("even letters - ")); } @@ -73,7 +73,7 @@ void runTestValidArg4() { assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 1)); assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); - assertEquals(2 + 1, getOutputLines().length); + assertEquals(3, getOutputLines().length); assertTrue(getOutput().contains("odd letters -")); } @@ -86,7 +86,7 @@ void runTestValidArg5() { assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 2)); assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); - assertEquals(1 + 1, getOutputLines().length); + assertEquals(2, getOutputLines().length); assertTrue(getOutput().contains("odd letters -")); } @@ -99,7 +99,7 @@ void runTestValidArg6() { assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 3)); assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); - assertEquals(2 + 1, getOutputLines().length); + assertEquals(3, getOutputLines().length); assertTrue(getOutput().contains("odd letters -")); } @@ -112,7 +112,7 @@ void runTestValidArg7() { assertTrue(isValidLetters(Arrays.copyOf(getOutputLines(), getOutputLines().length - 1), 20)); assertTrue(isOddLetters(getOutputLines()[getOutputLines().length - 1])); - assertEquals(10 + 1, getOutputLines().length); + assertEquals(11, getOutputLines().length); assertTrue(getOutput().contains("odd letters -")); } @@ -144,7 +144,7 @@ private boolean isValidLetters(String[] outputLines, int width) { private boolean isEvenLetters(String lastString) { lastString = lastString.replaceAll("(even letters -)|(\\s+)|(,+)", ""); for (int i = 0; i < lastString.length(); i++) { - if (!evenLettersArrayList.contains(lastString.charAt(i)) && oddLettersArrayList.contains(lastString.charAt(i))) { + if (oddLettersArrayList.contains(lastString.charAt(i))) { return false; } } @@ -154,7 +154,7 @@ private boolean isEvenLetters(String lastString) { private boolean isOddLetters(String lastString) { lastString = lastString.replaceAll("(odd letters -)|(\\s+)|(,+)", ""); for (int i = 0; i < lastString.length(); i++) { - if (!oddLettersArrayList.contains(lastString.charAt(i)) && evenLettersArrayList.contains(lastString.charAt(i))) { + if (evenLettersArrayList.contains(lastString.charAt(i))) { return false; } } diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java index b6593e1c..7262bf57 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -10,14 +10,14 @@ /** * todo Document type TrafficLightTest */ -class TrafficLightTest extends UnitBaseMode { +class TrafficLightTest extends UnitBaseMode { private final TrafficLight trafficLight = new TrafficLight(); private final String METHOD_NAME = "run"; private final String STRING_TO_DEL = "Enter the number"; @ParameterizedTest - @ValueSource(strings = {"0", "5"}) + @ValueSource(strings = {"0", "5", "61"}) void runTestValidArg1(String input) { setInput(input); From db966e0d32ead7e1ce3c4b3654837bba95b0ce0a Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sun, 1 Aug 2021 03:12:37 +0300 Subject: [PATCH 26/57] refactor hw3 --- src/test/java/base/UnitBaseMode.java | 3 --- .../random_chars_table/RandomCharsTableCreatorTest.java | 3 --- src/test/java/homework_2/traffic_light/TrafficLightTest.java | 3 --- 3 files changed, 9 deletions(-) diff --git a/src/test/java/base/UnitBaseMode.java b/src/test/java/base/UnitBaseMode.java index 21d130b4..1b3145f2 100644 --- a/src/test/java/base/UnitBaseMode.java +++ b/src/test/java/base/UnitBaseMode.java @@ -3,9 +3,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -/** - * todo Document type UnitBaseMode - */ public abstract class UnitBaseMode extends UnitBase { // can be used to invoke method for object your class under test diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java index 950be376..65093709 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java @@ -8,9 +8,6 @@ import static org.junit.jupiter.api.Assertions.*; -/** - * todo Document type RandomCharsTableCreatorTest - */ class RandomCharsTableCreatorTest { private List evenLettersArrayList; diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java index 7262bf57..eb5791af 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -7,9 +7,6 @@ import static org.junit.jupiter.api.Assertions.*; -/** - * todo Document type TrafficLightTest - */ class TrafficLightTest extends UnitBaseMode { private final TrafficLight trafficLight = new TrafficLight(); From 88f928315a5d94ddcf7bef9d96f52c8bf55a06a4 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Wed, 4 Aug 2021 01:29:26 +0300 Subject: [PATCH 27/57] add hw4 CustomFileReader --- build.gradle | 2 + .../custom_file_reader/CustomFileReader.java | 105 +++++++++ .../homework_4/custom_file_reader/Main.java | 9 + .../utility_classes/AbstractFileReader.java | 31 +++ .../utility_classes/ApacheFileReader.java | 22 ++ .../BufferedReaderFileReader.java | 22 ++ .../FileInputStreamFileReader.java | 23 ++ .../utility_classes/GuavaFileReader.java | 23 ++ .../utility_classes/MyScannerFileReader.java | 27 +++ .../utility_classes/NIOFileReader.java | 23 ++ .../resources/custom_file_reader/testFile.txt | 0 src/test/java/base/UnitBaseFileMode.java | 27 +++ .../CustomFileReaderTest.java | 212 ++++++++++++++++++ 13 files changed, 526 insertions(+) create mode 100644 src/main/java/homework_4/custom_file_reader/CustomFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/Main.java create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/BufferedReaderFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/MyScannerFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/NIOFileReader.java create mode 100644 src/main/resources/custom_file_reader/testFile.txt create mode 100644 src/test/java/base/UnitBaseFileMode.java create mode 100644 src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java diff --git a/build.gradle b/build.gradle index 522c2e14..60aa85d7 100644 --- a/build.gradle +++ b/build.gradle @@ -13,6 +13,8 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' testCompile 'org.junit.jupiter:junit-jupiter-params:5.7.0' + implementation 'com.google.guava:guava:30.1.1-jre' + implementation 'org.apache.commons:commons-io:1.3.2' } test { diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..83052f2f --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,105 @@ +package homework_4.custom_file_reader; + +import homework_4.custom_file_reader.utility_classes.*; + +import java.io.*; + +public class CustomFileReader { + + private String fileContent; + private File fileReader; + private String filePath = "./src/main/resources/custom_file_reader/testFile.txt"; + + public CustomFileReader() { + } + + public CustomFileReader(String filePath) { + this.filePath = filePath; + } + + public CustomFileReader(File file) { + this.filePath = file.getPath(); + } + + public String getFileContent() { + return fileContent.toString(); + } + + //used NIO + public void run1(/*NIO*/) { + if (isExistsFile(filePath)) { + fileReader = new File(filePath); + fileContent = new NIOFileReader().getFileContent(fileReader); + printResult(); + } else { + printErrorMessage(); + } + } + + //used FileInputStream + public void run2() { + if (isExistsFile(filePath)) { + fileReader = new File(filePath); + fileContent = new FileInputStreamFileReader().getFileContent(fileReader); + printResult(); + } else { + printErrorMessage(); + } + } + + //used Scanner + public void run3() { + if (isExistsFile(filePath)) { + fileReader = new File(filePath); + fileContent = new MyScannerFileReader().getFileContent(fileReader); + printResult(); + } else { + printErrorMessage(); + } + } + + //used BufferedReader + public void run4() { + if (isExistsFile(filePath)) { + fileReader = new File(filePath); + fileContent = new BufferedReaderFileReader().getFileContent(fileReader); + printResult(); + } else { + printErrorMessage(); + } + } + + //used GuavaFiles + public void run5() { + if (isExistsFile(filePath)) { + fileReader = new File(filePath); + fileContent = new GuavaFileReader().getFileContent(fileReader); + printResult(); + } else { + printErrorMessage(); + } + } + + //user ApacheFileUtils + public void run6() { + if (isExistsFile(filePath)) { + fileReader = new File(filePath); + fileContent = new ApacheFileReader().getFileContent(fileReader); + printResult(); + } else { + printErrorMessage(); + } + } + + private boolean isExistsFile(String filePath) { + return new File(filePath).exists(); + } + + private void printResult() { + System.out.println(fileContent.replaceAll("(\\.)|(,)", "")); + } + + private void printErrorMessage() { + System.out.println("File not found in path"); + } +} diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java new file mode 100644 index 00000000..b879dfb6 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,9 @@ +package homework_4.custom_file_reader; + +public class Main { + + public static void main(String[] args) { + new CustomFileReader().run1(); + } + +} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java new file mode 100644 index 00000000..19b678e2 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java @@ -0,0 +1,31 @@ +package homework_4.custom_file_reader.utility_classes; + +import java.io.File; +import java.util.Iterator; +import java.util.List; + +public abstract class AbstractFileReader { + + protected String fileContent; + + public String getFileContent() { + return fileContent; + } + + protected abstract String getFileContent(File file); + + protected void fillFileContent(List stringList) { + Iterator iterator = stringList.iterator(); + StringBuilder tempStringBuilder = new StringBuilder(); + while (iterator.hasNext()) { + String tempStr = iterator.next(); + if (iterator.hasNext()) { + tempStringBuilder.append(tempStr).append("\n"); + } else { + tempStringBuilder.append(tempStr); + } + } + fileContent = tempStringBuilder.toString(); + } + +} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java new file mode 100644 index 00000000..69fb4ad4 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java @@ -0,0 +1,22 @@ +package homework_4.custom_file_reader.utility_classes; + +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +public class ApacheFileReader extends AbstractFileReader { + + @Override + public String getFileContent(File file) { + try { + List contentFileLinesList = FileUtils.readLines(file, "UTF-8"); + fillFileContent(contentFileLinesList); + } catch (IOException e) { + e.printStackTrace(); + } + return fileContent; + } + +} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/BufferedReaderFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/BufferedReaderFileReader.java new file mode 100644 index 00000000..5d937bbe --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/BufferedReaderFileReader.java @@ -0,0 +1,22 @@ +package homework_4.custom_file_reader.utility_classes; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +public class BufferedReaderFileReader extends AbstractFileReader { + + @Override + public String getFileContent(File file) { + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + List stringList = bufferedReader.lines().collect(Collectors.toList()); + fillFileContent(stringList); + } catch (IOException e) { + e.printStackTrace(); + } + return fileContent; + } +} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java new file mode 100644 index 00000000..b5efffcc --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java @@ -0,0 +1,23 @@ +package homework_4.custom_file_reader.utility_classes; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +public class FileInputStreamFileReader extends AbstractFileReader { + + @Override + public String getFileContent(File file) { + try (FileInputStream fileInputStream = new FileInputStream(file.getPath())) { + StringBuilder fileCSB = new StringBuilder(); + int i; + while ((i = fileInputStream.read()) != -1) { + fileCSB.append((char) i); + } + fileContent = fileCSB.toString(); + } catch (IOException e) { + e.printStackTrace(); + } + return fileContent; + } +} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java new file mode 100644 index 00000000..597ff53b --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java @@ -0,0 +1,23 @@ +package homework_4.custom_file_reader.utility_classes; + +import com.google.common.base.Charsets; +import com.google.common.io.Files; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +public class GuavaFileReader extends AbstractFileReader { + + @Override + public String getFileContent(File file) { + try { + List stringList = Files.readLines(file, Charsets.UTF_8); + fillFileContent(stringList); + } catch (IOException e) { + e.printStackTrace(); + } + return fileContent; + } + +} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/MyScannerFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/MyScannerFileReader.java new file mode 100644 index 00000000..35a2fce3 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/MyScannerFileReader.java @@ -0,0 +1,27 @@ +package homework_4.custom_file_reader.utility_classes; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class MyScannerFileReader extends AbstractFileReader { + + @Override + public String getFileContent(File file) { + Path path = Paths.get(file.getPath()); + try (Scanner scanner = new Scanner(path)) { + List stringList = new ArrayList<>(); + while (scanner.hasNextLine()) { + stringList.add(scanner.nextLine()); + } + fillFileContent(stringList); + } catch (IOException e) { + e.printStackTrace(); + } + return fileContent; + } +} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/NIOFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/NIOFileReader.java new file mode 100644 index 00000000..067e4889 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/NIOFileReader.java @@ -0,0 +1,23 @@ +package homework_4.custom_file_reader.utility_classes; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +public class NIOFileReader extends AbstractFileReader { + + @Override + public String getFileContent(File file) { + Path path = Paths.get(file.getPath()); + try { + List stringList = Files.readAllLines(path); + fillFileContent(stringList); + } catch (IOException e) { + e.printStackTrace(); + } + return fileContent; + } +} diff --git a/src/main/resources/custom_file_reader/testFile.txt b/src/main/resources/custom_file_reader/testFile.txt new file mode 100644 index 00000000..e69de29b diff --git a/src/test/java/base/UnitBaseFileMode.java b/src/test/java/base/UnitBaseFileMode.java new file mode 100644 index 00000000..9264eb86 --- /dev/null +++ b/src/test/java/base/UnitBaseFileMode.java @@ -0,0 +1,27 @@ +package base; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +public class UnitBaseFileMode extends UnitBase { + + public void createAndFillTempFile(String fileName, String content) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));) { + writer.write(content); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void deleteTempFile(String fileName) { + try { + Files.deleteIfExists(Paths.get(fileName)); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..36a26ddc --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,212 @@ +package homework_4.custom_file_reader; + +import base.UnitBaseFileMode; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBaseFileMode { + + @AfterEach + void delTempFile() { + deleteTempFile("./src/main/resources/custom_file_reader/tempFile.txt"); + } + + @ParameterizedTest + @MethodSource("testValidValue") + void givenContent_whenRun1_thenExpected(String filePath, String content, String expected) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run1(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testEmpty") + void givenContent_whenRun1_thenEmpty(String filePath, String content) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run1(); + + assertEquals("", getOutput()); + } + + @ParameterizedTest + @MethodSource("testFileNotFound") + void givenWrongFileName_whenRun1_thenFileNotFound(String filePath, String content) { + createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); + new CustomFileReader(filePath).run1(); + + assertEquals("File not found in path", getOutput()); + } + + @ParameterizedTest + @MethodSource("testValidValue") + void givenContent_whenRun2_thenExpected(String filePath, String content, String expected) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run2(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testEmpty") + void givenContent_whenRun2_thenEmpty(String filePath, String content) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run2(); + + assertEquals("", getOutput()); + } + + @ParameterizedTest + @MethodSource("testFileNotFound") + void givenWrongFileName_whenRun2_thenFileNotFound(String filePath, String content) { + createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); + new CustomFileReader(filePath).run2(); + + assertEquals("File not found in path", getOutput()); + } + + @ParameterizedTest + @MethodSource("testValidValue") + void givenContent_whenRun3_thenExpected(String filePath, String content, String expected) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run3(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testEmpty") + void givenContent_whenRun3_thenEmpty(String filePath, String content) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run3(); + + assertEquals("", getOutput()); + } + + @ParameterizedTest + @MethodSource("testFileNotFound") + void givenWrongFileName_whenRun3_thenFileNotFound(String filePath, String content) { + createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); + new CustomFileReader(filePath).run3(); + + assertEquals("File not found in path", getOutput()); + } + + @ParameterizedTest + @MethodSource("testValidValue") + void givenContent_whenRun4_thenExpected(String filePath, String content, String expected) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run4(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testEmpty") + void givenContent_whenRun4_thenEmpty(String filePath, String content) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run4(); + + assertEquals("", getOutput()); + } + + @ParameterizedTest + @MethodSource("testFileNotFound") + void givenWrongFileName_whenRun4_thenFileNotFound(String filePath, String content) { + createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); + new CustomFileReader(filePath).run4(); + + assertEquals("File not found in path", getOutput()); + } + + @ParameterizedTest + @MethodSource("testValidValue") + void givenContent_whenRun5_thenExpected(String filePath, String content, String expected) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run5(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testEmpty") + void givenContent_whenRun5_thenEmpty(String filePath, String content) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run5(); + + assertEquals("", getOutput()); + } + + @ParameterizedTest + @MethodSource("testFileNotFound") + void givenWrongFileName_whenRun5_thenFileNotFound(String filePath, String content) { + createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); + new CustomFileReader(filePath).run5(); + + assertEquals("File not found in path", getOutput()); + } + + @ParameterizedTest + @MethodSource("testValidValue") + void givenContent_whenRun6_thenExpected(String filePath, String content, String expected) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run6(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testEmpty") + void givenContent_whenRun6_thenEmpty(String filePath, String content) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run6(); + + assertEquals("", getOutput()); + } + + @ParameterizedTest + @MethodSource("testFileNotFound") + void givenWrongFileName_whenRun6_thenFileNotFound(String filePath, String content) { + createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); + new CustomFileReader(filePath).run6(); + + assertEquals("File not found in path", getOutput()); + } + + private static Stream testFileNotFound() { + return Stream.of( + Arguments.of("/src/main/resources/custom_file_reader/testFile.txt", "1,2,3,4,5,6,7,\n8,9."), + Arguments.of("./sr/main/resources/custom_file_reader/testFile.txt", "..1,,"), + Arguments.of("./src/mai/resources/custom_file_reader/testFile.txt", "zxc01"), + Arguments.of("./src/main/resource/custom_file_reader/testFile.txt", "1! abcdefg"), + Arguments.of("./src/main/resources/custom_filereader/testFile.txt", "1!. qwerty, abcdefg."), + Arguments.of("./src/main/resources/custom_file_reader/testFiletxt", "1!. qwerty,\n abcdefg.") + ); + } + + private static Stream testEmpty() { + return Stream.of( + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", ""), + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", ".."), + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", ",,"), + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", "..,,"), + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", "..,,") + ); + } + + private static Stream testValidValue() { + return Stream.of( + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", "1,2,3,4,5,6,7,\n8,9.", "1234567\n89"), + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", "zxc01", "zxc01"), + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", "1! abcdefg", "1! abcdefg"), + Arguments.of("./src/main/resources/custom_file_reader/tempFile.txt", "1!. qwerty, abcdefg.", "1! qwerty abcdefg") + ); + } + +} \ No newline at end of file From 4af322556ac9649ba8ae6d14e1babdaa666b0aff Mon Sep 17 00:00:00 2001 From: pepyachka Date: Wed, 4 Aug 2021 01:29:42 +0300 Subject: [PATCH 28/57] add hw4 Singleton --- .../java/homework_4/singleton/MySingleton.java | 18 ++++++++++++++++++ .../homework_4/singleton/MySingletonTest.java | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 src/main/java/homework_4/singleton/MySingleton.java create mode 100644 src/test/java/homework_4/singleton/MySingletonTest.java diff --git a/src/main/java/homework_4/singleton/MySingleton.java b/src/main/java/homework_4/singleton/MySingleton.java new file mode 100644 index 00000000..66f0151f --- /dev/null +++ b/src/main/java/homework_4/singleton/MySingleton.java @@ -0,0 +1,18 @@ +package homework_4.singleton; + +public class MySingleton { + private static MySingleton mySingleton; + + private String singletonName; + + private MySingleton(String singletonName) { + this.singletonName = singletonName; + } + + public static MySingleton getInstance(String singletonName) { + if (mySingleton == null) { + mySingleton = new MySingleton(singletonName); + } + return mySingleton; + } +} diff --git a/src/test/java/homework_4/singleton/MySingletonTest.java b/src/test/java/homework_4/singleton/MySingletonTest.java new file mode 100644 index 00000000..340bb2a5 --- /dev/null +++ b/src/test/java/homework_4/singleton/MySingletonTest.java @@ -0,0 +1,18 @@ +package homework_4.singleton; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +class MySingletonTest { + + @ParameterizedTest + @ValueSource(strings = {"1st", "2nd", "3rd"}) + void test(String input) { + MySingleton mySingleton = MySingleton.getInstance("Singleton"); + + assertEquals(mySingleton.hashCode(), MySingleton.getInstance(input).hashCode()); + } + +} \ No newline at end of file From 7796db23069602d8255ab8a75d489247d87bf8dc Mon Sep 17 00:00:00 2001 From: pepyachka Date: Wed, 4 Aug 2021 01:30:10 +0300 Subject: [PATCH 29/57] add hw4 CustomAnnotation --- .../homework_4/custom_annotation/Cat.java | 57 +++++++++++++++++ .../annotations/XmlConverter.java | 63 +++++++++++++++++++ .../annotations/XmlElement.java | 12 ++++ .../annotations/XmlSerializable.java | 11 ++++ .../XmlSerializationException.java | 8 +++ .../annotations/XmlConverterTest.java | 29 +++++++++ 6 files changed, 180 insertions(+) create mode 100644 src/main/java/homework_4/custom_annotation/Cat.java create mode 100644 src/main/java/homework_4/custom_annotation/annotations/XmlConverter.java create mode 100644 src/main/java/homework_4/custom_annotation/annotations/XmlElement.java create mode 100644 src/main/java/homework_4/custom_annotation/annotations/XmlSerializable.java create mode 100644 src/main/java/homework_4/custom_annotation/custom_exception/XmlSerializationException.java create mode 100644 src/test/java/homework_4/custom_annotation/annotations/XmlConverterTest.java diff --git a/src/main/java/homework_4/custom_annotation/Cat.java b/src/main/java/homework_4/custom_annotation/Cat.java new file mode 100644 index 00000000..0de43fc5 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Cat.java @@ -0,0 +1,57 @@ +package homework_4.custom_annotation; + +import homework_4.custom_annotation.annotations.XmlElement; +import homework_4.custom_annotation.annotations.XmlSerializable; + +@XmlSerializable +public class Cat { + + @XmlElement + private String name; + + @XmlElement + private String age; + + @XmlElement + private String breed; + + private String emailAddress; + + public Cat(String name, String age, String breed) { + this.name = name; + this.age = age; + this.breed = breed; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAge() { + return age; + } + + public void setAge(String age) { + this.age = age; + } + + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } +} diff --git a/src/main/java/homework_4/custom_annotation/annotations/XmlConverter.java b/src/main/java/homework_4/custom_annotation/annotations/XmlConverter.java new file mode 100644 index 00000000..04b9f25c --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/annotations/XmlConverter.java @@ -0,0 +1,63 @@ +package homework_4.custom_annotation.annotations; + +import homework_4.custom_annotation.custom_exception.XmlSerializationException; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +public class XmlConverter { + + public String convertToXml(Object object) throws XmlSerializationException { + try { + validObjectToSerializable(object); + return getXmlString(object); + } catch (Exception e) { + throw new XmlSerializationException(e.getMessage()); + } + } + + private void validObjectToSerializable(Object object) { + if (Objects.isNull(object)) { + throw new XmlSerializationException("The object is null"); + } + + Class serializableClass = object.getClass(); + if (!serializableClass.isAnnotationPresent(XmlSerializable.class)) { + throw new XmlSerializationException("The object " + serializableClass.getSimpleName() + " should be annotated with " + XmlSerializable.class.getSimpleName()); + } + } + + private String getXmlString(Object object) throws Exception { + Class serializableClass = object.getClass(); + Map xmlElementsMap = new HashMap<>(); + for (Field field : serializableClass.getDeclaredFields()) { + field.setAccessible(true); + if (field.isAnnotationPresent(XmlElement.class)) { + xmlElementsMap.put(getKey(field), (String) field.get(object)); + } + } + + String xmlString = xmlElementsMap.entrySet() + .stream() + .map(entry -> "<" + entry.getKey().toLowerCase(Locale.ROOT) + ">" + + entry.getValue().toLowerCase(Locale.ROOT) + + "") + .collect(Collectors.joining("")); + return "<" + serializableClass.getSimpleName().toLowerCase(Locale.ROOT) + "s" + ">" + + "<" + serializableClass.getSimpleName().toLowerCase(Locale.ROOT) + ">" + + xmlString + + "" + + ""; + } + + private String getKey(Field field) { + String value = field.getAnnotation(XmlElement.class) + .key(); + return value.isEmpty() ? field.getName() : value; + } + +} diff --git a/src/main/java/homework_4/custom_annotation/annotations/XmlElement.java b/src/main/java/homework_4/custom_annotation/annotations/XmlElement.java new file mode 100644 index 00000000..08a72cae --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/annotations/XmlElement.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface XmlElement { + String key() default ""; +} \ No newline at end of file diff --git a/src/main/java/homework_4/custom_annotation/annotations/XmlSerializable.java b/src/main/java/homework_4/custom_annotation/annotations/XmlSerializable.java new file mode 100644 index 00000000..11b54767 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/annotations/XmlSerializable.java @@ -0,0 +1,11 @@ +package homework_4.custom_annotation.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface XmlSerializable { +} diff --git a/src/main/java/homework_4/custom_annotation/custom_exception/XmlSerializationException.java b/src/main/java/homework_4/custom_annotation/custom_exception/XmlSerializationException.java new file mode 100644 index 00000000..8c5ce331 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/custom_exception/XmlSerializationException.java @@ -0,0 +1,8 @@ +package homework_4.custom_annotation.custom_exception; + +public class XmlSerializationException extends RuntimeException { + + public XmlSerializationException(String message) { + super(message); + } +} diff --git a/src/test/java/homework_4/custom_annotation/annotations/XmlConverterTest.java b/src/test/java/homework_4/custom_annotation/annotations/XmlConverterTest.java new file mode 100644 index 00000000..4852d1bf --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/annotations/XmlConverterTest.java @@ -0,0 +1,29 @@ +package homework_4.custom_annotation.annotations; + +import homework_4.custom_annotation.Cat; +import homework_4.custom_annotation.custom_exception.XmlSerializationException; +import org.junit.jupiter.api.Test; + +import java.util.Locale; + +import static org.junit.jupiter.api.Assertions.*; + +class XmlConverterTest { + + @Test + void givenObject_whenConvertToXml_thenThrows() throws XmlSerializationException { + Object o = new Object(); + XmlConverter xmlConverter = new XmlConverter(); + assertThrows(XmlSerializationException.class, () -> { + xmlConverter.convertToXml(o); + }); + } + + @Test + void givenCat_whenConvertToXml_thenValidCatForXml() { + Cat cat = new Cat("Epam", "1", "Intern"); + XmlConverter xmlConverter = new XmlConverter(); + assertEquals("epam1intern".toLowerCase(Locale.ROOT), xmlConverter.convertToXml(cat)); + } + +} \ No newline at end of file From e1c78c6518b110445405c3e54d006c99920da170 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Wed, 4 Aug 2021 01:35:14 +0300 Subject: [PATCH 30/57] refactor hw4 CustomFileReader --- .../java/homework_4/custom_file_reader/CustomFileReader.java | 2 +- .../{MyScannerFileReader.java => ScannerFileReader.java} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/main/java/homework_4/custom_file_reader/utility_classes/{MyScannerFileReader.java => ScannerFileReader.java} (92%) diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index 83052f2f..377eba5f 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -51,7 +51,7 @@ public void run2() { public void run3() { if (isExistsFile(filePath)) { fileReader = new File(filePath); - fileContent = new MyScannerFileReader().getFileContent(fileReader); + fileContent = new ScannerFileReader().getFileContent(fileReader); printResult(); } else { printErrorMessage(); diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/MyScannerFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/ScannerFileReader.java similarity index 92% rename from src/main/java/homework_4/custom_file_reader/utility_classes/MyScannerFileReader.java rename to src/main/java/homework_4/custom_file_reader/utility_classes/ScannerFileReader.java index 35a2fce3..b58b21d7 100644 --- a/src/main/java/homework_4/custom_file_reader/utility_classes/MyScannerFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/ScannerFileReader.java @@ -8,7 +8,7 @@ import java.util.List; import java.util.Scanner; -public class MyScannerFileReader extends AbstractFileReader { +public class ScannerFileReader extends AbstractFileReader { @Override public String getFileContent(File file) { From b3ee00f60b8636c111ccba858a94b0e0185458f8 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Wed, 4 Aug 2021 01:40:16 +0300 Subject: [PATCH 31/57] update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index c6f7f2a9..26a10ddb 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ + # Java Core June 2021 ## *Drozdov Nikita* @@ -7,6 +8,10 @@ | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | | HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_1)
[PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_2)
[RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_3)| The app that reads input args and prints current traffic light
The app that reads input integer and prints "x" pyramid
The app that reads input arg, generate chars table and prints odd/even letters | | HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/DrozdovNikita/src/main/java/homework_3/MyImmutableClass.java) | | +| HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_file_reader)
[Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/singleton)
[CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_annotation) | The app has 6 implementation file reader: Apache, BufferedReader, FileInputStream, Guava, Scanner and NIO
The app-singleton
The app use custom annotations to create xml structure for your object: XmlSerializable and XmlElement | +| | | | +| TEST | [Test dir](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/test/java) + [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)
[Link to сodingBat](https://codingbat.com/done?user=ndrozdov9@gmail.com&tag=8408048475) From b67f41f3c57f6c70727d7466c70ae26df1ec3186 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Wed, 4 Aug 2021 01:40:58 +0300 Subject: [PATCH 32/57] update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 26a10ddb..db6a59ab 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Java Core June 2021 -## *Drozdov Nikita* +## *Drozdov Nikita* つ ◕_◕ ༽つ | Number | Solution | Short description | --- | --- | --- | From 328e0e6d08c6370e7123ff2b0796fb41977b8e53 Mon Sep 17 00:00:00 2001 From: Nikita <44002713+pepya4ka@users.noreply.github.com> Date: Fri, 6 Aug 2021 23:45:48 +0300 Subject: [PATCH 33/57] update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db6a59ab..a6638e3c 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | -| HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_1)
[PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_2)
[RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/task_3)| The app that reads input args and prints current traffic light
The app that reads input integer and prints "x" pyramid
The app that reads input arg, generate chars table and prints odd/even letters | +| HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/traffic_light)
[PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/pyramid_printer)
[RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/random_chars_table)| The app that reads input args and prints current traffic light
The app that reads input integer and prints "x" pyramid
The app that reads input arg, generate chars table and prints odd/even letters | | HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/DrozdovNikita/src/main/java/homework_3/MyImmutableClass.java) | | | HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_file_reader)
[Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/singleton)
[CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_annotation) | The app has 6 implementation file reader: Apache, BufferedReader, FileInputStream, Guava, Scanner and NIO
The app-singleton
The app use custom annotations to create xml structure for your object: XmlSerializable and XmlElement | | | | | From b2257ec25d8133360478484e0c141fcbe0f67d9a Mon Sep 17 00:00:00 2001 From: pepyachka Date: Thu, 19 Aug 2021 17:53:48 +0300 Subject: [PATCH 34/57] refactor HW4 --- .../custom_file_reader/CustomFileReader.java | 83 ++++++------------- .../utility_classes/AbstractFileReader.java | 2 +- .../FileInputStreamFileReader.java | 5 +- .../InputStreamReaderFileReader.java | 25 ++++++ .../resources/custom_file_reader/file.txt | 1 + .../resources/custom_file_reader/testFile.txt | 0 .../CustomFileReaderTest.java | 39 +++++++-- 7 files changed, 89 insertions(+), 66 deletions(-) create mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/InputStreamReaderFileReader.java create mode 100644 src/main/resources/custom_file_reader/file.txt delete mode 100644 src/main/resources/custom_file_reader/testFile.txt diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index 377eba5f..a0c596d8 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -1,6 +1,7 @@ package homework_4.custom_file_reader; import homework_4.custom_file_reader.utility_classes.*; +import homework_4.custom_file_reader.utility_classes.InputStreamReaderFileReader; import java.io.*; @@ -8,98 +9,68 @@ public class CustomFileReader { private String fileContent; private File fileReader; - private String filePath = "./src/main/resources/custom_file_reader/testFile.txt"; public CustomFileReader() { + fileReader = new File("./src/main/resources/custom_file_reader/file.txt"); } public CustomFileReader(String filePath) { - this.filePath = filePath; + fileReader = new File(filePath); } public CustomFileReader(File file) { - this.filePath = file.getPath(); + fileReader = file; } public String getFileContent() { return fileContent.toString(); } - //used NIO - public void run1(/*NIO*/) { - if (isExistsFile(filePath)) { - fileReader = new File(filePath); - fileContent = new NIOFileReader().getFileContent(fileReader); + private void run(AbstractFileReader reader) { + if (fileReader.exists()) { + fileContent = reader.getFileContent(fileReader); printResult(); } else { - printErrorMessage(); + System.out.println("File not found in path"); } } - //used FileInputStream + //used NIO + public void run1() { + this.run(new NIOFileReader()); + } + + //used FileInputStream (only end) public void run2() { - if (isExistsFile(filePath)) { - fileReader = new File(filePath); - fileContent = new FileInputStreamFileReader().getFileContent(fileReader); - printResult(); - } else { - printErrorMessage(); - } + this.run(new FileInputStreamFileReader()); } - //used Scanner + //used InputStreamReaderFileReader public void run3() { - if (isExistsFile(filePath)) { - fileReader = new File(filePath); - fileContent = new ScannerFileReader().getFileContent(fileReader); - printResult(); - } else { - printErrorMessage(); - } + this.run(new InputStreamReaderFileReader()); } - //used BufferedReader + //used Scanner public void run4() { - if (isExistsFile(filePath)) { - fileReader = new File(filePath); - fileContent = new BufferedReaderFileReader().getFileContent(fileReader); - printResult(); - } else { - printErrorMessage(); - } + this.run(new ScannerFileReader()); } - //used GuavaFiles + //used BufferedReader public void run5() { - if (isExistsFile(filePath)) { - fileReader = new File(filePath); - fileContent = new GuavaFileReader().getFileContent(fileReader); - printResult(); - } else { - printErrorMessage(); - } + this.run(new BufferedReaderFileReader()); } - //user ApacheFileUtils + //used GuavaFiles public void run6() { - if (isExistsFile(filePath)) { - fileReader = new File(filePath); - fileContent = new ApacheFileReader().getFileContent(fileReader); - printResult(); - } else { - printErrorMessage(); - } + this.run(new GuavaFileReader()); } - private boolean isExistsFile(String filePath) { - return new File(filePath).exists(); + //user ApacheFileUtils + public void run7() { + this.run(new ApacheFileReader()); } private void printResult() { - System.out.println(fileContent.replaceAll("(\\.)|(,)", "")); - } - - private void printErrorMessage() { - System.out.println("File not found in path"); + System.out.println(fileContent.replaceAll("[.,]", "")); } } diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java index 19b678e2..ae61d018 100644 --- a/src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/AbstractFileReader.java @@ -12,7 +12,7 @@ public String getFileContent() { return fileContent; } - protected abstract String getFileContent(File file); + public abstract String getFileContent(File file); protected void fillFileContent(List stringList) { Iterator iterator = stringList.iterator(); diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java index b5efffcc..a51aa7d2 100644 --- a/src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/FileInputStreamFileReader.java @@ -1,9 +1,6 @@ package homework_4.custom_file_reader.utility_classes; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - +import java.io.*; public class FileInputStreamFileReader extends AbstractFileReader { @Override diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/InputStreamReaderFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/InputStreamReaderFileReader.java new file mode 100644 index 00000000..0d582d99 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/utility_classes/InputStreamReaderFileReader.java @@ -0,0 +1,25 @@ +package homework_4.custom_file_reader.utility_classes; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +public class InputStreamReaderFileReader extends AbstractFileReader { + + @Override + public String getFileContent(File file) { + try (InputStreamReader inputStreamReader = new java.io.InputStreamReader(new FileInputStream(file.getPath()), StandardCharsets.UTF_8)) { + StringBuilder fileCSB = new StringBuilder(); + int i; + while ((i = inputStreamReader.read()) != -1) { + fileCSB.append((char) i); + } + fileContent = fileCSB.toString(); + } catch (IOException e) { + e.printStackTrace(); + } + return fileContent; + } +} diff --git a/src/main/resources/custom_file_reader/file.txt b/src/main/resources/custom_file_reader/file.txt new file mode 100644 index 00000000..78ce3d5f --- /dev/null +++ b/src/main/resources/custom_file_reader/file.txt @@ -0,0 +1 @@ +"Нет никого, кто любил бы боль саму по себе, кто искал бы её и кто хотел бы иметь её просто потому, что это боль.." \ No newline at end of file diff --git a/src/main/resources/custom_file_reader/testFile.txt b/src/main/resources/custom_file_reader/testFile.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java index 36a26ddc..419588e9 100644 --- a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -71,6 +71,7 @@ void givenWrongFileName_whenRun2_thenFileNotFound(String filePath, String conten assertEquals("File not found in path", getOutput()); } + @ParameterizedTest @MethodSource("testValidValue") void givenContent_whenRun3_thenExpected(String filePath, String content, String expected) { @@ -98,6 +99,7 @@ void givenWrongFileName_whenRun3_thenFileNotFound(String filePath, String conten assertEquals("File not found in path", getOutput()); } + @ParameterizedTest @MethodSource("testValidValue") void givenContent_whenRun4_thenExpected(String filePath, String content, String expected) { @@ -179,13 +181,40 @@ void givenWrongFileName_whenRun6_thenFileNotFound(String filePath, String conten assertEquals("File not found in path", getOutput()); } + @ParameterizedTest + @MethodSource("testValidValue") + void givenContent_whenRun7_thenExpected(String filePath, String content, String expected) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run7(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testEmpty") + void givenContent_whenRun7_thenEmpty(String filePath, String content) { + createAndFillTempFile(filePath, content); + new CustomFileReader(filePath).run7(); + + assertEquals("", getOutput()); + } + + @ParameterizedTest + @MethodSource("testFileNotFound") + void givenWrongFileName_whenRun7_thenFileNotFound(String filePath, String content) { + createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); + new CustomFileReader(filePath).run7(); + + assertEquals("File not found in path", getOutput()); + } + private static Stream testFileNotFound() { return Stream.of( - Arguments.of("/src/main/resources/custom_file_reader/testFile.txt", "1,2,3,4,5,6,7,\n8,9."), - Arguments.of("./sr/main/resources/custom_file_reader/testFile.txt", "..1,,"), - Arguments.of("./src/mai/resources/custom_file_reader/testFile.txt", "zxc01"), - Arguments.of("./src/main/resource/custom_file_reader/testFile.txt", "1! abcdefg"), - Arguments.of("./src/main/resources/custom_filereader/testFile.txt", "1!. qwerty, abcdefg."), + Arguments.of("/src/main/resources/custom_file_reader/file.txt", "1,2,3,4,5,6,7,\n8,9."), + Arguments.of("./sr/main/resources/custom_file_reader/file.txt", "..1,,"), + Arguments.of("./src/mai/resources/custom_file_reader/file.txt", "zxc01"), + Arguments.of("./src/main/resource/custom_file_reader/file.txt", "1! abcdefg"), + Arguments.of("./src/main/resources/custom_filereader/file.txt", "1!. qwerty, abcdefg."), Arguments.of("./src/main/resources/custom_file_reader/testFiletxt", "1!. qwerty,\n abcdefg.") ); } From a8816e388b698e6966378fefd36dca970e1b39af Mon Sep 17 00:00:00 2001 From: pepyachka Date: Fri, 20 Aug 2021 12:06:11 +0300 Subject: [PATCH 35/57] refactor HW4: remove apache and guava --- build.gradle | 2 - .../custom_file_reader/CustomFileReader.java | 10 ---- .../utility_classes/ApacheFileReader.java | 22 -------- .../utility_classes/GuavaFileReader.java | 23 -------- .../CustomFileReaderTest.java | 54 ------------------- 5 files changed, 111 deletions(-) delete mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java delete mode 100644 src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java diff --git a/build.gradle b/build.gradle index 60aa85d7..522c2e14 100644 --- a/build.gradle +++ b/build.gradle @@ -13,8 +13,6 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' testCompile 'org.junit.jupiter:junit-jupiter-params:5.7.0' - implementation 'com.google.guava:guava:30.1.1-jre' - implementation 'org.apache.commons:commons-io:1.3.2' } test { diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index a0c596d8..14925ab3 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -60,16 +60,6 @@ public void run5() { this.run(new BufferedReaderFileReader()); } - //used GuavaFiles - public void run6() { - this.run(new GuavaFileReader()); - } - - //user ApacheFileUtils - public void run7() { - this.run(new ApacheFileReader()); - } - private void printResult() { System.out.println(fileContent.replaceAll("[.,]", "")); } diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java deleted file mode 100644 index 69fb4ad4..00000000 --- a/src/main/java/homework_4/custom_file_reader/utility_classes/ApacheFileReader.java +++ /dev/null @@ -1,22 +0,0 @@ -package homework_4.custom_file_reader.utility_classes; - -import org.apache.commons.io.FileUtils; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -public class ApacheFileReader extends AbstractFileReader { - - @Override - public String getFileContent(File file) { - try { - List contentFileLinesList = FileUtils.readLines(file, "UTF-8"); - fillFileContent(contentFileLinesList); - } catch (IOException e) { - e.printStackTrace(); - } - return fileContent; - } - -} diff --git a/src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java b/src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java deleted file mode 100644 index 597ff53b..00000000 --- a/src/main/java/homework_4/custom_file_reader/utility_classes/GuavaFileReader.java +++ /dev/null @@ -1,23 +0,0 @@ -package homework_4.custom_file_reader.utility_classes; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -public class GuavaFileReader extends AbstractFileReader { - - @Override - public String getFileContent(File file) { - try { - List stringList = Files.readLines(file, Charsets.UTF_8); - fillFileContent(stringList); - } catch (IOException e) { - e.printStackTrace(); - } - return fileContent; - } - -} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java index 419588e9..f91ae849 100644 --- a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -154,60 +154,6 @@ void givenWrongFileName_whenRun5_thenFileNotFound(String filePath, String conten assertEquals("File not found in path", getOutput()); } - @ParameterizedTest - @MethodSource("testValidValue") - void givenContent_whenRun6_thenExpected(String filePath, String content, String expected) { - createAndFillTempFile(filePath, content); - new CustomFileReader(filePath).run6(); - - assertEquals(expected, getOutput()); - } - - @ParameterizedTest - @MethodSource("testEmpty") - void givenContent_whenRun6_thenEmpty(String filePath, String content) { - createAndFillTempFile(filePath, content); - new CustomFileReader(filePath).run6(); - - assertEquals("", getOutput()); - } - - @ParameterizedTest - @MethodSource("testFileNotFound") - void givenWrongFileName_whenRun6_thenFileNotFound(String filePath, String content) { - createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); - new CustomFileReader(filePath).run6(); - - assertEquals("File not found in path", getOutput()); - } - - @ParameterizedTest - @MethodSource("testValidValue") - void givenContent_whenRun7_thenExpected(String filePath, String content, String expected) { - createAndFillTempFile(filePath, content); - new CustomFileReader(filePath).run7(); - - assertEquals(expected, getOutput()); - } - - @ParameterizedTest - @MethodSource("testEmpty") - void givenContent_whenRun7_thenEmpty(String filePath, String content) { - createAndFillTempFile(filePath, content); - new CustomFileReader(filePath).run7(); - - assertEquals("", getOutput()); - } - - @ParameterizedTest - @MethodSource("testFileNotFound") - void givenWrongFileName_whenRun7_thenFileNotFound(String filePath, String content) { - createAndFillTempFile("./src/main/resources/custom_file_reader/tempFile.txt", content); - new CustomFileReader(filePath).run7(); - - assertEquals("File not found in path", getOutput()); - } - private static Stream testFileNotFound() { return Stream.of( Arguments.of("/src/main/resources/custom_file_reader/file.txt", "1,2,3,4,5,6,7,\n8,9."), From 0621fee1afb5cb03a4d9dc94a4787b78eb7d6f0e Mon Sep 17 00:00:00 2001 From: pepyachka Date: Fri, 20 Aug 2021 23:11:54 +0300 Subject: [PATCH 36/57] add hw5 CustomRegexMatcher --- .../CustomRegexMatcher.java | 38 ++++++++++ .../homework_5/custom_regex_matcher/Main.java | 8 +++ .../CustomRegexMatcherTest.java | 71 +++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java create mode 100644 src/main/java/homework_5/custom_regex_matcher/Main.java create mode 100644 src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..350c6ca5 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,38 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + + private String phoneNumber = ""; + + public void run() { + System.out.println("Enter the phone number"); + initPhoneNumber(); + System.out.println(isMatches()); + } + + private void initPhoneNumber() { + try (Scanner scanner = new Scanner(System.in)) { + if (scanner.hasNextLine()) { + phoneNumber = scanner.nextLine().trim(); + } + } + } + + /* + * String has: + * start with +7 or 8; + * first group - it is mobile operator code. Should contains three or more digit, and can wrapped in parentheses; + * last three groups, which contains 3, 2 and 2 digits respectively. These groups can splitted dash or space + * */ + private boolean isMatches() { + Pattern pattern = Pattern.compile("^(\\+7|8)" + + "\\s?((\\((?=\\w{3}\\))\\w{3}\\))|\\w{3})\\s?" + + "(\\d{3})[\\-\\s]?" + + "(\\d{2})[\\-\\s]?" + + "(\\d{2})"); + return pattern.matcher(phoneNumber).matches(); + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..e1e20462 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,8 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..4d6ed618 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,71 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomRegexMatcherTest extends UnitBase { + + @ParameterizedTest + @MethodSource + void runTestValidInput(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput("Enter the phone number"); + + assertEquals(getOutput(), "true"); + } + + @ParameterizedTest + @MethodSource + void runTestInvalidInput(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput("Enter the phone number"); + + assertEquals(getOutput(), "false"); + } + + private static Stream runTestValidInput() { + return Stream.of( + Arguments.of("8(499)1111111"), + Arguments.of("+7(499)111-11-11"), + Arguments.of("+7(499)1111111"), + Arguments.of("8(499)111 11 11"), + Arguments.of("+7(499)111 11 11"), + Arguments.of("8 499 111-11-11"), + Arguments.of("84991111111"), + Arguments.of("+7 111 111 11 11") + ); + } + + private static Stream runTestInvalidInput() { + return Stream.of( + Arguments.of("8(905 336 52 45"), + Arguments.of("8 905) 336 52 45"), + Arguments.of("8(905)336 52 5"), + Arguments.of("8(905)336 2 45"), + Arguments.of(" "), + Arguments.of(""), + Arguments.of("8(905)33 52 45"), + Arguments.of("8(90)336 52 45"), + Arguments.of("+8(905)336 52 45"), + Arguments.of("+(905)336 52 45"), + Arguments.of("8(4991111111"), + Arguments.of("8499)1111111"), + Arguments.of("8(499)1 111111"), + Arguments.of("49)1 111111"), + Arguments.of("(905)336 52 45") + ); + } + +} \ No newline at end of file From d4ef445014d180fa7be687bbeda7bfaf10c516f0 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Fri, 20 Aug 2021 23:12:02 +0300 Subject: [PATCH 37/57] add hw5 PowerOfNumber --- .../java/homework_5/power_of_number/Main.java | 8 ++ .../power_of_number/PowerOfNumber.java | 53 +++++++++++++ .../power_of_number/PowerOfNumberTest.java | 74 +++++++++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 src/main/java/homework_5/power_of_number/Main.java create mode 100644 src/main/java/homework_5/power_of_number/PowerOfNumber.java create mode 100644 src/test/java/homework_5/power_of_number/PowerOfNumberTest.java diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..89300565 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,8 @@ +package homework_5.power_of_number; + +public class Main { + + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..733de8e7 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,53 @@ +package homework_5.power_of_number; + +import java.math.BigInteger; +import java.util.Scanner; +import java.util.stream.IntStream; + +public class PowerOfNumber { + + private static final String ANSI_RESET = "\033[0m"; + private static final String ANSI_RED = "\u001B[31m"; + private static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; + + public void run() { + System.out.println("Enter the number and degree"); + System.out.println(printPowResult()); + } + + private String printPowResult() { + String inputStr = ""; + try (Scanner scanner = new Scanner(System.in)) { + if (scanner.hasNextLine()) { + inputStr = scanner.nextLine().trim(); + } + } + if (isValid(inputStr.split("\\s"))) { + BigInteger a = new BigInteger(inputStr.split("\\s")[0]); + BigInteger b = new BigInteger(inputStr.split("\\s")[1]); + return String.valueOf(pow(a, b)); + } else { + return ANSI_RED + ERROR_MESSAGE + ANSI_RESET; + } + } + + private BigInteger pow(BigInteger a, BigInteger b) { + if (b.compareTo(BigInteger.valueOf(0)) == 0) return BigInteger.valueOf(1); + b = b.subtract(BigInteger.valueOf(1)); + a = a.multiply(pow(a, b)); + return a; + } + + private boolean isValid(String[] inputStr) { + if (inputStr.length != 2) { + return false; + } + if (!(inputStr[0].chars().allMatch(Character::isDigit) && + inputStr[1].chars().allMatch(Character::isDigit))) { + return false; + } + return IntStream.of(Integer.parseInt(inputStr[0])).allMatch(elem -> elem + 1 > 0) && + IntStream.of(Integer.parseInt(inputStr[1])).allMatch(elem -> elem + 1 > 0); + } + +} diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..1249d04b --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,74 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PowerOfNumberTest extends UnitBase { + + @ParameterizedTest + @MethodSource + void runTestValidInput(String input, String result) { + setInput(input); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Enter the number and degree"); + + assertEquals(getOutput(), result); + } + + @ParameterizedTest + @MethodSource + void runTestInvalidInput(String input) { + setInput(input); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Enter the number and degree"); + + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } + + private static Stream runTestInvalidInput() { + return Stream.of( + Arguments.of("-2 0"), + Arguments.of("2 -1"), + Arguments.of("-2 -2"), + Arguments.of("a 3"), + Arguments.of("2 a"), + Arguments.of("a a"), + Arguments.of("2"), + Arguments.of(""), + Arguments.of("2 8 9") + ); + } + + private static Stream runTestValidInput() { + return Stream.of( + Arguments.of("2 0", "1"), + Arguments.of("2 1", "2"), + Arguments.of("2 2", "4"), + Arguments.of("2 3", "8"), + Arguments.of("2 4", "16"), + Arguments.of("2 5", "32"), + Arguments.of("2 6", "64"), + Arguments.of("2 7", "128"), + Arguments.of("2 8", "256"), + Arguments.of("2 9", "512"), + Arguments.of("2 10", "1024"), + Arguments.of("10 2", "100"), + Arguments.of("10 3", "1000"), + Arguments.of("10 4", "10000"), + Arguments.of("10 10", "10000000000"), + Arguments.of("11 10", "25937424601") + ); + } + +} \ No newline at end of file From 7e0bf34f026bcd73a2feaeea25d50375f8d45216 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:34:59 +0300 Subject: [PATCH 38/57] add BaseClazz --- src/main/java/base/BaseClazz.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/base/BaseClazz.java diff --git a/src/main/java/base/BaseClazz.java b/src/main/java/base/BaseClazz.java new file mode 100644 index 00000000..644820fb --- /dev/null +++ b/src/main/java/base/BaseClazz.java @@ -0,0 +1,28 @@ +package base; + +import java.math.BigInteger; +import java.util.stream.IntStream; + +public abstract class BaseClazz { + + protected static final String ANSI_RESET = "\033[0m"; + protected static final String ANSI_RED = "\u001B[31m"; + protected static final String ANSI_RED_BACKGROUND = "\u001B[41m"; + protected static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; + protected static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; + + public abstract void run(); + + protected boolean isValid(String... arg) { + if (arg[0].split("\\s").length > 1) { + return false; + } + if (!arg[0].chars().allMatch(Character::isDigit)) { + return false; + } + + return new BigInteger(arg[0]).compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) <= 0 && + IntStream.of(Integer.parseInt(arg[0])).allMatch(elem -> elem + 1 > 0); + } + +} From a5464384e7c97d96ccf4314952c73b5f81caebb9 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:35:14 +0300 Subject: [PATCH 39/57] refactor hw1 --- src/main/java/homework_1/Main.java | 6 +++--- src/test/java/homework_1/MainTest.java | 22 +++++++++++----------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 9830c089..95b12963 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -4,11 +4,11 @@ public class Main { public static void main(String[] args) { for (String arg : args) { - if (arg.equals("ошибка")) { - System.out.println("\033[0;31m" + "Тревога!" + "\033[0m"); + if (arg.equals("error")) { + System.out.println("\033[0;31m" + "Alarm!" + "\033[0m"); break; } - System.out.println(arg + ": " + arg.length() + " букв"); + System.out.println(arg + ": " + arg.length() + " letters"); } } } diff --git a/src/test/java/homework_1/MainTest.java b/src/test/java/homework_1/MainTest.java index ce792d41..df682467 100644 --- a/src/test/java/homework_1/MainTest.java +++ b/src/test/java/homework_1/MainTest.java @@ -13,11 +13,11 @@ void mainTestValidArg() { String[] inputArg = {"a", "aa", "aaa", "aaaa", "aaaaa"}; String[] expectedArray = { - "a: 1 букв", - "aa: 2 букв", - "aaa: 3 букв", - "aaaa: 4 букв", - "aaaaa: 5 букв"}; + "a: 1 letters", + "aa: 2 letters", + "aaa: 3 letters", + "aaaa: 4 letters", + "aaaaa: 5 letters"}; Main.main(inputArg); assertArrayEquals(expectedArray, getOutputLines()); @@ -27,7 +27,7 @@ void mainTestValidArg() { void mainTestValidArg2() { String[] inputArg = {"1"}; - String[] expectedArray = {"1: 1 букв"}; + String[] expectedArray = {"1: 1 letters"}; Main.main(inputArg); assertArrayEquals(expectedArray, getOutputLines()); @@ -45,13 +45,13 @@ void mainTestEmptyArg() { @Test void mainTestWithErr() { - String[] inputArg = {"a", "aa", "aaa", "ошибка", "ааааа"}; + String[] inputArg = {"a", "aa", "aaa", "error", "ааааа"}; String[] expectedArray = { - "a: 1 букв", - "aa: 2 букв", - "aaa: 3 букв", - "\033[0;31mТревога!\033[0m"}; + "a: 1 letters", + "aa: 2 letters", + "aaa: 3 letters", + "\033[0;31mAlarm!\033[0m"}; Main.main(inputArg); assertArrayEquals(expectedArray, getOutputLines()); From db582725cb9c02399f06185b6d4dbfdc10fd5d19 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:36:23 +0300 Subject: [PATCH 40/57] refactor hw2 PyramidPrinter --- .../pyramid_printer/PyramidPrinter.java | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 017263d9..7d3a6d98 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -1,13 +1,14 @@ package homework_2.pyramid_printer; +import base.BaseClazz; + import java.util.Scanner; -public class PyramidPrinter { +public class PyramidPrinter extends BaseClazz { - private static final String ANSI_RESET = "\033[0m"; - private static final String ANSI_RED = "\u001B[31m"; private static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + @Override public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); @@ -20,18 +21,6 @@ public void run() { scanner.close(); } - private boolean isValid(String arg) { - if (arg.matches("^\\s*[+]?[0-9]+\\s*$")) { - try { - Integer.parseInt(arg); - } catch (NumberFormatException exception) { - return false; - } - return true; - } - return false; - } - private void printPyramid(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < i + 1; j++) { From 4e9cfe3eea659975d66e0af17a3b8bf627dfe7c3 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:36:52 +0300 Subject: [PATCH 41/57] refactor hw2 TrafficLight --- .../traffic_light/TrafficLight.java | 22 ++++--------------- .../traffic_light/TrafficLightExtraMode.java | 5 +++-- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 81dc6460..cbe0ed4b 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,16 +1,14 @@ package homework_2.traffic_light; +import base.BaseClazz; + import java.util.Scanner; -public class TrafficLight { +public class TrafficLight extends BaseClazz { - protected static final String ANSI_RESET = "\033[0m"; - protected static final String ANSI_RED = "\u001B[31m"; - protected static final String ANSI_RED_BACKGROUND = "\u001B[41m"; - protected static final String ANSI_GREEN_BACKGROUND = "\u001B[42m"; - protected static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m"; private static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + @Override public void run() { System.out.println("Enter the number"); Scanner scanner = new Scanner(System.in); @@ -29,18 +27,6 @@ public void run() { scanner.close(); } - protected boolean isValid(String arg) { - if (arg.matches("^\\s*[+]?[0-9]*\\s*$")) { - try { - Integer.parseInt(arg); - } catch (NumberFormatException exception) { - return false; - } - return true; - } - return false; - } - protected String getTrafficLight(int numberOfSeconds) { int cutNumberOfSeconds = numberOfSeconds % 60; if (0 <= cutNumberOfSeconds && cutNumberOfSeconds < 35) { diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index 790e19c9..376278b5 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -21,9 +21,10 @@ public void run() { } @Override - public boolean isValid(String arg) { + public boolean isValid(String... arg) { + if (arg.length > 1) return false; try { - secondsParsed = LocalTime.parse(arg).toSecondOfDay(); + secondsParsed = LocalTime.parse(arg[0]).toSecondOfDay(); } catch (DateTimeException exception) { System.out.println(ANSI_RED + "Only hh:mm:ss input format (hh < 24, mm < 60, ss < 60)" + ANSI_RESET); return false; From e6769f78e788252a16bc01d32a5aa9d9b1534283 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:37:10 +0300 Subject: [PATCH 42/57] refactor hw2 RandomCharsTable --- .../random_chars_table/RandomCharsTable.java | 13 ++++++++----- .../random_chars_table/RandomCharsTableCreator.java | 4 ++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 9d2f3a34..32437e19 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,13 +1,14 @@ package homework_2.random_chars_table; +import base.BaseClazz; + import java.util.*; -public class RandomCharsTable { +public class RandomCharsTable extends BaseClazz { - private static final String ANSI_RED = "\u001B[31m"; - private static final String ANSI_RESET = "\033[0m"; private static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + @Override public void run() { Scanner systemScanner = new Scanner(System.in); @@ -29,8 +30,10 @@ public void run() { systemScanner.close(); } - private boolean isValid(String inputStr) { - return inputStr.matches("^(([1-9][0-9]*\\s){2})(odd|even)"); + @Override + protected boolean isValid(String... inputStr) { + if (inputStr.length > 1) return false; + return inputStr[0].matches("^(([1-9][0-9]*\\s){2})(odd|even)"); } public void printTable(char[][] arrayOfChars) { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java index 36f5fc61..f545aa88 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -4,19 +4,19 @@ public final class RandomCharsTableCreator { + private static final Random random = new Random(); + private RandomCharsTableCreator() { throw new IllegalStateException("Utility class"); } public static char[][] initAndFillTable(int height, int width) { char[][] table = new char[height][width]; - Random random = new Random(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { table[i][j] = (char) (random.nextInt(26) + 65); } } - return table; } From 68efb7ac085c10a6f0a73cf8b23bdf5a9e1098fa Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:37:44 +0300 Subject: [PATCH 43/57] refactor hw3 MyImmutableClass --- src/main/java/homework_3/MyImmutableClass.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/homework_3/MyImmutableClass.java b/src/main/java/homework_3/MyImmutableClass.java index db5d93fb..0e47946e 100644 --- a/src/main/java/homework_3/MyImmutableClass.java +++ b/src/main/java/homework_3/MyImmutableClass.java @@ -12,6 +12,7 @@ Defensive copy to reference object should be for getters */ public final class MyImmutableClass { + private final String myName; private final int myAge; private final Map myPassword; From 804c5ef54c1b8870e05cf568fa51cc0be003694f Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:38:03 +0300 Subject: [PATCH 44/57] refactor hw4 CustomFileReader --- .../java/homework_4/custom_file_reader/CustomFileReader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index 14925ab3..dc37d03b 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -23,7 +23,7 @@ public CustomFileReader(File file) { } public String getFileContent() { - return fileContent.toString(); + return fileContent; } private void run(AbstractFileReader reader) { From 070db1bd02af3fb35d6adafdc29665d4d8803903 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:38:17 +0300 Subject: [PATCH 45/57] refactor hw5 CustomRegexMatcher --- .../CustomRegexMatcher.java | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java index 350c6ca5..ffe024f2 100644 --- a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -1,38 +1,42 @@ package homework_5.custom_regex_matcher; +import base.BaseClazz; + import java.util.Scanner; import java.util.regex.Pattern; -public class CustomRegexMatcher { - - private String phoneNumber = ""; +public class CustomRegexMatcher extends BaseClazz { + @Override public void run() { System.out.println("Enter the phone number"); - initPhoneNumber(); - System.out.println(isMatches()); + System.out.println(isValid(initPhoneNumber())); } - private void initPhoneNumber() { + private String initPhoneNumber() { + String phoneNumber = ""; try (Scanner scanner = new Scanner(System.in)) { if (scanner.hasNextLine()) { phoneNumber = scanner.nextLine().trim(); } } + return phoneNumber; } /* * String has: - * start with +7 or 8; - * first group - it is mobile operator code. Should contains three or more digit, and can wrapped in parentheses; - * last three groups, which contains 3, 2 and 2 digits respectively. These groups can splitted dash or space + * Starts with +7 or 8; + * First group - it is mobile operator code. It should contain three or more digits and it can be wrapped in parentheses; + * Last three groups should contains 3, 2 and 2 digits respectively. These groups can be splitted with the help of dash or space * */ - private boolean isMatches() { + @Override + protected boolean isValid(String... arg) { + if (arg.length > 1) return false; Pattern pattern = Pattern.compile("^(\\+7|8)" + "\\s?((\\((?=\\w{3}\\))\\w{3}\\))|\\w{3})\\s?" + "(\\d{3})[\\-\\s]?" + "(\\d{2})[\\-\\s]?" + "(\\d{2})"); - return pattern.matcher(phoneNumber).matches(); + return pattern.matcher(arg[0]).matches(); } } From 579fac18c6ab81ce73365a2edf2e1de93f2799fe Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:38:27 +0300 Subject: [PATCH 46/57] refactor hw5 PowerOfNumber --- .../java/homework_5/power_of_number/PowerOfNumber.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java index 733de8e7..8051f1e9 100644 --- a/src/main/java/homework_5/power_of_number/PowerOfNumber.java +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -1,15 +1,16 @@ package homework_5.power_of_number; +import base.BaseClazz; + import java.math.BigInteger; import java.util.Scanner; import java.util.stream.IntStream; -public class PowerOfNumber { +public class PowerOfNumber extends BaseClazz { - private static final String ANSI_RESET = "\033[0m"; - private static final String ANSI_RED = "\u001B[31m"; private static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; + @Override public void run() { System.out.println("Enter the number and degree"); System.out.println(printPowResult()); @@ -38,7 +39,8 @@ private BigInteger pow(BigInteger a, BigInteger b) { return a; } - private boolean isValid(String[] inputStr) { + @Override + protected boolean isValid(String... inputStr) { if (inputStr.length != 2) { return false; } From 1df79cb70cb872aa08faac6496fb37eb7d917374 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sat, 21 Aug 2021 00:47:32 +0300 Subject: [PATCH 47/57] update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a6638e3c..6044028d 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ | HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/traffic_light)
[PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/pyramid_printer)
[RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_2/random_chars_table)| The app that reads input args and prints current traffic light
The app that reads input integer and prints "x" pyramid
The app that reads input arg, generate chars table and prints odd/even letters | | HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/DrozdovNikita/src/main/java/homework_3/MyImmutableClass.java) | | | HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_file_reader)
[Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/singleton)
[CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_annotation) | The app has 6 implementation file reader: Apache, BufferedReader, FileInputStream, Guava, Scanner and NIO
The app-singleton
The app use custom annotations to create xml structure for your object: XmlSerializable and XmlElement | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_5/power_of_number)
[CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_5/custom_regex_matcher) | The app that reads two input integers and prints a to the power of b
The app that reads input phone number and prints its validity | | | | | | TEST | [Test dir](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/test/java) From 750a82def37fa6ccce9e059620a69e2e554bbf91 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Mon, 13 Sep 2021 16:11:33 +0300 Subject: [PATCH 48/57] add hw7 --- src/main/java/homework_7/Main.java | 28 ++++++++ .../function/KittenToCatFunction.java | 11 +++ src/main/java/homework_7/model/Sex.java | 17 +++++ .../java/homework_7/model/cat_model/Cat.java | 67 +++++++++++++++++++ .../model/cat_model/MilitaryCat.java | 15 +++++ .../homework_7/model/kitten_model/Kitten.java | 50 ++++++++++++++ 6 files changed, 188 insertions(+) create mode 100644 src/main/java/homework_7/Main.java create mode 100644 src/main/java/homework_7/function/KittenToCatFunction.java create mode 100644 src/main/java/homework_7/model/Sex.java create mode 100644 src/main/java/homework_7/model/cat_model/Cat.java create mode 100644 src/main/java/homework_7/model/cat_model/MilitaryCat.java create mode 100644 src/main/java/homework_7/model/kitten_model/Kitten.java diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..66c6a0bf --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,28 @@ +package homework_7; + +import homework_7.function.KittenToCatFunction; +import homework_7.model.Sex; +import homework_7.model.cat_model.Cat; +import homework_7.model.cat_model.MilitaryCat; +import homework_7.model.kitten_model.Kitten; + +import java.util.Random; + +import static homework_7.model.Sex.*; + +public class Main { + + public static void main(String[] args) { + + KittenToCatFunction kittenToCatFunction = Main::toCat; + Kitten kitten = new Kitten("Nikita", 0, MALE); + System.out.println(kittenToCatFunction.grow(kitten)); + } + + private static Cat toCat(Kitten kitten) { + String catName = (kitten.getSex().equals(MALE) ? "Mr. " : "Ms. ") + kitten.getFirstName(); + int catAge = new Random().nextInt(82) + 18; + return new Cat(catName, catAge, kitten.getSex(), "student"); + } + +} diff --git a/src/main/java/homework_7/function/KittenToCatFunction.java b/src/main/java/homework_7/function/KittenToCatFunction.java new file mode 100644 index 00000000..105be45e --- /dev/null +++ b/src/main/java/homework_7/function/KittenToCatFunction.java @@ -0,0 +1,11 @@ +package homework_7.function; + +import homework_7.model.cat_model.Cat; +import homework_7.model.kitten_model.Kitten; + +@FunctionalInterface +public interface KittenToCatFunction { + + C grow(K kitten); + +} diff --git a/src/main/java/homework_7/model/Sex.java b/src/main/java/homework_7/model/Sex.java new file mode 100644 index 00000000..2f42039e --- /dev/null +++ b/src/main/java/homework_7/model/Sex.java @@ -0,0 +1,17 @@ +package homework_7.model; + +public enum Sex { + + MALE ("male"), + FEMALE ("female"); + + private String sex; + + Sex(String sex) { + this.sex = sex; + } + + public String getSex() { + return sex; + } +} diff --git a/src/main/java/homework_7/model/cat_model/Cat.java b/src/main/java/homework_7/model/cat_model/Cat.java new file mode 100644 index 00000000..e658111b --- /dev/null +++ b/src/main/java/homework_7/model/cat_model/Cat.java @@ -0,0 +1,67 @@ +package homework_7.model.cat_model; + +import homework_7.model.Sex; + +public class Cat { + + protected String firstName; + protected int age; + protected Sex sex; + protected String worker; + + public Cat(String firstName, int age, Sex sex) { + this.firstName = firstName; + this.age = age; + this.sex = sex; + this.worker = "unemployed"; + } + + public Cat(String firstName, int age, Sex sex, String worker) { + this.firstName = firstName; + this.age = age; + this.sex = sex; + this.worker = worker; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public Sex getSex() { + return sex; + } + + public void setSex(Sex sex) { + this.sex = sex; + } + + public String getWorker() { + return worker; + } + + public void setWorker(String worker) { + this.worker = worker; + } + + @Override + public String toString() { + return "Cat{" + + "firstName='" + firstName + '\'' + + ", age=" + age + + ", sex=" + sex + + ", worker='" + worker + '\'' + + '}'; + } +} diff --git a/src/main/java/homework_7/model/cat_model/MilitaryCat.java b/src/main/java/homework_7/model/cat_model/MilitaryCat.java new file mode 100644 index 00000000..1abc2ee6 --- /dev/null +++ b/src/main/java/homework_7/model/cat_model/MilitaryCat.java @@ -0,0 +1,15 @@ +package homework_7.model.cat_model; + +import homework_7.model.Sex; + +public class MilitaryCat extends Cat { + + public MilitaryCat(String firstName, int age, Sex sex, String worker) { + super(firstName, age, sex, "Military"); + } + + public MilitaryCat(String name, int age, Sex sex) { + super(name, age, sex, "Military"); + } + +} diff --git a/src/main/java/homework_7/model/kitten_model/Kitten.java b/src/main/java/homework_7/model/kitten_model/Kitten.java new file mode 100644 index 00000000..a01d5d97 --- /dev/null +++ b/src/main/java/homework_7/model/kitten_model/Kitten.java @@ -0,0 +1,50 @@ +package homework_7.model.kitten_model; + +import homework_7.model.Sex; + +public class Kitten { + + protected String firstName; + protected int age; + protected Sex sex; + + public Kitten(String name, int age, Sex sex) { + if (age > 18) throw new IllegalArgumentException("too old for kitten"); + this.firstName = name; + this.age = age; + this.sex = sex; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public Sex getSex() { + return sex; + } + + public void setSex(Sex sex) { + this.sex = sex; + } + + @Override + public String toString() { + return "Kitten{" + + "firstName='" + firstName + '\'' + + ", age=" + age + + ", sex=" + sex + + '}'; + } +} From aee0d31fd664e220887adcdc0675d71fd610c8d4 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Mon, 13 Sep 2021 16:12:55 +0300 Subject: [PATCH 49/57] add hw6 --- src/main/java/homework_6/Main.java | 76 +++++++++++++++++++ .../MapProblemsCollisionGenerator.java | 31 ++++++++ .../map_problems/MapProblemsGenerator.java | 41 ++++++++++ .../MapProblemsMutableGenerator.java | 34 +++++++++ 4 files changed, 182 insertions(+) create mode 100644 src/main/java/homework_6/Main.java create mode 100644 src/main/java/homework_6/map_problems/MapProblemsCollisionGenerator.java create mode 100644 src/main/java/homework_6/map_problems/MapProblemsGenerator.java create mode 100644 src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..06b3298b --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,76 @@ +package homework_6; + +import homework_6.map_problems.MapProblemsMutableGenerator; + +import java.awt.*; +import java.util.HashMap; +import java.util.Map; + + +//сделано в срок, писал в личку +public class Main { + + public static void main(String[] args) { + + new Main().runMapProblemsMutable(); + new Main().runMapProblemsCollision(); + + } + + private void runMapProblemsMutable() { + System.out.println("MapProblemsMutable"); + + Map map = new HashMap<>(); + + MapProblemsMutableGenerator o1 = new MapProblemsMutableGenerator("First obj", 1, new Color(183, 86, 192)); + MapProblemsMutableGenerator o2 = new MapProblemsMutableGenerator("Second obj", 2, new Color(197, 193, 78)); + MapProblemsMutableGenerator o3 = new MapProblemsMutableGenerator("Third obj", 3, new Color(73, 113, 166)); + MapProblemsMutableGenerator on = new MapProblemsMutableGenerator("Nth obj", Integer.MAX_VALUE, new Color(61, 199, 176)); + + MapProblemsMutableGenerator o1Clone = new MapProblemsMutableGenerator("First obj", 1, new Color(183, 86, 192)); + + System.out.println("\no1 equals with all objects"); + System.out.println("o1.equals(o2) = " + o1.equals(o2)); + System.out.println("o1.equals(o3) = " + o1.equals(o3)); + System.out.println("o1.equals(on) = " + o1.equals(on)); + + System.out.println("\no2 equals with all objects"); + System.out.println("o2.equals(o1) = " + o2.equals(o1)); + System.out.println("o2.equals(o3) = " + o2.equals(o3)); + System.out.println("o2.equals(on) = " + o2.equals(on)); + + System.out.println("\no3 equals with all objects"); + System.out.println("o3.equals(o1) = " + o3.equals(o1)); + System.out.println("o3.equals(o2) = " + o3.equals(o2)); + System.out.println("o3.equals(on) = " + o3.equals(on)); + + System.out.println("\non equals with all objects"); + System.out.println("on.equals(o1) = " + on.equals(o1)); + System.out.println("on.equals(o2) = " + on.equals(o2)); + System.out.println("on.equals(o3) = " + on.equals(o3)); + + map.put(o1, 2); + map.put(o2, 1); + map.put(o3, 1); + map.put(on, 1); + + + System.out.println("\ntry find o1"); + Integer temp; + int count = 0; + do { + temp = map.get(o1); + count++; + } while (temp == null); + System.out.println("count = " + count + ", temp = " + temp); + System.out.println("(o1.getClazzAge() == temp) = " + (o1.getClazzAge() == temp)); + + System.out.println("\no1 equals with o1Clone"); + System.out.println("o1.equals(o1Clone) = " + o1.equals(o1Clone)); + } + + private void runMapProblemsCollision() { + } + + +} diff --git a/src/main/java/homework_6/map_problems/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problems/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..505f5601 --- /dev/null +++ b/src/main/java/homework_6/map_problems/MapProblemsCollisionGenerator.java @@ -0,0 +1,31 @@ +package homework_6.map_problems; + +import java.awt.*; + +public class MapProblemsCollisionGenerator extends MapProblemsGenerator { + + public MapProblemsCollisionGenerator(String clazzName, int clazzAge, Color clazzColor) { + super(clazzName, clazzAge, clazzColor); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsCollisionGenerator that = (MapProblemsCollisionGenerator) o; + return clazzAge == that.clazzAge && clazzName.equals(that.clazzName) && clazzColor.equals(that.clazzColor); + } + @Override + public int hashCode() { + return 1; + } + + @Override + public String toString() { + return "MapProblemsCollisionGenerator{" + + "clazzName='" + clazzName + '\'' + + ", clazzAge=" + clazzAge + + ", clazzColor=" + clazzColor + + '}'; + } +} diff --git a/src/main/java/homework_6/map_problems/MapProblemsGenerator.java b/src/main/java/homework_6/map_problems/MapProblemsGenerator.java new file mode 100644 index 00000000..988e1248 --- /dev/null +++ b/src/main/java/homework_6/map_problems/MapProblemsGenerator.java @@ -0,0 +1,41 @@ +package homework_6.map_problems; + +import java.awt.*; + +public abstract class MapProblemsGenerator { + + protected String clazzName; + protected int clazzAge; + protected Color clazzColor; + + public MapProblemsGenerator(String clazzName, int clazzAge, Color clazzColor) { + this.clazzName = clazzName; + this.clazzAge = clazzAge; + this.clazzColor = clazzColor; + } + + public String getClazzName() { + return clazzName; + } + + public void setClazzName(String clazzName) { + this.clazzName = clazzName; + } + + public int getClazzAge() { + return clazzAge; + } + + public void setClazzAge(int clazzAge) { + this.clazzAge = clazzAge; + } + + public Color getClazzColor() { + return clazzColor; + } + + public void setClazzColor(Color clazzColor) { + this.clazzColor = clazzColor; + } + +} diff --git a/src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..e7a996b0 --- /dev/null +++ b/src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java @@ -0,0 +1,34 @@ +package homework_6.map_problems; + +import java.awt.*; +import java.util.Random; + +public class MapProblemsMutableGenerator extends MapProblemsGenerator { + + public MapProblemsMutableGenerator(String clazzName, int clazzAge, Color clazzColor) { + super(clazzName, clazzAge, clazzColor); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return clazzAge == that.clazzAge && clazzName.equals(that.clazzName) && clazzColor.equals(that.clazzColor); + } + + @Override + public int hashCode() { + return new Random().nextInt(10); +// return new Random().nextInt(); + } + + @Override + public String toString() { + return "MapProblemsMutableGenerator{" + + "clazzName='" + clazzName + '\'' + + ", clazzAge=" + clazzAge + + ", clazzColor=" + clazzColor + + '}'; + } +} From 4f7d50c224429cea6449cef8b0abe54968700e46 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Sun, 19 Sep 2021 21:46:04 +0300 Subject: [PATCH 50/57] beta 1 --- src/main/java/course_project/Game.java | 94 +++++++++++++++++++ src/main/java/course_project/Main.java | 11 +++ .../course_project/services/FieldPrinter.java | 94 +++++++++++++++++++ .../course_project/services/GameService.java | 79 ++++++++++++++++ .../services/PlayerController.java | 67 +++++++++++++ .../ship/abstracts/SinglePartShip.java | 51 ++++++++++ .../ship/abstracts/TypeShip.java | 25 +++++ .../course_project/ship/models/Player.java | 62 ++++++++++++ .../java/course_project/ship/models/Ship.java | 26 +++++ 9 files changed, 509 insertions(+) create mode 100644 src/main/java/course_project/Game.java create mode 100644 src/main/java/course_project/Main.java create mode 100644 src/main/java/course_project/services/FieldPrinter.java create mode 100644 src/main/java/course_project/services/GameService.java create mode 100644 src/main/java/course_project/services/PlayerController.java create mode 100644 src/main/java/course_project/ship/abstracts/SinglePartShip.java create mode 100644 src/main/java/course_project/ship/abstracts/TypeShip.java create mode 100644 src/main/java/course_project/ship/models/Player.java create mode 100644 src/main/java/course_project/ship/models/Ship.java diff --git a/src/main/java/course_project/Game.java b/src/main/java/course_project/Game.java new file mode 100644 index 00000000..a7b203a9 --- /dev/null +++ b/src/main/java/course_project/Game.java @@ -0,0 +1,94 @@ +package course_project; + +import base.BaseClazz; +import course_project.services.FieldPrinter; +import course_project.services.PlayerController; +import course_project.ship.abstracts.SinglePartShip; +import course_project.ship.models.Player; +import course_project.ship.abstracts.TypeShip; + +import java.awt.*; +import java.awt.event.InputEvent; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Stream; + +import static course_project.services.GameService.*; + +public class Game extends BaseClazz { + + private final Player player = new Player("player"); + private final Player computer = new Player("computer"); + + public static Scanner scanner = new Scanner(System.in); + + private static final Function> convert = + elem -> elem + .getShips() + .values() + .stream() + .flatMap(e -> e + .stream() + .flatMap(l -> l.getList().stream())); + + @Override + public void run() { + initPlayer(computer); + initPlayer(player); + startGame(); + } + + private void startGame() { + Player aim = computer; + Player attacker = player; + while (!(player.isEmptyShips() || computer.isEmptyShips())) { + FieldPrinter.printFiled(convert.apply(attacker), attacker.getHitsMap()); + if (playersHit(aim, attacker)) { + System.out.println("Вражеский корабль подбит"); + } else { + aim = (aim == computer ? player : computer); + attacker = (attacker == computer ? player : computer); + clearConsole(); + System.out.println("Промах. В следующий раз повезет"); + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + System.out.println("Победил " + attacker.getName()); + } + + private void initPlayer(Player gamer) { + + FieldPrinter.printFieldForInit(convert.apply(gamer)); + PlayerController.initShipLists(gamer, TypeShip.SINGLE_DECK, 4); + FieldPrinter.printFieldForInit(convert.apply(gamer)); + PlayerController.initShipLists(gamer, TypeShip.DOUBLE_DECK, 3); + FieldPrinter.printFieldForInit(convert.apply(gamer)); + PlayerController.initShipLists(gamer, TypeShip.THREE_DECK, 2); + FieldPrinter.printFieldForInit(convert.apply(gamer)); + PlayerController.initShipLists(gamer, TypeShip.FOUR_DECK, 1); + } + + private void initPlayer1(Player gamer) { + PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "A10", "V", 1); + PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "D9", "V", 1); + PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "F9", "V", 1); + PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "G6", "V", 1); + PlayerController.addToList(gamer, TypeShip.DOUBLE_DECK, "A1", "H", 2); + PlayerController.addToList(gamer, TypeShip.DOUBLE_DECK, "J3", "V", 2); + PlayerController.addToList(gamer, TypeShip.DOUBLE_DECK, "I9", "V", 2); + PlayerController.addToList(gamer, TypeShip.THREE_DECK, "D1", "V", 3); + PlayerController.addToList(gamer, TypeShip.THREE_DECK, "B5", "V", 3); + PlayerController.addToList(gamer, TypeShip.FOUR_DECK, "G1", "H", 4); + } + + private void clearConsole() { + for (int i = 0; i < 10; i++) { + System.out.println(); + } + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..45e469da --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +public class Main { + + public static void main(String[] args) { + + new Game().run(); + + } + +} diff --git a/src/main/java/course_project/services/FieldPrinter.java b/src/main/java/course_project/services/FieldPrinter.java new file mode 100644 index 00000000..4fc3019b --- /dev/null +++ b/src/main/java/course_project/services/FieldPrinter.java @@ -0,0 +1,94 @@ +package course_project.services; + +import course_project.ship.abstracts.SinglePartShip; + +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class FieldPrinter { + + private static final int FIELD_CAPACITY = 10; + protected static final String ANSI_RESET = "\033[0m"; + protected static final String ANSI_GREEN = "\u001B[32m"; + protected static final String ANSI_CYAN = "\u001B[36m"; + + private FieldPrinter() { + throw new IllegalStateException("Utility class"); + } + + public static void printFieldForInit(Stream attacker) { + int[][] attackerField = new int[FIELD_CAPACITY][FIELD_CAPACITY]; + attacker.forEach(elem -> add(attackerField, elem, 1)); + printTableHeader(); + System.out.println(); + for (int i = 0; i < FIELD_CAPACITY; i++) { + printLineTable(i, attackerField); + System.out.println(); + } + } + + public static void printFiled(Stream attacker, Map> opponent) { + int[][] attackerField = new int[FIELD_CAPACITY][FIELD_CAPACITY]; + int[][] opponentField = new int[FIELD_CAPACITY][FIELD_CAPACITY]; + attacker.forEach(elem -> add(attackerField, elem, 1)); + opponent.entrySet().forEach(elem -> add(opponentField, elem)); + + System.out.printf("%-51s", "your field"); + System.out.println("opponent field"); + + printTableHeader(); + System.out.printf("%4s", " | "); + printTableHeader(); + System.out.println(); + + for (int i = 0; i < FIELD_CAPACITY; i++) { + printLineTable(i, attackerField); + System.out.printf("%4s", " | "); + printLineOpponentTable(i, opponentField); + System.out.println(); + } + } + + private static void printTableHeader() { + System.out.printf("%4s", ""); + IntStream.range(0, FIELD_CAPACITY).forEach(i -> System.out.printf("%4s", (char) (65 + i))); + } + + private static void printLineTable(int i, int[][] field) { + System.out.printf("%4s", i + 1); + for (int j = 0; j < FIELD_CAPACITY; j++) { + if (field[i][j] == 1) { + System.out.printf("%13s", ANSI_GREEN + "x" + ANSI_RESET); + } else { + System.out.printf("%4s", "."); + } + } + } + + private static void printLineOpponentTable(int i, int[][] field) { + System.out.printf("%4s", i + 1); + for (int j = 0; j < FIELD_CAPACITY; j++) { + if (field[i][j] == 1) { + System.out.printf("%13s", ANSI_GREEN + "x" + ANSI_RESET); + } else if (field[i][j] == -1) { + System.out.printf("%13s", ANSI_CYAN + "o" + ANSI_RESET); + } else { + System.out.printf("%4s", "?"); + } + } + } + + private static void add(int[][] field, SinglePartShip partShip, int value) { + field[partShip.getY() - 1][partShip.getX() - 1] = value; + } + + private static void add(int[][] field, Map.Entry> partShip) { + if (partShip.getKey()) { + partShip.getValue().forEach(elem -> add(field, elem, 1)); + } else { + partShip.getValue().forEach(elem -> add(field, elem, -1)); + } + } +} \ No newline at end of file diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java new file mode 100644 index 00000000..0ef0f1f6 --- /dev/null +++ b/src/main/java/course_project/services/GameService.java @@ -0,0 +1,79 @@ +package course_project.services; + +import course_project.Game; +import course_project.ship.models.Player; +import course_project.ship.abstracts.SinglePartShip; + +import java.util.Locale; + +public final class GameService { + + private GameService() { + throw new IllegalStateException("Utility class"); + } + + public static boolean playersHit(Player aim, Player attacker) { + String coordinates = getNewCoordinates(attacker.getName()); + SinglePartShip partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); + attacker.getHitsMap().get(aim.containsShip(partShip)).add(partShip); + if (aim.containsShip(partShip)) { + PlayerController.destroyPartShip(aim, partShip); + return true; + } + return false; + } + + public static boolean isNeighbor(Player gamer, SinglePartShip partShip) { + int x = partShip.getX(); + int y = partShip.getY(); + return gamer.containsShip(partShip.setX(x - 1)) ||//-x + gamer.containsShip(partShip.setX(x - 1).setY(y + 1)) ||//-x +y + gamer.containsShip(partShip.setY(y + 1)) ||//+y + gamer.containsShip(partShip.setX(x + 1).setY(y + 1)) ||//+x +y + gamer.containsShip(partShip.setX(x + 1));//+x + } + + public static boolean isHeaderNeighbor(Player gamer, SinglePartShip partShip) { + int x = partShip.getX(); + int y = partShip.getY(); + + return gamer.containsShip(partShip.setX(x - 1).setY(y - 1)) ||//-x -y + gamer.containsShip(partShip.setY(y - 1)) ||//-y + gamer.containsShip(partShip.setX(x + 1).setY(y - 1));//+x -y + } + + public static String getNewCoordinates(String name) { + System.out.printf(name + ": введите координаты цели([A-J][1-10]): "); + String coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); + while (!isValidCoordinatesForShot(coordinates)) { + System.out.printf(name + ": введите координаты цели([A-J][1-10]): "); + coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); + } + return coordinates; + } + + public static String getNewCoordinates(int numberOfShip, int numberOfShipDeck) { + System.out.printf("Введите координаты и положение %1$s-ого %2$s-палубного корабля([A-J][1-10] [v|h]): ", numberOfShip, numberOfShipDeck); + String coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); + while (!isValidCoordinatesForShip(coordinates)) { + System.out.printf("Введите координаты и положение %1$s-ого %2$s-палубного корабля([A-J][1-10] [v|h]): ", numberOfShip, numberOfShipDeck); + coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); + } + return coordinates; + } + + private static boolean isValidCoordinatesForShot(String... arg) { + if (arg[0].split("\\s").length > 1) { + return false; + } + return arg[0].matches("[A-J][1-9][0]*"); + } + + private static boolean isValidCoordinatesForShip(String... arg) { + if (arg[0].split("\\s").length != 2) { + return false; + } + String[] split = arg[0].split("\\s"); + return split[0].matches("[A-J]([1-9]|10)") && split[1].matches("[VH]"); + } +} diff --git a/src/main/java/course_project/services/PlayerController.java b/src/main/java/course_project/services/PlayerController.java new file mode 100644 index 00000000..ec4aedc6 --- /dev/null +++ b/src/main/java/course_project/services/PlayerController.java @@ -0,0 +1,67 @@ +package course_project.services; + +import course_project.ship.abstracts.TypeShip; +import course_project.ship.models.Player; +import course_project.ship.models.Ship; +import course_project.ship.abstracts.SinglePartShip; + +import java.util.*; + +import static course_project.services.GameService.isHeaderNeighbor; +import static course_project.services.GameService.isNeighbor; + +public final class PlayerController { + + private static final String ANSI_RESET = "\033[0m"; + private static final String ANSI_RED = "\u001B[31m"; + + private PlayerController() { + throw new IllegalStateException("Utility class"); + } + + public static void destroyPartShip(Player player, SinglePartShip partShip) { + Map> ships = player.getShips(); + Collection> values = ships.values(); + + values + .forEach(shipList -> shipList + .forEach(elem -> elem + .getList() + .removeIf(next -> next.equals(partShip)))); + } + + public static void initShipLists(Player gamer, TypeShip typeShip, int countOfDeck) { + for (int i = 0; i < countOfDeck; i++) { + String coordinates = GameService.getNewCoordinates(i + 1, 5 - countOfDeck); + if (!addToList(gamer, typeShip, coordinates.split("\\s")[0], coordinates.split("\\s")[1], 5 - countOfDeck)) { + System.out.println(ANSI_RED + "Что-то пошло не так, попробуйте еще раз" + ANSI_RESET); + i--; + } + } + } + + public static boolean addToList(Player gamer, TypeShip typeShip, String coordinates, String location, int countOfDeck) { + List tempList = new ArrayList<>(); + SinglePartShip partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); + for (int i = 0; i < countOfDeck; i++) { + if (i == 0 && isHeaderNeighbor(gamer, partShip)) { + return false; + } + if (gamer.containsShip(partShip) || + ((location.equals("V") ? partShip.getY() : partShip.getX()) > 10 && i + 1 < countOfDeck) || + isNeighbor(gamer, partShip)) { + return false; + } + tempList.add(partShip); + if (location.equals("V")) { + partShip = partShip.setY(partShip.getY() + 1); + } else { + partShip = partShip.setX(partShip.getX() + 1); + } + } + gamer.getShips().get(typeShip.getType()).add(new Ship(tempList)); + return true; + } + + +} diff --git a/src/main/java/course_project/ship/abstracts/SinglePartShip.java b/src/main/java/course_project/ship/abstracts/SinglePartShip.java new file mode 100644 index 00000000..3a2e46ca --- /dev/null +++ b/src/main/java/course_project/ship/abstracts/SinglePartShip.java @@ -0,0 +1,51 @@ +package course_project.ship.abstracts; + +import java.util.Objects; + +public class SinglePartShip { + + private Integer x; + private Integer y; + + public SinglePartShip(Integer x, Integer y) { + this.x = x; + this.y = y; + } + + public Integer getX() { + return x; + } + + public SinglePartShip setX(Integer x) { + return new SinglePartShip(x, this.y); + } + + public Integer getY() { + return y; + } + + public SinglePartShip setY(Integer y) { + return new SinglePartShip(this.x, y); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SinglePartShip partShip = (SinglePartShip) o; + return Objects.equals(x, partShip.x) && Objects.equals(y, partShip.y); + } + + @Override + public int hashCode() { + return Objects.hash(x, y); + } + + @Override + public String toString() { + return "{" + + "x=" + x + + ", y=" + y + + '}'; + } +} diff --git a/src/main/java/course_project/ship/abstracts/TypeShip.java b/src/main/java/course_project/ship/abstracts/TypeShip.java new file mode 100644 index 00000000..c0661782 --- /dev/null +++ b/src/main/java/course_project/ship/abstracts/TypeShip.java @@ -0,0 +1,25 @@ +package course_project.ship.abstracts; + +public enum TypeShip { + + SINGLE_DECK ("SingleDeckShip", 4), + DOUBLE_DECK ("DoubleDeckShip", 3), + THREE_DECK ("ThreeDeckShip", 2), + FOUR_DECK ("FourDeckShip", 1); + + private String type; + private int count; + + TypeShip(String type, int count) { + this.type = type; + this.count = count; + } + + public String getType() { + return type; + } + + public int getCount() { + return count; + } +} diff --git a/src/main/java/course_project/ship/models/Player.java b/src/main/java/course_project/ship/models/Player.java new file mode 100644 index 00000000..e424b630 --- /dev/null +++ b/src/main/java/course_project/ship/models/Player.java @@ -0,0 +1,62 @@ +package course_project.ship.models; + +import course_project.ship.models.Ship; +import course_project.ship.abstracts.SinglePartShip; +import course_project.ship.abstracts.TypeShip; + +import java.util.*; +import java.util.stream.Stream; + +public class Player { + + private String name; + private final Map> ships = new HashMap<>(); + private final Map> hitsList = new HashMap<>(); + + public Player(String name) { + this.name = name; + ships.put(TypeShip.SINGLE_DECK.getType(), new ArrayList<>()); + ships.put(TypeShip.DOUBLE_DECK.getType(),new ArrayList<>()); + ships.put(TypeShip.THREE_DECK.getType(), new ArrayList<>()); + ships.put(TypeShip.FOUR_DECK.getType(), new ArrayList<>()); + + hitsList.put(Boolean.TRUE, new ArrayList<>()); + hitsList.put(Boolean.FALSE, new ArrayList<>()); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map> getShips() { + return ships; + } + + public Map> getHitsMap() { + return hitsList; + } + + public boolean containsShip(SinglePartShip singlePartShip) { + Stream singlePartShipStream = ships + .values() + .stream() + .flatMap(elem -> elem + .stream() + .flatMap(l -> l.getList().stream())); + return singlePartShipStream.anyMatch(elem -> elem.equals(singlePartShip)); + } + + public boolean isEmptyShips() { + Stream singlePartShipStream = ships + .values() + .stream() + .flatMap(elem -> elem + .stream() + .flatMap(l -> l.getList().stream())); + return !singlePartShipStream.findAny().isPresent(); + } +} diff --git a/src/main/java/course_project/ship/models/Ship.java b/src/main/java/course_project/ship/models/Ship.java new file mode 100644 index 00000000..991c0a72 --- /dev/null +++ b/src/main/java/course_project/ship/models/Ship.java @@ -0,0 +1,26 @@ +package course_project.ship.models; + +import course_project.ship.abstracts.SinglePartShip; + +import java.util.ArrayList; +import java.util.List; + +public class Ship { + + private final List list = new ArrayList<>(); + + public Ship() { + } + + public Ship(List list) { + this.list.addAll(list); + } + + public boolean contains(SinglePartShip singlePartShip) { + return list.contains(singlePartShip); + } + + public List getList() { + return list; + } +} From d17e9373f1cc6c8920654ef84b42d6dc0b8e75bc Mon Sep 17 00:00:00 2001 From: pepyachka Date: Tue, 21 Sep 2021 02:42:11 +0300 Subject: [PATCH 51/57] refactor hw6 MapProblemsGenerator --- src/main/java/homework_6/Main.java | 63 +++++-------------- .../MapProblemsMutableGenerator.java | 3 +- 2 files changed, 16 insertions(+), 50 deletions(-) diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java index 06b3298b..d06b241b 100644 --- a/src/main/java/homework_6/Main.java +++ b/src/main/java/homework_6/Main.java @@ -1,5 +1,6 @@ package homework_6; +import homework_6.map_problems.MapProblemsCollisionGenerator; import homework_6.map_problems.MapProblemsMutableGenerator; import java.awt.*; @@ -18,58 +19,24 @@ public static void main(String[] args) { } private void runMapProblemsMutable() { - System.out.println("MapProblemsMutable"); - + MapProblemsMutableGenerator val = new MapProblemsMutableGenerator("Cat", 1, new Color(183, 86, 192)); Map map = new HashMap<>(); - - MapProblemsMutableGenerator o1 = new MapProblemsMutableGenerator("First obj", 1, new Color(183, 86, 192)); - MapProblemsMutableGenerator o2 = new MapProblemsMutableGenerator("Second obj", 2, new Color(197, 193, 78)); - MapProblemsMutableGenerator o3 = new MapProblemsMutableGenerator("Third obj", 3, new Color(73, 113, 166)); - MapProblemsMutableGenerator on = new MapProblemsMutableGenerator("Nth obj", Integer.MAX_VALUE, new Color(61, 199, 176)); - - MapProblemsMutableGenerator o1Clone = new MapProblemsMutableGenerator("First obj", 1, new Color(183, 86, 192)); - - System.out.println("\no1 equals with all objects"); - System.out.println("o1.equals(o2) = " + o1.equals(o2)); - System.out.println("o1.equals(o3) = " + o1.equals(o3)); - System.out.println("o1.equals(on) = " + o1.equals(on)); - - System.out.println("\no2 equals with all objects"); - System.out.println("o2.equals(o1) = " + o2.equals(o1)); - System.out.println("o2.equals(o3) = " + o2.equals(o3)); - System.out.println("o2.equals(on) = " + o2.equals(on)); - - System.out.println("\no3 equals with all objects"); - System.out.println("o3.equals(o1) = " + o3.equals(o1)); - System.out.println("o3.equals(o2) = " + o3.equals(o2)); - System.out.println("o3.equals(on) = " + o3.equals(on)); - - System.out.println("\non equals with all objects"); - System.out.println("on.equals(o1) = " + on.equals(o1)); - System.out.println("on.equals(o2) = " + on.equals(o2)); - System.out.println("on.equals(o3) = " + on.equals(o3)); - - map.put(o1, 2); - map.put(o2, 1); - map.put(o3, 1); - map.put(on, 1); - - - System.out.println("\ntry find o1"); - Integer temp; - int count = 0; - do { - temp = map.get(o1); - count++; - } while (temp == null); - System.out.println("count = " + count + ", temp = " + temp); - System.out.println("(o1.getClazzAge() == temp) = " + (o1.getClazzAge() == temp)); - - System.out.println("\no1 equals with o1Clone"); - System.out.println("o1.equals(o1Clone) = " + o1.equals(o1Clone)); + map.put(val, 123); + val.setClazzAge(21); + System.out.println("map.containsKey(val) = " + map.containsKey(val)); } private void runMapProblemsCollision() { + MapProblemsCollisionGenerator val1 = new MapProblemsCollisionGenerator("Cat", 1, new Color(183, 86, 192)); + MapProblemsCollisionGenerator val2 = new MapProblemsCollisionGenerator("Dog", 2, new Color(197, 193, 78)); + Map map = new HashMap<>(); + + map.put(val1, "Murzik"); + map.put(val2, "Sharik"); + + System.out.println("map = " + map); + System.out.println("map.get(val1) = " + map.get(val1)); + System.out.println("map.get(val2) = " + map.get(val2)); } diff --git a/src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java index e7a996b0..01258344 100644 --- a/src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java +++ b/src/main/java/homework_6/map_problems/MapProblemsMutableGenerator.java @@ -19,8 +19,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - return new Random().nextInt(10); -// return new Random().nextInt(); + return Integer.hashCode(clazzAge) + clazzName.hashCode(); } @Override From d8ee91a7af6ee403a9e11ae658970af3a16fb421 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Tue, 21 Sep 2021 02:46:14 +0300 Subject: [PATCH 52/57] refactor hw6 MapProblemsGenerator --- src/main/java/homework_6/Main.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java index d06b241b..725bd6af 100644 --- a/src/main/java/homework_6/Main.java +++ b/src/main/java/homework_6/Main.java @@ -33,10 +33,7 @@ private void runMapProblemsCollision() { map.put(val1, "Murzik"); map.put(val2, "Sharik"); - - System.out.println("map = " + map); - System.out.println("map.get(val1) = " + map.get(val1)); - System.out.println("map.get(val2) = " + map.get(val2)); + //now we have only 1 bucket } From f5fa48000438a7636cf8945b1ad1f1be52833594 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Tue, 21 Sep 2021 20:41:40 +0300 Subject: [PATCH 53/57] beta 2 --- src/main/java/course_project/Game.java | 12 ++-- .../course_project/services/GameService.java | 62 ++++++++++++++++++- .../services/PlayerController.java | 13 ++-- .../ship/abstracts/TypeShip.java | 10 +++ 4 files changed, 82 insertions(+), 15 deletions(-) diff --git a/src/main/java/course_project/Game.java b/src/main/java/course_project/Game.java index a7b203a9..7e923cc6 100644 --- a/src/main/java/course_project/Game.java +++ b/src/main/java/course_project/Game.java @@ -2,13 +2,12 @@ import base.BaseClazz; import course_project.services.FieldPrinter; +import course_project.services.GameService; import course_project.services.PlayerController; import course_project.ship.abstracts.SinglePartShip; import course_project.ship.models.Player; import course_project.ship.abstracts.TypeShip; -import java.awt.*; -import java.awt.event.InputEvent; import java.util.*; import java.util.function.Function; import java.util.stream.Stream; @@ -33,8 +32,8 @@ public class Game extends BaseClazz { @Override public void run() { - initPlayer(computer); - initPlayer(player); + player.getShips().putAll(GameService.getNewPlayerWithRandomShips(player.getName()).getShips()); + computer.getShips().putAll(GameService.getNewPlayerWithRandomShips(computer.getName()).getShips()); startGame(); } @@ -51,7 +50,7 @@ private void startGame() { clearConsole(); System.out.println("Промах. В следующий раз повезет"); try { - Thread.sleep(10000); + Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } @@ -61,7 +60,6 @@ private void startGame() { } private void initPlayer(Player gamer) { - FieldPrinter.printFieldForInit(convert.apply(gamer)); PlayerController.initShipLists(gamer, TypeShip.SINGLE_DECK, 4); FieldPrinter.printFieldForInit(convert.apply(gamer)); @@ -86,7 +84,7 @@ private void initPlayer1(Player gamer) { } private void clearConsole() { - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 20; i++) { System.out.println(); } } diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java index 0ef0f1f6..3ee2dd34 100644 --- a/src/main/java/course_project/services/GameService.java +++ b/src/main/java/course_project/services/GameService.java @@ -1,13 +1,26 @@ package course_project.services; import course_project.Game; +import course_project.ship.abstracts.TypeShip; import course_project.ship.models.Player; import course_project.ship.abstracts.SinglePartShip; -import java.util.Locale; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.*; public final class GameService { + private static Random rand; + + static { + try { + rand = SecureRandom.getInstanceStrong(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + } + private GameService() { throw new IllegalStateException("Utility class"); } @@ -23,7 +36,7 @@ public static boolean playersHit(Player aim, Player attacker) { return false; } - public static boolean isNeighbor(Player gamer, SinglePartShip partShip) { + public static boolean isVerticalNeighbor(Player gamer, SinglePartShip partShip) { int x = partShip.getX(); int y = partShip.getY(); return gamer.containsShip(partShip.setX(x - 1)) ||//-x @@ -33,13 +46,29 @@ public static boolean isNeighbor(Player gamer, SinglePartShip partShip) { gamer.containsShip(partShip.setX(x + 1));//+x } + public static boolean isHorizontalNeighbor(Player gamer, SinglePartShip partShip) { + int x = partShip.getX(); + int y = partShip.getY(); + return gamer.containsShip(partShip.setY(y - 1)) ||//-y + gamer.containsShip(partShip.setX(x + 1).setY(y - 1)) ||//+x -y + gamer.containsShip(partShip.setX(x + 1)) ||//+x + gamer.containsShip(partShip.setX(x + 1).setY(y + 1)) ||//+x +y + gamer.containsShip(partShip.setY(y + 1));//+y + } + + public static boolean isHeaderNeighbor(Player gamer, SinglePartShip partShip) { int x = partShip.getX(); int y = partShip.getY(); return gamer.containsShip(partShip.setX(x - 1).setY(y - 1)) ||//-x -y gamer.containsShip(partShip.setY(y - 1)) ||//-y - gamer.containsShip(partShip.setX(x + 1).setY(y - 1));//+x -y + gamer.containsShip(partShip.setX(x + 1).setY(y - 1)) ||//+x -y + gamer.containsShip(partShip.setX(x - 1)) ||//-x + gamer.containsShip(partShip.setX(x + 1)) ||//+x + gamer.containsShip(partShip.setX(x - 1).setY(y + 1)) ||//-x +y + gamer.containsShip(partShip.setY(y + 1)) ||//+y + gamer.containsShip(partShip.setX(x + 1).setY(y + 1));//+x +y } public static String getNewCoordinates(String name) { @@ -62,6 +91,29 @@ public static String getNewCoordinates(int numberOfShip, int numberOfShipDeck) { return coordinates; } + public static Player getNewPlayerWithRandomShips(String name) { + Player tempPlayer = new Player(name); + + for (int i = 0; i < 4; i++) { + + for (int j = i; j < 4; j++) { + + String coordinates = getRandomCoordinates(); + String location = rand.nextBoolean() ? "V" : "H"; + + SinglePartShip partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); + while (tempPlayer.containsShip(partShip) || + !PlayerController.addToList(tempPlayer, TypeShip.getType(i + 1), coordinates, location, i + 1)) { + coordinates = getRandomCoordinates(); + location = rand.nextBoolean() ? "V" : "H"; + partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); + } + } + } + + return tempPlayer; + } + private static boolean isValidCoordinatesForShot(String... arg) { if (arg[0].split("\\s").length > 1) { return false; @@ -76,4 +128,8 @@ private static boolean isValidCoordinatesForShip(String... arg) { String[] split = arg[0].split("\\s"); return split[0].matches("[A-J]([1-9]|10)") && split[1].matches("[VH]"); } + + private static String getRandomCoordinates() { + return (char) (65 + rand.nextInt(10)) + String.valueOf(rand.nextInt(10) + 1); + } } diff --git a/src/main/java/course_project/services/PlayerController.java b/src/main/java/course_project/services/PlayerController.java index ec4aedc6..3a6b8893 100644 --- a/src/main/java/course_project/services/PlayerController.java +++ b/src/main/java/course_project/services/PlayerController.java @@ -7,8 +7,7 @@ import java.util.*; -import static course_project.services.GameService.isHeaderNeighbor; -import static course_project.services.GameService.isNeighbor; +import static course_project.services.GameService.*; public final class PlayerController { @@ -47,9 +46,13 @@ public static boolean addToList(Player gamer, TypeShip typeShip, String coordina if (i == 0 && isHeaderNeighbor(gamer, partShip)) { return false; } - if (gamer.containsShip(partShip) || - ((location.equals("V") ? partShip.getY() : partShip.getX()) > 10 && i + 1 < countOfDeck) || - isNeighbor(gamer, partShip)) { + if (gamer.containsShip(partShip)) { + return false; + } + if ((partShip.getX() > 10 || partShip.getY() > 10)) { + return false; + } + if (location.equals("V") ? isVerticalNeighbor(gamer, partShip) : isHorizontalNeighbor(gamer, partShip)) { return false; } tempList.add(partShip); diff --git a/src/main/java/course_project/ship/abstracts/TypeShip.java b/src/main/java/course_project/ship/abstracts/TypeShip.java index c0661782..2c81b7c2 100644 --- a/src/main/java/course_project/ship/abstracts/TypeShip.java +++ b/src/main/java/course_project/ship/abstracts/TypeShip.java @@ -19,6 +19,16 @@ public String getType() { return type; } + public static TypeShip getType(int n) { + switch (n) { + case 1: return TypeShip.SINGLE_DECK; + case 2: return TypeShip.DOUBLE_DECK; + case 3: return TypeShip.THREE_DECK; + case 4: return TypeShip.FOUR_DECK; + } + return null; + } + public int getCount() { return count; } From 07b95a77b771c88167aa9ca6772920ef8c9de589 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Tue, 21 Sep 2021 20:45:04 +0300 Subject: [PATCH 54/57] refactor hw5 PowerOfNumber --- .../java/homework_5/power_of_number/PowerOfNumber.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java index 8051f1e9..1aee2b37 100644 --- a/src/main/java/homework_5/power_of_number/PowerOfNumber.java +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -33,10 +33,11 @@ private String printPowResult() { } private BigInteger pow(BigInteger a, BigInteger b) { - if (b.compareTo(BigInteger.valueOf(0)) == 0) return BigInteger.valueOf(1); - b = b.subtract(BigInteger.valueOf(1)); - a = a.multiply(pow(a, b)); - return a; + if (b.compareTo(BigInteger.valueOf(0)) == 0) { + return BigInteger.valueOf(1); + } + BigInteger newB = b.subtract(BigInteger.valueOf(1)); + return a.multiply(pow(a, newB)); } @Override From 203ef1d54489d14431a9e17095116325fcdd0914 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Tue, 21 Sep 2021 21:31:46 +0300 Subject: [PATCH 55/57] CP: add some message for players --- src/main/java/course_project/Game.java | 12 ++++++++---- .../course_project/services/GameService.java | 16 ++++++++++++---- .../services/PlayerController.java | 16 ++++++++++------ 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/src/main/java/course_project/Game.java b/src/main/java/course_project/Game.java index 7e923cc6..bd82ca9e 100644 --- a/src/main/java/course_project/Game.java +++ b/src/main/java/course_project/Game.java @@ -16,6 +16,8 @@ public class Game extends BaseClazz { + private static String MISS = "Промах. В следующий раз повезет"; + private final Player player = new Player("player"); private final Player computer = new Player("computer"); @@ -42,18 +44,20 @@ private void startGame() { Player attacker = player; while (!(player.isEmptyShips() || computer.isEmptyShips())) { FieldPrinter.printFiled(convert.apply(attacker), attacker.getHitsMap()); - if (playersHit(aim, attacker)) { - System.out.println("Вражеский корабль подбит"); + String result = playersHit(aim, attacker); + if (!result.equals(MISS)) { + System.out.println(result); } else { aim = (aim == computer ? player : computer); attacker = (attacker == computer ? player : computer); clearConsole(); - System.out.println("Промах. В следующий раз повезет"); + System.out.println(result); try { - Thread.sleep(4000); + Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } + clearConsole(); } } System.out.println("Победил " + attacker.getName()); diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java index 3ee2dd34..f77e0cf9 100644 --- a/src/main/java/course_project/services/GameService.java +++ b/src/main/java/course_project/services/GameService.java @@ -11,6 +11,13 @@ public final class GameService { + private static final String SHIP_SANK = "Вражеский корабль потоплен!"; + private static final String SHIP_DAMAGED = "Вражеский корабль подбит"; + private static final String MISS = "Промах. В следующий раз повезет"; + private static final String INVALID_IN = "Неверные координаты цели, попробуйте еще раз!"; + private static final String ANSI_RESET = "\033[0m"; + private static final String ANSI_RED = "\u001B[31m"; + private static Random rand; static { @@ -25,15 +32,14 @@ private GameService() { throw new IllegalStateException("Utility class"); } - public static boolean playersHit(Player aim, Player attacker) { + public static String playersHit(Player aim, Player attacker) { String coordinates = getNewCoordinates(attacker.getName()); SinglePartShip partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); attacker.getHitsMap().get(aim.containsShip(partShip)).add(partShip); if (aim.containsShip(partShip)) { - PlayerController.destroyPartShip(aim, partShip); - return true; + return PlayerController.destroyPartShip(aim, partShip) ? SHIP_SANK : SHIP_DAMAGED; } - return false; + return MISS; } public static boolean isVerticalNeighbor(Player gamer, SinglePartShip partShip) { @@ -75,6 +81,7 @@ public static String getNewCoordinates(String name) { System.out.printf(name + ": введите координаты цели([A-J][1-10]): "); String coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); while (!isValidCoordinatesForShot(coordinates)) { + System.out.println(ANSI_RED + INVALID_IN + ANSI_RESET); System.out.printf(name + ": введите координаты цели([A-J][1-10]): "); coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); } @@ -85,6 +92,7 @@ public static String getNewCoordinates(int numberOfShip, int numberOfShipDeck) { System.out.printf("Введите координаты и положение %1$s-ого %2$s-палубного корабля([A-J][1-10] [v|h]): ", numberOfShip, numberOfShipDeck); String coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); while (!isValidCoordinatesForShip(coordinates)) { + System.out.println(ANSI_RED + INVALID_IN + ANSI_RESET); System.out.printf("Введите координаты и положение %1$s-ого %2$s-палубного корабля([A-J][1-10] [v|h]): ", numberOfShip, numberOfShipDeck); coordinates = Game.scanner.nextLine().trim().toUpperCase(Locale.ROOT); } diff --git a/src/main/java/course_project/services/PlayerController.java b/src/main/java/course_project/services/PlayerController.java index 3a6b8893..d6d9190b 100644 --- a/src/main/java/course_project/services/PlayerController.java +++ b/src/main/java/course_project/services/PlayerController.java @@ -18,15 +18,19 @@ private PlayerController() { throw new IllegalStateException("Utility class"); } - public static void destroyPartShip(Player player, SinglePartShip partShip) { + public static boolean destroyPartShip(Player player, SinglePartShip partShip) { Map> ships = player.getShips(); Collection> values = ships.values(); - values - .forEach(shipList -> shipList - .forEach(elem -> elem - .getList() - .removeIf(next -> next.equals(partShip)))); + for (List next : values) { + for (Ship next1 : next) { + if (next1.getList().contains(partShip)) { + next1.getList().remove(partShip); + return next1.getList().size() == 0; + } + } + } + return false; } public static void initShipLists(Player gamer, TypeShip typeShip, int countOfDeck) { From dd2df0ef170778548326bb8b077455a2fd9b3cad Mon Sep 17 00:00:00 2001 From: pepyachka Date: Wed, 22 Sep 2021 09:42:37 +0300 Subject: [PATCH 56/57] update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 6044028d..69c88ab0 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,9 @@ | HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/DrozdovNikita/src/main/java/homework_3/MyImmutableClass.java) | | | HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_file_reader)
[Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/singleton)
[CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_4/custom_annotation) | The app has 6 implementation file reader: Apache, BufferedReader, FileInputStream, Guava, Scanner and NIO
The app-singleton
The app use custom annotations to create xml structure for your object: XmlSerializable and XmlElement | | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_5/power_of_number)
[CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_5/custom_regex_matcher) | The app that reads two input integers and prints a to the power of b
The app that reads input phone number and prints its validity | +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_6) | The app that generate map problems +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/homework_7) | The app that implementation KittenToCatFunction functional interface +| CP | [SeaBattle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/main/java/course_project) | Sea Battle | | | | | TEST | [Test dir](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DrozdovNikita/src/test/java) From e34eceb4e01a2c27ad369fd6c2ccee9fa6e745d1 Mon Sep 17 00:00:00 2001 From: pepyachka Date: Fri, 24 Sep 2021 02:00:30 +0300 Subject: [PATCH 57/57] CP: add autoset marks around sunken ship, mark damage on your field, warning of re-hit --- src/main/java/course_project/Game.java | 45 +++++------ .../course_project/services/FieldPrinter.java | 7 +- .../course_project/services/GameService.java | 77 ++++++++++++++++++- .../services/PlayerController.java | 22 ++++-- .../ship/abstracts/ShipStatus.java | 23 ++++++ .../{TypeShip.java => ShipType.java} | 14 ++-- .../ship/abstracts/SinglePartShip.java | 10 +++ .../course_project/ship/models/Player.java | 43 +++++++---- 8 files changed, 187 insertions(+), 54 deletions(-) create mode 100644 src/main/java/course_project/ship/abstracts/ShipStatus.java rename src/main/java/course_project/ship/abstracts/{TypeShip.java => ShipType.java} (61%) diff --git a/src/main/java/course_project/Game.java b/src/main/java/course_project/Game.java index bd82ca9e..417f53f1 100644 --- a/src/main/java/course_project/Game.java +++ b/src/main/java/course_project/Game.java @@ -6,7 +6,7 @@ import course_project.services.PlayerController; import course_project.ship.abstracts.SinglePartShip; import course_project.ship.models.Player; -import course_project.ship.abstracts.TypeShip; +import course_project.ship.abstracts.ShipType; import java.util.*; import java.util.function.Function; @@ -18,14 +18,14 @@ public class Game extends BaseClazz { private static String MISS = "Промах. В следующий раз повезет"; - private final Player player = new Player("player"); - private final Player computer = new Player("computer"); + private final Player player = new Player("player1"); + private final Player computer = new Player("player2"); public static Scanner scanner = new Scanner(System.in); private static final Function> convert = elem -> elem - .getShips() + .getMapShips() .values() .stream() .flatMap(e -> e @@ -34,16 +34,16 @@ public class Game extends BaseClazz { @Override public void run() { - player.getShips().putAll(GameService.getNewPlayerWithRandomShips(player.getName()).getShips()); - computer.getShips().putAll(GameService.getNewPlayerWithRandomShips(computer.getName()).getShips()); + player.getMapShips().putAll(GameService.getNewPlayerWithRandomShips(player.getName()).getMapShips()); + computer.getMapShips().putAll(GameService.getNewPlayerWithRandomShips(computer.getName()).getMapShips()); startGame(); } private void startGame() { Player aim = computer; Player attacker = player; - while (!(player.isEmptyShips() || computer.isEmptyShips())) { - FieldPrinter.printFiled(convert.apply(attacker), attacker.getHitsMap()); + while (!(player.isEmptyHealthShips() || computer.isEmptyHealthShips())) { + FieldPrinter.printFiled(convert.apply(attacker), attacker.getHitsMap(), attacker.getDamageList().stream()); String result = playersHit(aim, attacker); if (!result.equals(MISS)) { System.out.println(result); @@ -60,31 +60,32 @@ private void startGame() { clearConsole(); } } + FieldPrinter.printFiled(convert.apply(attacker), attacker.getHitsMap(), attacker.getDamageList().stream()); System.out.println("Победил " + attacker.getName()); } private void initPlayer(Player gamer) { FieldPrinter.printFieldForInit(convert.apply(gamer)); - PlayerController.initShipLists(gamer, TypeShip.SINGLE_DECK, 4); + PlayerController.initShipLists(gamer, ShipType.SINGLE_DECK, 4); FieldPrinter.printFieldForInit(convert.apply(gamer)); - PlayerController.initShipLists(gamer, TypeShip.DOUBLE_DECK, 3); + PlayerController.initShipLists(gamer, ShipType.DOUBLE_DECK, 3); FieldPrinter.printFieldForInit(convert.apply(gamer)); - PlayerController.initShipLists(gamer, TypeShip.THREE_DECK, 2); + PlayerController.initShipLists(gamer, ShipType.THREE_DECK, 2); FieldPrinter.printFieldForInit(convert.apply(gamer)); - PlayerController.initShipLists(gamer, TypeShip.FOUR_DECK, 1); + PlayerController.initShipLists(gamer, ShipType.FOUR_DECK, 1); } private void initPlayer1(Player gamer) { - PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "A10", "V", 1); - PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "D9", "V", 1); - PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "F9", "V", 1); - PlayerController.addToList(gamer, TypeShip.SINGLE_DECK, "G6", "V", 1); - PlayerController.addToList(gamer, TypeShip.DOUBLE_DECK, "A1", "H", 2); - PlayerController.addToList(gamer, TypeShip.DOUBLE_DECK, "J3", "V", 2); - PlayerController.addToList(gamer, TypeShip.DOUBLE_DECK, "I9", "V", 2); - PlayerController.addToList(gamer, TypeShip.THREE_DECK, "D1", "V", 3); - PlayerController.addToList(gamer, TypeShip.THREE_DECK, "B5", "V", 3); - PlayerController.addToList(gamer, TypeShip.FOUR_DECK, "G1", "H", 4); + PlayerController.addToList(gamer, ShipType.SINGLE_DECK, "A10", "V", 1); + PlayerController.addToList(gamer, ShipType.SINGLE_DECK, "D9", "V", 1); + PlayerController.addToList(gamer, ShipType.SINGLE_DECK, "F9", "V", 1); + PlayerController.addToList(gamer, ShipType.SINGLE_DECK, "G6", "V", 1); + PlayerController.addToList(gamer, ShipType.DOUBLE_DECK, "A1", "H", 2); + PlayerController.addToList(gamer, ShipType.DOUBLE_DECK, "J3", "V", 2); + PlayerController.addToList(gamer, ShipType.DOUBLE_DECK, "I9", "V", 2); + PlayerController.addToList(gamer, ShipType.THREE_DECK, "D1", "V", 3); + PlayerController.addToList(gamer, ShipType.THREE_DECK, "B5", "V", 3); + PlayerController.addToList(gamer, ShipType.FOUR_DECK, "G1", "H", 4); } private void clearConsole() { diff --git a/src/main/java/course_project/services/FieldPrinter.java b/src/main/java/course_project/services/FieldPrinter.java index 4fc3019b..5039e8d3 100644 --- a/src/main/java/course_project/services/FieldPrinter.java +++ b/src/main/java/course_project/services/FieldPrinter.java @@ -29,10 +29,13 @@ public static void printFieldForInit(Stream attacker) { } } - public static void printFiled(Stream attacker, Map> opponent) { + public static void printFiled(Stream attacker, + Map> opponent, + Stream damageList) { int[][] attackerField = new int[FIELD_CAPACITY][FIELD_CAPACITY]; int[][] opponentField = new int[FIELD_CAPACITY][FIELD_CAPACITY]; attacker.forEach(elem -> add(attackerField, elem, 1)); + damageList.forEach(elem -> add(attackerField, elem, -1)); opponent.entrySet().forEach(elem -> add(opponentField, elem)); System.out.printf("%-51s", "your field"); @@ -61,6 +64,8 @@ private static void printLineTable(int i, int[][] field) { for (int j = 0; j < FIELD_CAPACITY; j++) { if (field[i][j] == 1) { System.out.printf("%13s", ANSI_GREEN + "x" + ANSI_RESET); + } else if (field[i][j] == -1) { + System.out.printf("%13s", ANSI_CYAN + "o" + ANSI_RESET); } else { System.out.printf("%4s", "."); } diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java index f77e0cf9..a648be2b 100644 --- a/src/main/java/course_project/services/GameService.java +++ b/src/main/java/course_project/services/GameService.java @@ -1,7 +1,7 @@ package course_project.services; import course_project.Game; -import course_project.ship.abstracts.TypeShip; +import course_project.ship.abstracts.ShipType; import course_project.ship.models.Player; import course_project.ship.abstracts.SinglePartShip; @@ -15,6 +15,7 @@ public final class GameService { private static final String SHIP_DAMAGED = "Вражеский корабль подбит"; private static final String MISS = "Промах. В следующий раз повезет"; private static final String INVALID_IN = "Неверные координаты цели, попробуйте еще раз!"; + private static final String EXIST_HIT = "Вы уже стреляли по цели с такими координатами!"; private static final String ANSI_RESET = "\033[0m"; private static final String ANSI_RED = "\u001B[31m"; @@ -35,13 +36,79 @@ private GameService() { public static String playersHit(Player aim, Player attacker) { String coordinates = getNewCoordinates(attacker.getName()); SinglePartShip partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); + while (containsHit(aim, partShip)) { + System.out.println(ANSI_RED + EXIST_HIT + ANSI_RESET); + coordinates = getNewCoordinates(attacker.getName()); + partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); + } + aim.getDamageList().add(partShip); attacker.getHitsMap().get(aim.containsShip(partShip)).add(partShip); if (aim.containsShip(partShip)) { - return PlayerController.destroyPartShip(aim, partShip) ? SHIP_SANK : SHIP_DAMAGED; + if (PlayerController.destroyPartShip(aim, partShip)) { + markSunkShip(attacker, aim, partShip); + return SHIP_SANK; + } else { + return SHIP_DAMAGED; + } } return MISS; } + public static boolean markSunkShip(Player attacker, Player aim, SinglePartShip partShip) { + List marks = new ArrayList<>(); + + List ship = aim.getShip(partShip).getList(); + List damageList = aim.getDamageList(); + if (ship.size() < 2 || ship.get(0).getY().equals(ship.get(1).getY())) { + marks.addAll(markSunkHorizontalShip(ship)); + } else { + marks.addAll(markSunkVerticalShip(ship)); + } + return attacker.getHitsMap().get(Boolean.FALSE).addAll(marks) && damageList.addAll(marks); + } + + private static Set markSunkVerticalShip(List list) { + Set hitsSet = new HashSet<>(); + SinglePartShip headerShip = list.get(0); + addToList(hitsSet, new SinglePartShip(headerShip.getX() - 1, headerShip.getY() - 1)); + addToList(hitsSet, new SinglePartShip(headerShip.getX(), headerShip.getY() - 1)); + addToList(hitsSet, new SinglePartShip(headerShip.getX() + 1, headerShip.getY() - 1)); + for (SinglePartShip s : list) { + addToList(hitsSet, new SinglePartShip(s.getX() - 1, s.getY())); + addToList(hitsSet, new SinglePartShip(s.getX() + 1, s.getY())); + } + SinglePartShip lastShip = list.get(list.size() - 1); + addToList(hitsSet, new SinglePartShip(lastShip.getX() - 1, lastShip.getY() + 1)); + addToList(hitsSet, new SinglePartShip(lastShip.getX(), lastShip.getY() + 1)); + addToList(hitsSet, new SinglePartShip(lastShip.getX() + 1, lastShip.getY() + 1)); + return hitsSet; + } + + private static Set markSunkHorizontalShip(List list) { + Set hitsList = new HashSet<>(); + SinglePartShip headerShip = list.get(0); + addToList(hitsList, new SinglePartShip(headerShip.getX() - 1, headerShip.getY() - 1)); + addToList(hitsList, new SinglePartShip(headerShip.getX() - 1, headerShip.getY())); + addToList(hitsList, new SinglePartShip(headerShip.getX() - 1, headerShip.getY() + 1)); + for (SinglePartShip s : list) { + addToList(hitsList, new SinglePartShip(s.getX(), s.getY() - 1)); + addToList(hitsList, new SinglePartShip(s.getX(), s.getY() + 1)); + } + SinglePartShip lastShip = list.get(list.size() - 1); + addToList(hitsList, new SinglePartShip(lastShip.getX() + 1, lastShip.getY() - 1)); + addToList(hitsList, new SinglePartShip(lastShip.getX() + 1, lastShip.getY())); + addToList(hitsList, new SinglePartShip(lastShip.getX() + 1, lastShip.getY() + 1)); + + return hitsList; + } + + private static boolean addToList(Set hitsList, SinglePartShip partShip) { + if ((0 < partShip.getX() && partShip.getX() < 11) && (0 < partShip.getY() && partShip.getY() < 11)) { + return hitsList.add(partShip); + } + return false; + } + public static boolean isVerticalNeighbor(Player gamer, SinglePartShip partShip) { int x = partShip.getX(); int y = partShip.getY(); @@ -111,7 +178,7 @@ public static Player getNewPlayerWithRandomShips(String name) { SinglePartShip partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); while (tempPlayer.containsShip(partShip) || - !PlayerController.addToList(tempPlayer, TypeShip.getType(i + 1), coordinates, location, i + 1)) { + !PlayerController.addToList(tempPlayer, ShipType.getType(i + 1), coordinates, location, i + 1)) { coordinates = getRandomCoordinates(); location = rand.nextBoolean() ? "V" : "H"; partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); @@ -122,6 +189,10 @@ public static Player getNewPlayerWithRandomShips(String name) { return tempPlayer; } + private static boolean containsHit(Player gamer, SinglePartShip partShip) { + return gamer.getDamageList().contains(partShip); + } + private static boolean isValidCoordinatesForShot(String... arg) { if (arg[0].split("\\s").length > 1) { return false; diff --git a/src/main/java/course_project/services/PlayerController.java b/src/main/java/course_project/services/PlayerController.java index d6d9190b..072b03ec 100644 --- a/src/main/java/course_project/services/PlayerController.java +++ b/src/main/java/course_project/services/PlayerController.java @@ -1,6 +1,7 @@ package course_project.services; -import course_project.ship.abstracts.TypeShip; +import course_project.ship.abstracts.ShipStatus; +import course_project.ship.abstracts.ShipType; import course_project.ship.models.Player; import course_project.ship.models.Ship; import course_project.ship.abstracts.SinglePartShip; @@ -19,31 +20,36 @@ private PlayerController() { } public static boolean destroyPartShip(Player player, SinglePartShip partShip) { - Map> ships = player.getShips(); + Map> ships = player.getMapShips(); Collection> values = ships.values(); for (List next : values) { for (Ship next1 : next) { if (next1.getList().contains(partShip)) { - next1.getList().remove(partShip); - return next1.getList().size() == 0; + List list = next1.getList(); + for (SinglePartShip singlePartShip : list) { + if (singlePartShip.equals(partShip)) { + singlePartShip.setStatus(ShipStatus.SANK); + } + } + return list.stream().noneMatch(elem -> elem.getStatus().equals(ShipStatus.HEALTHY)); } } } return false; } - public static void initShipLists(Player gamer, TypeShip typeShip, int countOfDeck) { + public static void initShipLists(Player gamer, ShipType shipType, int countOfDeck) { for (int i = 0; i < countOfDeck; i++) { String coordinates = GameService.getNewCoordinates(i + 1, 5 - countOfDeck); - if (!addToList(gamer, typeShip, coordinates.split("\\s")[0], coordinates.split("\\s")[1], 5 - countOfDeck)) { + if (!addToList(gamer, shipType, coordinates.split("\\s")[0], coordinates.split("\\s")[1], 5 - countOfDeck)) { System.out.println(ANSI_RED + "Что-то пошло не так, попробуйте еще раз" + ANSI_RESET); i--; } } } - public static boolean addToList(Player gamer, TypeShip typeShip, String coordinates, String location, int countOfDeck) { + public static boolean addToList(Player gamer, ShipType shipType, String coordinates, String location, int countOfDeck) { List tempList = new ArrayList<>(); SinglePartShip partShip = new SinglePartShip(coordinates.charAt(0) - 64, new Integer(coordinates.substring(1))); for (int i = 0; i < countOfDeck; i++) { @@ -66,7 +72,7 @@ public static boolean addToList(Player gamer, TypeShip typeShip, String coordina partShip = partShip.setX(partShip.getX() + 1); } } - gamer.getShips().get(typeShip.getType()).add(new Ship(tempList)); + gamer.getMapShips().get(shipType.getType()).add(new Ship(tempList)); return true; } diff --git a/src/main/java/course_project/ship/abstracts/ShipStatus.java b/src/main/java/course_project/ship/abstracts/ShipStatus.java new file mode 100644 index 00000000..c3b15acc --- /dev/null +++ b/src/main/java/course_project/ship/abstracts/ShipStatus.java @@ -0,0 +1,23 @@ +package course_project.ship.abstracts; + +public enum ShipStatus { + + SANK("Sank", 0), + HEALTHY("Healthy", 1); + + private String status; + private int value; + + ShipStatus(String status, int value) { + this.status = status; + this.value = value; + } + + public String getStatus() { + return status; + } + + public int getValue() { + return value; + } +} diff --git a/src/main/java/course_project/ship/abstracts/TypeShip.java b/src/main/java/course_project/ship/abstracts/ShipType.java similarity index 61% rename from src/main/java/course_project/ship/abstracts/TypeShip.java rename to src/main/java/course_project/ship/abstracts/ShipType.java index 2c81b7c2..3b3d871b 100644 --- a/src/main/java/course_project/ship/abstracts/TypeShip.java +++ b/src/main/java/course_project/ship/abstracts/ShipType.java @@ -1,6 +1,6 @@ package course_project.ship.abstracts; -public enum TypeShip { +public enum ShipType { SINGLE_DECK ("SingleDeckShip", 4), DOUBLE_DECK ("DoubleDeckShip", 3), @@ -10,7 +10,7 @@ public enum TypeShip { private String type; private int count; - TypeShip(String type, int count) { + ShipType(String type, int count) { this.type = type; this.count = count; } @@ -19,12 +19,12 @@ public String getType() { return type; } - public static TypeShip getType(int n) { + public static ShipType getType(int n) { switch (n) { - case 1: return TypeShip.SINGLE_DECK; - case 2: return TypeShip.DOUBLE_DECK; - case 3: return TypeShip.THREE_DECK; - case 4: return TypeShip.FOUR_DECK; + case 1: return ShipType.SINGLE_DECK; + case 2: return ShipType.DOUBLE_DECK; + case 3: return ShipType.THREE_DECK; + case 4: return ShipType.FOUR_DECK; } return null; } diff --git a/src/main/java/course_project/ship/abstracts/SinglePartShip.java b/src/main/java/course_project/ship/abstracts/SinglePartShip.java index 3a2e46ca..601a9181 100644 --- a/src/main/java/course_project/ship/abstracts/SinglePartShip.java +++ b/src/main/java/course_project/ship/abstracts/SinglePartShip.java @@ -6,10 +6,12 @@ public class SinglePartShip { private Integer x; private Integer y; + private ShipStatus status; public SinglePartShip(Integer x, Integer y) { this.x = x; this.y = y; + status = ShipStatus.HEALTHY; } public Integer getX() { @@ -28,6 +30,14 @@ public SinglePartShip setY(Integer y) { return new SinglePartShip(this.x, y); } + public ShipStatus getStatus() { + return status; + } + + public void setStatus(ShipStatus status) { + this.status = status; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/course_project/ship/models/Player.java b/src/main/java/course_project/ship/models/Player.java index e424b630..0603ba3f 100644 --- a/src/main/java/course_project/ship/models/Player.java +++ b/src/main/java/course_project/ship/models/Player.java @@ -1,8 +1,8 @@ package course_project.ship.models; -import course_project.ship.models.Ship; +import course_project.ship.abstracts.ShipStatus; import course_project.ship.abstracts.SinglePartShip; -import course_project.ship.abstracts.TypeShip; +import course_project.ship.abstracts.ShipType; import java.util.*; import java.util.stream.Stream; @@ -11,17 +11,18 @@ public class Player { private String name; private final Map> ships = new HashMap<>(); - private final Map> hitsList = new HashMap<>(); + private final Map> hitsMap = new HashMap<>(); + private final List damageList = new ArrayList<>(); public Player(String name) { this.name = name; - ships.put(TypeShip.SINGLE_DECK.getType(), new ArrayList<>()); - ships.put(TypeShip.DOUBLE_DECK.getType(),new ArrayList<>()); - ships.put(TypeShip.THREE_DECK.getType(), new ArrayList<>()); - ships.put(TypeShip.FOUR_DECK.getType(), new ArrayList<>()); + ships.put(ShipType.SINGLE_DECK.getType(), new ArrayList<>()); + ships.put(ShipType.DOUBLE_DECK.getType(),new ArrayList<>()); + ships.put(ShipType.THREE_DECK.getType(), new ArrayList<>()); + ships.put(ShipType.FOUR_DECK.getType(), new ArrayList<>()); - hitsList.put(Boolean.TRUE, new ArrayList<>()); - hitsList.put(Boolean.FALSE, new ArrayList<>()); + hitsMap.put(Boolean.TRUE, new ArrayList<>()); + hitsMap.put(Boolean.FALSE, new ArrayList<>()); } public String getName() { @@ -32,12 +33,28 @@ public void setName(String name) { this.name = name; } - public Map> getShips() { + public List getDamageList() { + return damageList; + } + + public Map> getMapShips() { return ships; } public Map> getHitsMap() { - return hitsList; + return hitsMap; + } + + public Ship getShip(SinglePartShip partShip) { + Collection> values = ships.values(); + for (List shipList : values) { + for (Ship ship : shipList) { + if (ship.contains(partShip)) { + return ship; + } + } + } + return null; } public boolean containsShip(SinglePartShip singlePartShip) { @@ -50,13 +67,13 @@ public boolean containsShip(SinglePartShip singlePartShip) { return singlePartShipStream.anyMatch(elem -> elem.equals(singlePartShip)); } - public boolean isEmptyShips() { + public boolean isEmptyHealthShips() { Stream singlePartShipStream = ships .values() .stream() .flatMap(elem -> elem .stream() .flatMap(l -> l.getList().stream())); - return !singlePartShipStream.findAny().isPresent(); + return singlePartShipStream.noneMatch(elem -> elem.getStatus().equals(ShipStatus.HEALTHY)); } }