From a09f13c7042c123ebc9e9dcb23cb617ce25f1969 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Tue, 6 Jul 2021 20:48:05 +0300 Subject: [PATCH 01/33] master stuff returned back to compilable --- src/main/java/lesson_2/Main.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/lesson_2/Main.java b/src/main/java/lesson_2/Main.java index ed30607a..7a69ed7c 100644 --- a/src/main/java/lesson_2/Main.java +++ b/src/main/java/lesson_2/Main.java @@ -1,12 +1,9 @@ package lesson_2; -import lesson_2.catbox.Cat1; - public class Main { public static void main(String[] args) { - final int x = 5; - final Cat1 cat1 = new Cat1(); + System.out.println("Hello, world!"); } } From 2b15633a8e8ba8a1d079454da669590a48a4fff8 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Tue, 6 Jul 2021 20:48:14 +0300 Subject: [PATCH 02/33] homework_1's done --- src/main/java/homework_1/Main.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/java/homework_1/Main.java diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java new file mode 100644 index 00000000..b317b034 --- /dev/null +++ b/src/main/java/homework_1/Main.java @@ -0,0 +1,14 @@ +package homework_1; + +public class Main { + public static void main(String[] args) { + for (String arg : args) { + if (!arg.equals("error")){ + System.out.println(arg + ": " + arg.length() + " letters"); + } else{ + System.err.println("Alarm!"); + break; + } + } + } +} From e9f4c1494e69b54735dfe663a73e7170792d64aa Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Sat, 10 Jul 2021 08:50:39 +0300 Subject: [PATCH 03/33] README.md added --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5d686e9f..ca60a276 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Dzenzura Tatiana* | 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/TatianaDzenzura/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 d487f3221063bd2baa19b7e7aa6fc36070f77a3c Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Tue, 13 Jul 2021 05:43:26 +0300 Subject: [PATCH 04/33] different streams output fixed --- src/main/java/homework_1/Main.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index b317b034..5e73425d 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -2,11 +2,14 @@ public class Main { public static void main(String[] args) { + final String RED_FONT = "\033[0;31m"; + final String RESET_FONT = "\033[0m"; + for (String arg : args) { if (!arg.equals("error")){ System.out.println(arg + ": " + arg.length() + " letters"); } else{ - System.err.println("Alarm!"); + System.out.println(RED_FONT + "Alarm!" + RESET_FONT); break; } } From b7b3c70fcb16d3db3331bcd00a00f1f749fc016e Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 14 Jul 2021 13:00:46 +0300 Subject: [PATCH 05/33] style hm1 fixed --- src/main/java/homework_1/Main.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 5e73425d..adfd0b99 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,16 +1,17 @@ package homework_1; public class Main { + public static void main(String[] args) { final String RED_FONT = "\033[0;31m"; final String RESET_FONT = "\033[0m"; for (String arg : args) { - if (!arg.equals("error")){ - System.out.println(arg + ": " + arg.length() + " letters"); - } else{ + if (arg.equals("error")){ System.out.println(RED_FONT + "Alarm!" + RESET_FONT); break; + } else { + System.out.println(arg + ": " + arg.length() + " letters"); } } } From b3fa7aa88c88200a14ac6db4414f4469806ce5b9 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 14 Jul 2021 13:03:03 +0300 Subject: [PATCH 06/33] white spaces hm1 fixed --- 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 adfd0b99..69c17949 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -7,7 +7,7 @@ public static void main(String[] args) { final String RESET_FONT = "\033[0m"; for (String arg : args) { - if (arg.equals("error")){ + if (arg.equals("error")) { System.out.println(RED_FONT + "Alarm!" + RESET_FONT); break; } else { From 9d1226559e216348cbb20a222ae5fdbf0cac39e7 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Thu, 15 Jul 2021 09:35:16 +0300 Subject: [PATCH 07/33] HM2 traffic light added --- .../traffic_light/TrafficLight.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/main/java/homework_2/traffic_light/TrafficLight.java 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..864327b5 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,63 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + public static final int BOUND_1 = 35; + public static final int BOUND_2 = 40; + public static final int BOUND_3 = 55; + public static final int MAX_VALUE = 86399; + + public static final int SEC_IN_MIN = 60; + + public static void main(String[] args) throws IOException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + while (true) { + String input = br.readLine(); + if (!isInt(input)) { + if (input.trim().equals("exit")) { + break; + } + System.out.println("Wrong input format, try integer number, your input: " + input); + continue; + } + + int light = Integer.parseInt(input); + if (light < 0) { + System.out.println("Positive values supported only, your value: " + light); + continue; + } else if (light > MAX_VALUE) { + System.out.println("Day's over, try smaller value"); + continue; + } + + light = light % SEC_IN_MIN; + + if (light < BOUND_1) { + System.out.println("GREEN"); + } else if (light < BOUND_2) { + System.out.println("YELLOW"); + } else if (light < BOUND_3) { + System.out.println("RED"); + } else { + System.out.println("YELLOW"); + } + } + } + } + + private static boolean isInt(String str) { + if (str == null) { + return false; + } + try { + int i = Integer.parseInt(str); + } catch (NumberFormatException e) { + return false; + } + return true; + } +} From 4a7ce6d55210d5dce7280ec24022e397a64652d2 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Thu, 15 Jul 2021 09:48:51 +0300 Subject: [PATCH 08/33] HM2 pyramid printer added --- .../pyramid_printer/PyramidPrinter.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinter.java 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..3cf67fe0 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,27 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + private static final char SPEC_CHAR = 'x'; + + public static void main(String[] args) throws IOException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + int n = Integer.parseInt(br.readLine()); + for (int i = 0; i < n; i++) { + printNTimes(i + 1, SPEC_CHAR); + System.out.println(); + } + } catch (NumberFormatException e) { + System.out.println("Integers supported only"); + } + } + + private static void printNTimes(int n, char c) { + for (int i = 0; i < n; i++) { + System.out.print(c); + } + } +} From e1ab4b290d306d2d130cc1bca9b0ab93bdaba7ea Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Thu, 15 Jul 2021 12:26:44 +0300 Subject: [PATCH 09/33] HM2 traffic light refactored --- src/main/java/homework_2/Utils.java | 16 ++++++++++++++++ .../homework_2/traffic_light/TrafficLight.java | 16 +++------------- 2 files changed, 19 insertions(+), 13 deletions(-) create mode 100644 src/main/java/homework_2/Utils.java diff --git a/src/main/java/homework_2/Utils.java b/src/main/java/homework_2/Utils.java new file mode 100644 index 00000000..849a32fe --- /dev/null +++ b/src/main/java/homework_2/Utils.java @@ -0,0 +1,16 @@ +package homework_2; + +public class Utils { + + public static boolean isInt(String str) { + if (str == null) { + return false; + } + try { + int i = Integer.parseInt(str); + } catch (NumberFormatException e) { + return false; + } + return true; + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 864327b5..e635fbe1 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,5 +1,7 @@ package homework_2.traffic_light; +import homework_2.Utils; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -17,7 +19,7 @@ public static void main(String[] args) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { while (true) { String input = br.readLine(); - if (!isInt(input)) { + if (!Utils.isInt(input)) { if (input.trim().equals("exit")) { break; } @@ -48,16 +50,4 @@ public static void main(String[] args) throws IOException { } } } - - private static boolean isInt(String str) { - if (str == null) { - return false; - } - try { - int i = Integer.parseInt(str); - } catch (NumberFormatException e) { - return false; - } - return true; - } } From 4c05ca0943f37e81627c7de219438b0fcaea49d4 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Thu, 15 Jul 2021 12:27:09 +0300 Subject: [PATCH 10/33] HM2 random char table added --- .../random_chars_table/RandomCharTable.java | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharTable.java diff --git a/src/main/java/homework_2/random_chars_table/RandomCharTable.java b/src/main/java/homework_2/random_chars_table/RandomCharTable.java new file mode 100644 index 00000000..3ae6c39f --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharTable.java @@ -0,0 +1,90 @@ +package homework_2.random_chars_table; + +import homework_2.Utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharTable { + private static char[][] chars; + private static int height; + private static int width; + private static Strategy strategy; + + private static final char TABLE_SPLITTER = '|'; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String line = br.readLine(); + String[] params = line.split(" +"); + + if (!isCorrectParams(params)) { + System.out.println("Parameters are not correct"); + throw new IllegalArgumentException(); + } + + height = Integer.parseInt(params[0]); + width = Integer.parseInt(params[1]); + strategy = Strategy.valueOf(params[2].toUpperCase()); + + chars = new char[height][width]; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j ++) { + chars[i][j] = getRandomChar(); + } + } + + printTable(); + printStrategyOKNums(); + } + + + private static void printStrategyOKNums() { + System.out.print(strategy.name().charAt(0) + strategy.name().substring(1).toLowerCase() + " letters - "); + + int count = 0; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j ++) { + if (isStrategyOK(chars[i][j])) { + if (count != 0) { + System.out.print(", "); + } + System.out.print(chars[i][j]); + count++; + } + chars[i][j] = getRandomChar(); + } + } + } + + private static boolean isStrategyOK(char c) { + boolean isEven = c % 2 == 0; + return (strategy == Strategy.EVEN) == isEven; + } + + private static void printTable() { + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j ++) { + System.out.print(TABLE_SPLITTER); + System.out.print(chars[i][j]); + } + System.out.println(TABLE_SPLITTER); + } + } + + private static boolean isCorrectParams(String[] params) { + return Utils.isInt(params[0]) && Utils.isInt(params[1]) && (params[2].equals("even") || params[2].equals("odd")); + } + + private static char getRandomChar() { + int range = 'Z' - 'A'; + return (char) (Math.random() * range + 'A'); + } + + private enum Strategy { + ODD, + EVEN + } + +} From 74c907e69adc81b586d5c22fd7716915c39af904 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Mon, 19 Jul 2021 12:32:40 +0300 Subject: [PATCH 11/33] HW2 README.md changed for hw2 --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ca60a276..40355540 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,9 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW 1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW 2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/traffic_light) | The app that reads number of seconds from the beginning of the day from the console and calculates color of the traffic light | +| HW 2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/pyramid_printer) | The app that prints pyramid of 'x' chars based on user input | +| HW 2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/random_chars_table) | The app that reads length, width and strategy from the console and generates table of random chars and prints even/odd letters according to strategy | -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From d5324153776a01a764627a5c35da820c98f7288a Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Fri, 23 Jul 2021 15:21:21 +0300 Subject: [PATCH 12/33] HW2 refactored as required in HW3 --- README.md | 2 + src/main/java/homework_2/Utils.java | 16 ---- .../java/homework_2/WrongInputException.java | 8 ++ .../pyramid_printer/InputReader.java | 30 +++++++ .../java/homework_2/pyramid_printer/Main.java | 10 +++ .../pyramid_printer/PyramidPrinter.java | 31 ++++--- .../random_chars_table/InputReader.java | 40 +++++++++ .../homework_2/random_chars_table/Main.java | 10 +++ .../random_chars_table/RandomCharTable.java | 90 ------------------- .../random_chars_table/RandomCharsTable.java | 26 ++++++ .../StrategyCharacterSet.java | 39 ++++++++ .../homework_2/random_chars_table/Table.java | 74 +++++++++++++++ .../homework_2/traffic_light/InputReader.java | 38 ++++++++ .../java/homework_2/traffic_light/Main.java | 10 +++ .../traffic_light/TrafficLight.java | 72 ++++++--------- 15 files changed, 333 insertions(+), 163 deletions(-) delete mode 100644 src/main/java/homework_2/Utils.java create mode 100644 src/main/java/homework_2/WrongInputException.java create mode 100644 src/main/java/homework_2/pyramid_printer/InputReader.java create mode 100644 src/main/java/homework_2/pyramid_printer/Main.java create mode 100644 src/main/java/homework_2/random_chars_table/InputReader.java create mode 100644 src/main/java/homework_2/random_chars_table/Main.java delete mode 100644 src/main/java/homework_2/random_chars_table/RandomCharTable.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/StrategyCharacterSet.java create mode 100644 src/main/java/homework_2/random_chars_table/Table.java create mode 100644 src/main/java/homework_2/traffic_light/InputReader.java create mode 100644 src/main/java/homework_2/traffic_light/Main.java diff --git a/README.md b/README.md index 40355540..eca5eba3 100644 --- a/README.md +++ b/README.md @@ -10,3 +10,5 @@ | HW 2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/random_chars_table) | The app that reads length, width and strategy from the console and generates table of random chars and prints even/odd letters according to strategy | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) + +[Link to CodingBat](https://codingbat.com/done?user=tatiana22d@gmail.com&tag=53255552) \ No newline at end of file diff --git a/src/main/java/homework_2/Utils.java b/src/main/java/homework_2/Utils.java deleted file mode 100644 index 849a32fe..00000000 --- a/src/main/java/homework_2/Utils.java +++ /dev/null @@ -1,16 +0,0 @@ -package homework_2; - -public class Utils { - - public static boolean isInt(String str) { - if (str == null) { - return false; - } - try { - int i = Integer.parseInt(str); - } catch (NumberFormatException e) { - return false; - } - return true; - } -} diff --git a/src/main/java/homework_2/WrongInputException.java b/src/main/java/homework_2/WrongInputException.java new file mode 100644 index 00000000..bcee6ace --- /dev/null +++ b/src/main/java/homework_2/WrongInputException.java @@ -0,0 +1,8 @@ +package homework_2; + +public class WrongInputException extends Exception { + + public WrongInputException(String errorMsg) { + super(errorMsg); + } +} diff --git a/src/main/java/homework_2/pyramid_printer/InputReader.java b/src/main/java/homework_2/pyramid_printer/InputReader.java new file mode 100644 index 00000000..ef46ee91 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/InputReader.java @@ -0,0 +1,30 @@ +package homework_2.pyramid_printer; + +import homework_2.WrongInputException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class InputReader { + private final String ERROR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + + protected int readNum() throws WrongInputException, IOException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + String input = br.readLine(); + return parseInput(input); + } + } + + private int parseInput(String input) throws WrongInputException { + try { + int num = Integer.parseInt(input); + if (num < 0) { + throw new WrongInputException(ERROR_MSG); + } + return num; + } catch (NumberFormatException e) { + throw new WrongInputException(ERROR_MSG); + } + } +} 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..1d8733a3 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,10 @@ +package homework_2.pyramid_printer; + +import java.io.IOException; + +public class Main { + + public static void main(String[] args) throws IOException { + 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 3cf67fe0..d9fcb043 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -1,27 +1,30 @@ package homework_2.pyramid_printer; -import java.io.BufferedReader; +import homework_2.WrongInputException; import java.io.IOException; -import java.io.InputStreamReader; public class PyramidPrinter { - private static final char SPEC_CHAR = 'x'; + private final char SPEC_CHAR = 'x'; - public static void main(String[] args) throws IOException { - try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { - int n = Integer.parseInt(br.readLine()); - for (int i = 0; i < n; i++) { - printNTimes(i + 1, SPEC_CHAR); - System.out.println(); - } - } catch (NumberFormatException e) { - System.out.println("Integers supported only"); + public void run() throws IOException { + try { + InputReader inputReader = new InputReader(); + int n = inputReader.readNum(); + + System.out.println(getPyramid(n)); + } catch (WrongInputException e) { + System.out.println(e.getMessage()); } } - private static void printNTimes(int n, char c) { + private String getPyramid(int n) { + StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < n; i++) { - System.out.print(c); + for (int j = 0; j < i + 1; j++) { + stringBuilder.append(SPEC_CHAR); + } + stringBuilder.append('\n'); } + return stringBuilder.toString(); } } diff --git a/src/main/java/homework_2/random_chars_table/InputReader.java b/src/main/java/homework_2/random_chars_table/InputReader.java new file mode 100644 index 00000000..83f67ea6 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/InputReader.java @@ -0,0 +1,40 @@ +package homework_2.random_chars_table; + +import homework_2.WrongInputException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class InputReader { + private final String ERROR_MSG = "Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]"; + + protected Table readTableParams() throws IOException, WrongInputException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + String input = br.readLine(); + return parseInput(input); + } + } + + private Table parseInput(String input) throws WrongInputException { + String[] params = input.split(" +"); + try { + if (params.length == 3) { + int height = Integer.parseInt(params[0]); + int width = Integer.parseInt(params[1]); + StrategyCharacterSet.Strategy strategy = StrategyCharacterSet.Strategy.valueOf(params[2].toUpperCase()); + + if (width > 0 && height > 0) { + return new Table(width, height, strategy); + } else { + throw new WrongInputException(ERROR_MSG); + } + } else { + throw new WrongInputException(ERROR_MSG); + } + } catch (IllegalArgumentException e) { + throw new WrongInputException(ERROR_MSG); + } + } +} 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..e0708d5a --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,10 @@ +package homework_2.random_chars_table; + +import java.io.IOException; + +public class Main { + + public static void main(String[] args) throws IOException { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharTable.java b/src/main/java/homework_2/random_chars_table/RandomCharTable.java deleted file mode 100644 index 3ae6c39f..00000000 --- a/src/main/java/homework_2/random_chars_table/RandomCharTable.java +++ /dev/null @@ -1,90 +0,0 @@ -package homework_2.random_chars_table; - -import homework_2.Utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class RandomCharTable { - private static char[][] chars; - private static int height; - private static int width; - private static Strategy strategy; - - private static final char TABLE_SPLITTER = '|'; - - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - String line = br.readLine(); - String[] params = line.split(" +"); - - if (!isCorrectParams(params)) { - System.out.println("Parameters are not correct"); - throw new IllegalArgumentException(); - } - - height = Integer.parseInt(params[0]); - width = Integer.parseInt(params[1]); - strategy = Strategy.valueOf(params[2].toUpperCase()); - - chars = new char[height][width]; - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j ++) { - chars[i][j] = getRandomChar(); - } - } - - printTable(); - printStrategyOKNums(); - } - - - private static void printStrategyOKNums() { - System.out.print(strategy.name().charAt(0) + strategy.name().substring(1).toLowerCase() + " letters - "); - - int count = 0; - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j ++) { - if (isStrategyOK(chars[i][j])) { - if (count != 0) { - System.out.print(", "); - } - System.out.print(chars[i][j]); - count++; - } - chars[i][j] = getRandomChar(); - } - } - } - - private static boolean isStrategyOK(char c) { - boolean isEven = c % 2 == 0; - return (strategy == Strategy.EVEN) == isEven; - } - - private static void printTable() { - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j ++) { - System.out.print(TABLE_SPLITTER); - System.out.print(chars[i][j]); - } - System.out.println(TABLE_SPLITTER); - } - } - - private static boolean isCorrectParams(String[] params) { - return Utils.isInt(params[0]) && Utils.isInt(params[1]) && (params[2].equals("even") || params[2].equals("odd")); - } - - private static char getRandomChar() { - int range = 'Z' - 'A'; - return (char) (Math.random() * range + 'A'); - } - - private enum Strategy { - ODD, - EVEN - } - -} 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..9e719ce9 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,26 @@ +package homework_2.random_chars_table; + +import homework_2.WrongInputException; + +import java.io.IOException; + +public class RandomCharsTable { + + public void run() throws IOException { + try { + InputReader inputReader = new InputReader(); + Table table = inputReader.readTableParams(); + + table.fillTable(); + table.printTable(); + + StrategyCharacterSet strategyCharacterSet = new StrategyCharacterSet(); + + strategyCharacterSet.fillCharacterSet(table); + strategyCharacterSet.printCharacterSet(table.getStrategy()); + + } catch (WrongInputException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/src/main/java/homework_2/random_chars_table/StrategyCharacterSet.java b/src/main/java/homework_2/random_chars_table/StrategyCharacterSet.java new file mode 100644 index 00000000..e2e07806 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/StrategyCharacterSet.java @@ -0,0 +1,39 @@ +package homework_2.random_chars_table; + +import java.util.HashSet; +import java.util.Set; + +public class StrategyCharacterSet { + private final Set characterSet = new HashSet<>(); + + enum Strategy { + ODD, + EVEN + } + + public Set getCharacterSet() { + return characterSet; + } + + protected void fillCharacterSet(Table table) { + char[][] chars = table.getTable(); + for (int i = 0; i < table.getHeight(); i++) { + for (int j = 0; j < table.getWidth(); j ++) { + if (isStrategyOK(chars[i][j], table.getStrategy())) { + characterSet.add(chars[i][j] + ""); + } + } + } + } + + protected void printCharacterSet(Strategy strategy) { + System.out.print(strategy.name().charAt(0) + + strategy.name().substring(1).toLowerCase() + " letters - "); + System.out.println(String.join(", ", characterSet)); + } + + private boolean isStrategyOK(char c, Strategy strategy) { + boolean isEven = c % 2 == 0; + return (strategy == Strategy.EVEN) == isEven; + } +} diff --git a/src/main/java/homework_2/random_chars_table/Table.java b/src/main/java/homework_2/random_chars_table/Table.java new file mode 100644 index 00000000..73f03295 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Table.java @@ -0,0 +1,74 @@ +package homework_2.random_chars_table; + +public class Table { + private final char TABLE_SPLITTER = '|'; + + private int width; + private int height; + private StrategyCharacterSet.Strategy strategy; + + private char[][] table; + + public Table(int width, int height, StrategyCharacterSet.Strategy strategy) { + this.width = width; + this.height = height; + this.strategy = strategy; + + table = new char[height][width]; + } + + public char[][] getTable() { + return table; + } + + public void setTable(char[][] table) { + this.table = table; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public StrategyCharacterSet.Strategy getStrategy() { + return strategy; + } + + public void setStrategy(StrategyCharacterSet.Strategy strategy) { + this.strategy = strategy; + } + + protected void fillTable() { + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j ++) { + table[i][j] = getRandomChar(); + } + } + } + + protected void printTable() { + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j ++) { + System.out.print(TABLE_SPLITTER); + System.out.print(table[i][j]); + } + System.out.println(TABLE_SPLITTER); + } + } + + private char getRandomChar() { + int range = 'Z' - 'A'; + return (char) (Math.random() * range + 'A'); + } +} diff --git a/src/main/java/homework_2/traffic_light/InputReader.java b/src/main/java/homework_2/traffic_light/InputReader.java new file mode 100644 index 00000000..e30b52f0 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/InputReader.java @@ -0,0 +1,38 @@ +package homework_2.traffic_light; + +import homework_2.WrongInputException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class InputReader { + private final String errorMsgDayIsOver = "The day is over"; + private final String errorMsg = "Only 1 non-negative integer is allowed as passed parameter"; + private final int MAX_VALUE_OF_SECS = 86399; + + protected int readSecs() throws IOException, WrongInputException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + String input = br.readLine(); + return parseInput(input); + } + } + + private int parseInput(String input) throws WrongInputException { + try { + int light = Integer.parseInt(input); + + if (light < 0) { + throw new WrongInputException(errorMsg); + } + if (light > MAX_VALUE_OF_SECS) { + throw new WrongInputException(errorMsgDayIsOver); + } + + return light; + + } catch (NumberFormatException e) { + throw new WrongInputException(errorMsg); + } + } +} 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..8227f297 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,10 @@ +package homework_2.traffic_light; + +import java.io.IOException; + +public class Main { + + public static void main(String[] args) throws IOException { + 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 e635fbe1..4c202dce 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,53 +1,39 @@ package homework_2.traffic_light; -import homework_2.Utils; +import homework_2.WrongInputException; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; public class TrafficLight { + private final int GREEN_TO_YELLOW = 35; + private final int YELLOW_TO_RED = 40; + private final int RED_TO_YELLOW = 55; - public static final int BOUND_1 = 35; - public static final int BOUND_2 = 40; - public static final int BOUND_3 = 55; - public static final int MAX_VALUE = 86399; - - public static final int SEC_IN_MIN = 60; - - public static void main(String[] args) throws IOException { - try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { - while (true) { - String input = br.readLine(); - if (!Utils.isInt(input)) { - if (input.trim().equals("exit")) { - break; - } - System.out.println("Wrong input format, try integer number, your input: " + input); - continue; - } - - int light = Integer.parseInt(input); - if (light < 0) { - System.out.println("Positive values supported only, your value: " + light); - continue; - } else if (light > MAX_VALUE) { - System.out.println("Day's over, try smaller value"); - continue; - } - - light = light % SEC_IN_MIN; - - if (light < BOUND_1) { - System.out.println("GREEN"); - } else if (light < BOUND_2) { - System.out.println("YELLOW"); - } else if (light < BOUND_3) { - System.out.println("RED"); - } else { - System.out.println("YELLOW"); - } - } + private final int SEC_IN_MIN = 60; + + public void run() throws IOException { + try { + InputReader inputReader = new InputReader(); + int wholeSecs = inputReader.readSecs(); + + int secs = wholeSecs % SEC_IN_MIN; + + printColor(secs); + } catch (WrongInputException e) { + System.out.println(e.getMessage()); } } + + private void printColor(int secs) { + if (secs < GREEN_TO_YELLOW) { + System.out.println("GREEN"); + } else if (secs < YELLOW_TO_RED) { + System.out.println("YELLOW"); + } else if (secs < RED_TO_YELLOW) { + System.out.println("RED"); + } else { + System.out.println("YELLOW"); + } + } + } From ef2cbb5fd3e94c7af091a29980f375f8932d342c Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Tue, 10 Aug 2021 04:51:58 +0300 Subject: [PATCH 13/33] HW2 fixed style issues --- src/main/java/homework_2/pyramid_printer/Main.java | 4 +--- .../homework_2/pyramid_printer/PyramidPrinter.java | 4 ++-- .../homework_2/random_chars_table/InputReader.java | 6 +++++- .../random_chars_table/RandomCharsTable.java | 4 ++-- .../java/homework_2/traffic_light/InputReader.java | 10 +++++----- .../java/homework_2/traffic_light/TrafficLight.java | 4 ++-- 6 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index 1d8733a3..71e33035 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -1,10 +1,8 @@ package homework_2.pyramid_printer; -import java.io.IOException; - public class Main { - public static void main(String[] args) throws IOException { + public static void main(String[] args) { 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 d9fcb043..5019272b 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,13 +6,13 @@ public class PyramidPrinter { private final char SPEC_CHAR = 'x'; - public void run() throws IOException { + public void run() { try { InputReader inputReader = new InputReader(); int n = inputReader.readNum(); System.out.println(getPyramid(n)); - } catch (WrongInputException e) { + } catch (WrongInputException | IOException e) { System.out.println(e.getMessage()); } } diff --git a/src/main/java/homework_2/random_chars_table/InputReader.java b/src/main/java/homework_2/random_chars_table/InputReader.java index 83f67ea6..f0fb3ee7 100644 --- a/src/main/java/homework_2/random_chars_table/InputReader.java +++ b/src/main/java/homework_2/random_chars_table/InputReader.java @@ -13,7 +13,11 @@ public class InputReader { protected Table readTableParams() throws IOException, WrongInputException { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { String input = br.readLine(); - return parseInput(input); + if (input == null) { + throw new WrongInputException(ERROR_MSG); + } else { + return parseInput(input); + } } } 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 9e719ce9..c7c882de 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -6,7 +6,7 @@ public class RandomCharsTable { - public void run() throws IOException { + public void run() { try { InputReader inputReader = new InputReader(); Table table = inputReader.readTableParams(); @@ -19,7 +19,7 @@ public void run() throws IOException { strategyCharacterSet.fillCharacterSet(table); strategyCharacterSet.printCharacterSet(table.getStrategy()); - } catch (WrongInputException e) { + } catch (WrongInputException | IOException e) { System.out.println(e.getMessage()); } } diff --git a/src/main/java/homework_2/traffic_light/InputReader.java b/src/main/java/homework_2/traffic_light/InputReader.java index e30b52f0..16c8cff4 100644 --- a/src/main/java/homework_2/traffic_light/InputReader.java +++ b/src/main/java/homework_2/traffic_light/InputReader.java @@ -7,8 +7,8 @@ import java.io.InputStreamReader; public class InputReader { - private final String errorMsgDayIsOver = "The day is over"; - private final String errorMsg = "Only 1 non-negative integer is allowed as passed parameter"; + private final String ERROR_MSG_DAY_IS_OVER = "The day is over"; + private final String ERROR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; private final int MAX_VALUE_OF_SECS = 86399; protected int readSecs() throws IOException, WrongInputException { @@ -23,16 +23,16 @@ private int parseInput(String input) throws WrongInputException { int light = Integer.parseInt(input); if (light < 0) { - throw new WrongInputException(errorMsg); + throw new WrongInputException(ERROR_MSG); } if (light > MAX_VALUE_OF_SECS) { - throw new WrongInputException(errorMsgDayIsOver); + throw new WrongInputException(ERROR_MSG_DAY_IS_OVER); } return light; } catch (NumberFormatException e) { - throw new WrongInputException(errorMsg); + throw new WrongInputException(ERROR_MSG); } } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 4c202dce..e7fceba0 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -11,7 +11,7 @@ public class TrafficLight { private final int SEC_IN_MIN = 60; - public void run() throws IOException { + public void run() { try { InputReader inputReader = new InputReader(); int wholeSecs = inputReader.readSecs(); @@ -19,7 +19,7 @@ public void run() throws IOException { int secs = wholeSecs % SEC_IN_MIN; printColor(secs); - } catch (WrongInputException e) { + } catch (WrongInputException | IOException e) { System.out.println(e.getMessage()); } } From fab30755fc57254843999297fa5dbe8f6d4e89c4 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Tue, 10 Aug 2021 04:52:44 +0300 Subject: [PATCH 14/33] HW3 Immutable class and test added --- src/main/java/homework_3/ImmutableCat.java | 55 +++++ src/test/java/homework_1/MainTest.java | 52 ++++ .../java/homework_2/PyramidPrinterTest.java | 73 ++++++ .../java/homework_2/RandomCharsTableTest.java | 228 ++++++++++++++++++ .../java/homework_2/TrafficLightTest.java | 153 ++++++++++++ 5 files changed, 561 insertions(+) create mode 100644 src/main/java/homework_3/ImmutableCat.java create mode 100644 src/test/java/homework_1/MainTest.java create mode 100644 src/test/java/homework_2/PyramidPrinterTest.java create mode 100644 src/test/java/homework_2/RandomCharsTableTest.java create mode 100644 src/test/java/homework_2/TrafficLightTest.java diff --git a/src/main/java/homework_3/ImmutableCat.java b/src/main/java/homework_3/ImmutableCat.java new file mode 100644 index 00000000..10f8eec3 --- /dev/null +++ b/src/main/java/homework_3/ImmutableCat.java @@ -0,0 +1,55 @@ +package homework_3; +/* +* Immutable class Cat +* +* Requirements for class to be immutable: +* +* The class must be declared as final (So that child classes can’t be created) +* Data members in the class must be declared as private (So that direct access is not allowed) +* Data members in the class must be declared as final (So that we can’t change the value of it after object creation) +* A parameterized constructor should initialize all the fields performing a deep copy (So that data members can’t be modified with object reference) +* Deep Copy of objects should be performed in the getter methods (To return a copy rather than returning the actual object reference) +* No setters (To not have the option to change the value of the instance variable) +* +* */ + +import java.util.HashMap; +import java.util.Map; + +public final class ImmutableCat { + private final String name; + private final int passportCode; + private final Map toyStorage; + + public ImmutableCat(String name, int passportCode, Map toyStorage) { + this.name = name; + this.passportCode = passportCode; + this.toyStorage = new HashMap<>(toyStorage); + } + + public ImmutableCat(String name, int passportCode) { + this.name = name; + this.passportCode = passportCode; + this.toyStorage = new HashMap<>(); + } + + public String getName() { + return name; + } + + public int getPassportCode() { + return passportCode; + } + + public Map getToyStorage() { + return new HashMap<>(toyStorage); + } + + public ImmutableCat getModifiedCat(ImmutableCat oldImmutableCat, String name) { + return new ImmutableCat(name, oldImmutableCat.getPassportCode(), oldImmutableCat.getToyStorage()); + } + + public ImmutableCat getModifiedBrokeCat(ImmutableCat oldImmutableCat) { + return new ImmutableCat(oldImmutableCat.getName(), oldImmutableCat.getPassportCode()); + } +} diff --git a/src/test/java/homework_1/MainTest.java b/src/test/java/homework_1/MainTest.java new file mode 100644 index 00000000..7b3be7de --- /dev/null +++ b/src/test/java/homework_1/MainTest.java @@ -0,0 +1,52 @@ +package homework_1; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MainTest extends UnitBase { + + @Test + void givenHiHelloError_whenPrintArgsUntilError_thenPrintingHiHelloAlarm() { + final String[] given = {"Hi", "Hello", "error"}; + + Main.main(given); + printOut(); + + assertEquals("Hi: 2 letters", getOutputLines()[0]); + assertEquals("Hello: 5 letters", getOutputLines()[1]); + assertEquals("\033[0;31mAlarm!\033[0m", getOutputLines()[2]); + } + + @Test + void givenError_whenPrintArgsUntilError_thenPrintingAlarm() { + final String[] given = {"error"}; + + Main.main(given); + printOut(); + + assertEquals("[0;31mAlarm!\u001B[0m", getOutputLines()[0]); + } + + @Test + void givenHiErrorBye_whenPrintArgsUntilError_thenPrintingHiAlarm() { + final String[] given = {"Hi", "error", "Bye"}; + + Main.main(given); + printOut(); + + assertEquals("Hi: 2 letters", getOutputLines()[0]); + assertEquals("\033[0;31mAlarm!\033[0m", getOutputLines()[1]); + } + + @Test + void givenNothing_whenPrintArgsUntilError_thenPrintingNothing() { + final String[] given = {}; + + Main.main(given); + printOut(); + + assertEquals("", getOutputLines()[0]); + } +} diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java new file mode 100644 index 00000000..290aa763 --- /dev/null +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -0,0 +1,73 @@ +package homework_2; + +import base.UnitBase; +import homework_2.pyramid_printer.PyramidPrinter; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PyramidPrinterTest extends UnitBase { + private final String ERROR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + + @Test + void givenInteger3_whenRunPyramidPrinter_thenPrintingPyramidOfSimbolsX() { + setInput("3"); + + new PyramidPrinter().run(); + printOut(); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + } + + @Test + void givenInteger1_whenRunPyramidPrinter_thenPrintingOneSimbolX() { + setInput("1"); + + new PyramidPrinter().run(); + printOut(); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void givenInteger0_whenRunPyramidPrinter_thenPrintNothing() { + setInput("0"); + + new PyramidPrinter().run(); + printOut(); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void givenNegativeInteger_whenRunPyramidPrinter_thenPrintErrorMsg() { + setInput("-1"); + + new PyramidPrinter().run(); + printOut(); + + assertEquals(ERROR_MSG, getOutputLines()[0]); + } + + @Test + void givenStringHi_whenRunPyramidPrinter_thenPrintErrorMsg() { + setInput("Hi"); + + new PyramidPrinter().run(); + printOut(); + + assertEquals(ERROR_MSG, getOutputLines()[0]); + } + + @Test + void givenEmptyString_whenRunPyramidPrinter_thenPrintErrorMsg() { + setInput(""); + + new PyramidPrinter().run(); + printOut(); + + assertEquals(ERROR_MSG, getOutputLines()[0]); + } +} diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java new file mode 100644 index 00000000..4e5655e9 --- /dev/null +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -0,0 +1,228 @@ +package homework_2; + +import base.UnitBase; +import homework_2.random_chars_table.RandomCharsTable; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class RandomCharsTableTest extends UnitBase { + private final String ERROR_MSG = "Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]"; + + @Test + void given3_3_even_whenRunRandomCharsTable_thenPrinting3rowTable() { + final int row = 3; + final int column = 3; + final String strategy = "even"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String[] actual = getOutputLines(); + + assertEquals(row, actual.length - 1); + } + + @Test + void given4_8_even_whenRunRandomCharsTable_thenPrinting8columnTable() { + final int row = 4; + final int column = 8; + final String strategy = "even"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String[] actual = getOutputLines(); + + assertEquals(column, charsInRow(0, actual).size()); + } + + @Test + void given5_2_even_whenRunRandomCharsTable_thenPrintingTableWith10Chars() { + final int row = 5; + final int column = 2; + final String strategy = "even"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String[] actual = getOutputLines(); + + assertEquals(row * column, charsInTable(actual, row).size()); + } + + @Test + void given4_7_even_whenRunRandomCharsTable_thenPrintingEvenCharsCorrectly() { + final int row = 4; + final int column = 7; + final String strategy = "even"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String[] table = getOutputLines(); + + final Set actualEvens = parseToSet(table[table.length - 1].substring(14).replace(" ", "").replace(",", "")); + final Set expectedEvens = getEvens(charsInTable(table, row)); + + assertEquals(expectedEvens, actualEvens); + } + + @Test + void given12_1_odd_whenRunRandomCharsTable_thenPrintingOddCharsCorrectly() { + final int row = 12; + final int column = 1; + final String strategy = "odd"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String[] table = getOutputLines(); + + final Set actualOdds = parseToSet(table[table.length - 1].substring(13).replace(" ", "").replace(",", "")); + final Set expectedOdds = getOdds(charsInTable(table, row)); + + assertEquals(expectedOdds, actualOdds); + } + + @Test + void given1_0_odd_whenRunRandomCharsTable_thenPrintingErrorMsg() { + final int row = 1; + final int column = 0; + final String strategy = "odd"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String actual = getOutputLines()[0]; + + assertEquals(ERROR_MSG, actual); + } + + @Test + void givenNegative_1_odd_whenRunRandomCharsTable_thenPrintingErrorMsg() { + final int row = -10; + final int column = 1; + final String strategy = "odd"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String actual = getOutputLines()[0]; + + assertEquals(ERROR_MSG, actual); + } + + @Test + void given6_1_hi_whenRunRandomCharsTable_thenPrintingErrorMsg() { + final int row = 6; + final int column = 1; + final String strategy = "hi"; + + setInput(row + " " + column + " " + strategy); + + new RandomCharsTable().run(); + printOut(); + + final String actual = getOutputLines()[0]; + + assertEquals(ERROR_MSG, actual); + } + + @Test + void givenHello_whenRunRandomCharsTable_thenPrintingErrorMsg() { + setInput("Hello"); + + new RandomCharsTable().run(); + printOut(); + + final String actual = getOutputLines()[0]; + + assertEquals(ERROR_MSG, actual); + } + + @Test + void givenEmptyString_whenRunRandomCharsTable_thenPrintingErrorMsg() { + setInput(""); + + new RandomCharsTable().run(); + printOut(); + + final String actual = getOutputLines()[0]; + + assertEquals(ERROR_MSG, actual); + } + + private List charsInRow(int row, String[] table) { + List chars = new ArrayList<>(); + + for (char c : table[row].toCharArray()) { + if (c >= 'A' && c <= 'Z') { + chars.add(c); + } + } + return chars; + } + + private List charsInTable(String[] table, int rows) { + List chars = new ArrayList<>(); + + for (int i = 0; i < rows; i++) { + chars.addAll(charsInRow(i, table)); + } + + return chars; + } + + private Set getEvens(List chars) { + Set evens = new HashSet<>(); + + for (char c : chars) { + if (isEven(c)) { + evens.add(c + ""); + } + } + return evens; + } + + private Set getOdds(List chars) { + Set odds = new HashSet<>(); + + for (char c : chars) { + if (!isEven(c)) { + odds.add(c + ""); + } + } + return odds; + } + + private boolean isEven(char c) { + return c % 2 == 0; + } + + private Set parseToSet(String str) { + Set chars = new HashSet<>(); + + for (char c: str.toCharArray()) { + chars.add(c + ""); + } + return chars; + } +} diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java new file mode 100644 index 00000000..527fd3df --- /dev/null +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -0,0 +1,153 @@ +package homework_2; + +import base.UnitBase; +import homework_2.traffic_light.TrafficLight; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightTest extends UnitBase { + private final String ERROR_MSG_DAY_IS_OVER = "The day is over"; + private final String ERROR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + private final int MAX_VALUE_OF_SECS = 86399; + + @Test + void givenInteger0_whenRunTrafficLight_thenPrintingGreen() { + setInput("0"); + + new TrafficLight().run(); + printOut(); + + assertEquals("GREEN", getOutputLines()[0]); + } + + @Test + void givenInteger25_whenRunTrafficLight_thenPrintingGreen() { + setInput("25"); + + new TrafficLight().run(); + printOut(); + + assertEquals("GREEN", getOutputLines()[0]); + } + + @Test + void givenInteger35_whenRunTrafficLight_thenPrintingYellow() { + setInput("35"); + + new TrafficLight().run(); + printOut(); + + assertEquals("YELLOW", getOutputLines()[0]); + } + + @Test + void givenInteger37_whenRunTrafficLight_thenPrintingYellow() { + setInput("37"); + + new TrafficLight().run(); + printOut(); + + assertEquals("YELLOW", getOutputLines()[0]); + } + + @Test + void givenInteger40_whenRunTrafficLight_thenPrintingRed() { + setInput("40"); + + new TrafficLight().run(); + printOut(); + + assertEquals("RED", getOutputLines()[0]); + } + + @Test + void givenInteger50_whenRunTrafficLight_thenPrintingRed() { + setInput("50"); + + new TrafficLight().run(); + printOut(); + + assertEquals("RED", getOutputLines()[0]); + } + + @Test + void givenInteger55_whenRunTrafficLight_thenPrintingYellow() { + setInput("55"); + + new TrafficLight().run(); + printOut(); + + assertEquals("YELLOW", getOutputLines()[0]); + } + + @Test + void givenInteger59_whenRunTrafficLight_thenPrintingYellow() { + setInput("59"); + + new TrafficLight().run(); + printOut(); + + assertEquals("YELLOW", getOutputLines()[0]); + } + + @Test + void givenInteger60_whenRunTrafficLight_thenPrintingGreen() { + setInput("60"); + + new TrafficLight().run(); + printOut(); + + assertEquals("GREEN", getOutputLines()[0]); + } + + @Test + void givenMaxSecsInteger_whenRunTrafficLight_thenPrintingYellow() { + setInput(String.valueOf(MAX_VALUE_OF_SECS)); + + new TrafficLight().run(); + printOut(); + + assertEquals("YELLOW", getOutputLines()[0]); + } + + @Test + void givenNextToMaxSecsInteger_whenRunTrafficLight_thenPrintingErrorMsg() { + setInput(String.valueOf(MAX_VALUE_OF_SECS + 1)); + + new TrafficLight().run(); + printOut(); + + assertEquals(ERROR_MSG_DAY_IS_OVER, getOutputLines()[0]); + } + + @Test + void givenNegativeInteger_whenRunTrafficLight_thenPrintingErrorMsg() { + setInput("-1"); + + new TrafficLight().run(); + printOut(); + + assertEquals(ERROR_MSG, getOutputLines()[0]); + } + + @Test + void givenStringHi_whenRunTrafficLight_thenPrintingErrorMsg() { + setInput("Hi"); + + new TrafficLight().run(); + printOut(); + + assertEquals(ERROR_MSG, getOutputLines()[0]); + } + + @Test + void givenEmptyString_whenRunTrafficLight_thenPrintingErrorMsg() { + setInput(""); + + new TrafficLight().run(); + printOut(); + + assertEquals(ERROR_MSG, getOutputLines()[0]); + } +} From 6b543ca399013e8c3962560beedca8f24d11b7b1 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Tue, 10 Aug 2021 04:53:01 +0300 Subject: [PATCH 15/33] HW3 README.md updated --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index eca5eba3..24ce1a89 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ | HW 2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/traffic_light) | The app that reads number of seconds from the beginning of the day from the console and calculates color of the traffic light | | HW 2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/pyramid_printer) | The app that prints pyramid of 'x' chars based on user input | | HW 2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/random_chars_table) | The app that reads length, width and strategy from the console and generates table of random chars and prints even/odd letters according to strategy | +| HW 3 | [Immutable Class Cat](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_3) | The app that reads length, width and strategy from the console and generates table of random chars and prints even/odd letters according to strategy | +| | | | +| Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | +| Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 4bda0da43de4ba5b704e571000cfa99a72ed2ac6 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Mon, 16 Aug 2021 12:55:15 +0300 Subject: [PATCH 16/33] HW4 CustomFileReader with tests added --- .../custom_file_reader/CustomFileReader.java | 73 +++++++++++++++++++ .../homework_4/custom_file_reader/Main.java | 9 +++ .../custom_file_reader/custom_file_reader.txt | 3 + .../CustomFileReaderRun1Test.java | 69 ++++++++++++++++++ .../CustomFileReaderRun2Test.java | 71 ++++++++++++++++++ .../CustomFileReaderRun3Test.java | 69 ++++++++++++++++++ .../custom_file_commas_and_dots_only.txt | 2 + .../custom_file_reader_OK.txt | 2 + .../custom_file_reader_empty.txt | 0 ...om_file_reader_without_commas_and_dots.txt | 2 + 10 files changed, 300 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/resources/custom_file_reader/custom_file_reader.txt create mode 100644 src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun1Test.java create mode 100644 src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun2Test.java create mode 100644 src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun3Test.java create mode 100644 src/test/resources/custom_file_reader/custom_file_commas_and_dots_only.txt create mode 100644 src/test/resources/custom_file_reader/custom_file_reader_OK.txt create mode 100644 src/test/resources/custom_file_reader/custom_file_reader_empty.txt create mode 100644 src/test/resources/custom_file_reader/custom_file_reader_without_commas_and_dots.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 new file mode 100644 index 00000000..0f357b19 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,73 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; +import java.util.Scanner; + +public class CustomFileReader { + private String fileName; + private String pathToResources; + + public CustomFileReader() { + this.fileName = "custom_file_reader/custom_file_reader.txt"; + this.pathToResources = "src/main/resources/"; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + public void setPathToResources(String pathToResources) { this.pathToResources = pathToResources; } + + + // BufferedReader approach + public void run1() { + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(getFileFromResources()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + printLineWithoutDotsAndCommas(line); + } + } catch (NullPointerException | IOException e) { + System.out.println("File not found"); + } + } + + + // NOI approach + public void run2() { + Path path = Paths.get(pathToResources + fileName); + + try (BufferedReader bufferedReader = Files.newBufferedReader(path)) { + String line; + while ((line = bufferedReader.readLine()) != null) { + printLineWithoutDotsAndCommas(line); + } + } catch (IOException e) { + System.out.println("File not found"); + } + } + + + // Scanner approach + public void run3() { + try (Scanner scanner = new Scanner(getFileFromResources())) { + while (scanner.hasNext()) { + String line = scanner.nextLine(); + printLineWithoutDotsAndCommas(line); + } + } catch (FileNotFoundException | NullPointerException e) { + System.out.println("File not found"); + } + } + + private File getFileFromResources() throws NullPointerException { + ClassLoader classLoader = getClass().getClassLoader(); + return new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile()); + } + + private void printLineWithoutDotsAndCommas(String line) { + System.out.println(line.replace(",", "").replace(".", "")); + } +} 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..01087a42 --- /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(); + new CustomFileReader().run2(); + new CustomFileReader().run3(); + } +} diff --git a/src/main/resources/custom_file_reader/custom_file_reader.txt b/src/main/resources/custom_file_reader/custom_file_reader.txt new file mode 100644 index 00000000..96256074 --- /dev/null +++ b/src/main/resources/custom_file_reader/custom_file_reader.txt @@ -0,0 +1,3 @@ +1 3 5 4 6 7 8 ,9 hv 6yiu, hg , lkl +njnkn +bnm,l. jnl \ No newline at end of file diff --git a/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun1Test.java b/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun1Test.java new file mode 100644 index 00000000..27fc2284 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun1Test.java @@ -0,0 +1,69 @@ +package homework_4.custom_file_reader_tests; + +import base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomFileReaderRun1Test extends UnitBase { + private CustomFileReader customFileReader; + + @BeforeEach + void setCustomFileReader() { + customFileReader = new CustomFileReader(); + } + + @Test + void givenOKFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_OK.txt"); + customFileReader.run1(); + + String[] actual = getOutputLines(); + + assertEquals("string with commas and dots", actual[0]); + assertEquals("another string with commas and dots", actual[1]); + } + + @Test + void givenFileWithoutCommasAndDots_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_without_commas_and_dots.txt"); + customFileReader.run1(); + + String[] actual = getOutputLines(); + + assertEquals("file without commas and dots", actual[0]); + assertEquals("another line of file without commas and dots", actual[1]); + } + + @Test + void givenFileWithOnlyCommasAndDots_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_commas_and_dots_only.txt"); + customFileReader.run1(); + + String[] actual = getOutputLines(); + + assertEquals("", actual[0]); + } + + @Test + void givenEmptyFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_empty.txt"); + customFileReader.run1(); + + String[] actual = getOutputLines(); + + assertEquals("", actual[0]); + } + + @Test + void givenNonExistentFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_not_exist.txt"); + customFileReader.run1(); + + String[] actual = getOutputLines(); + + assertEquals("File not found", actual[0]); + } +} diff --git a/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun2Test.java b/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun2Test.java new file mode 100644 index 00000000..45c7f5df --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun2Test.java @@ -0,0 +1,71 @@ +package homework_4.custom_file_reader_tests; + +import base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomFileReaderRun2Test extends UnitBase { + private final String pathToResources = "src/test/resources/"; + private CustomFileReader customFileReader; + + @BeforeEach + void setCustomFileReader() { + customFileReader = new CustomFileReader(); + customFileReader.setPathToResources(pathToResources); + } + + @Test + void givenOKFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_OK.txt"); + customFileReader.run2(); + + String[] actual1 = getOutputLines(); + + assertEquals("string with commas and dots", actual1[0]); + assertEquals("another string with commas and dots", actual1[1]); + } + + @Test + void givenFileWithoutCommasAndDots_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_without_commas_and_dots.txt"); + customFileReader.run2(); + + String[] actual = getOutputLines(); + + assertEquals("file without commas and dots", actual[0]); + assertEquals("another line of file without commas and dots", actual[1]); + } + + @Test + void givenFileWithOnlyCommasAndDots_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_commas_and_dots_only.txt"); + customFileReader.run2(); + + String[] actual = getOutputLines(); + + assertEquals("", actual[0]); + } + + @Test + void givenEmptyFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_empty.txt"); + customFileReader.run2(); + + String[] actual = getOutputLines(); + + assertEquals("", actual[0]); + } + + @Test + void givenNonExistentFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_not_exist.txt"); + customFileReader.run2(); + + String[] actual = getOutputLines(); + + assertEquals("File not found", actual[0]); + } +} diff --git a/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun3Test.java b/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun3Test.java new file mode 100644 index 00000000..daef224a --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader_tests/CustomFileReaderRun3Test.java @@ -0,0 +1,69 @@ +package homework_4.custom_file_reader_tests; + +import base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomFileReaderRun3Test extends UnitBase { + private CustomFileReader customFileReader; + + @BeforeEach + void setCustomFileReader() { + customFileReader = new CustomFileReader(); + } + + @Test + void givenOKFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_OK.txt"); + customFileReader.run3(); + + String[] actual = getOutputLines(); + + assertEquals("string with commas and dots", actual[0]); + assertEquals("another string with commas and dots", actual[1]); + } + + @Test + void givenFileWithoutCommasAndDots_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_without_commas_and_dots.txt"); + customFileReader.run3(); + + String[] actual = getOutputLines(); + + assertEquals("file without commas and dots", actual[0]); + assertEquals("another line of file without commas and dots", actual[1]); + } + + @Test + void givenFileWithOnlyCommasAndDots_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_commas_and_dots_only.txt"); + customFileReader.run3(); + + String[] actual = getOutputLines(); + + assertEquals("", actual[0]); + } + + @Test + void givenEmptyFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader/custom_file_reader_empty.txt"); + customFileReader.run3(); + + String[] actual = getOutputLines(); + + assertEquals("", actual[0]); + } + + @Test + void givenNonExistentFile_whenRunBufferedReader_thenPrintCorrectly() { + customFileReader.setFileName("custom_file_reader_not_exist.txt"); + customFileReader.run3(); + + String[] actual = getOutputLines(); + + assertEquals("File not found", actual[0]); + } +} diff --git a/src/test/resources/custom_file_reader/custom_file_commas_and_dots_only.txt b/src/test/resources/custom_file_reader/custom_file_commas_and_dots_only.txt new file mode 100644 index 00000000..ba4486f9 --- /dev/null +++ b/src/test/resources/custom_file_reader/custom_file_commas_and_dots_only.txt @@ -0,0 +1,2 @@ +,, .. ,,,,,, ,.,., .,.,. ,.,., , +,, .,.., ,., \ No newline at end of file diff --git a/src/test/resources/custom_file_reader/custom_file_reader_OK.txt b/src/test/resources/custom_file_reader/custom_file_reader_OK.txt new file mode 100644 index 00000000..1389b292 --- /dev/null +++ b/src/test/resources/custom_file_reader/custom_file_reader_OK.txt @@ -0,0 +1,2 @@ +string with, commas and... ,dots +another ,string. with commas,, and,.., dots \ No newline at end of file diff --git a/src/test/resources/custom_file_reader/custom_file_reader_empty.txt b/src/test/resources/custom_file_reader/custom_file_reader_empty.txt new file mode 100644 index 00000000..e69de29b diff --git a/src/test/resources/custom_file_reader/custom_file_reader_without_commas_and_dots.txt b/src/test/resources/custom_file_reader/custom_file_reader_without_commas_and_dots.txt new file mode 100644 index 00000000..d4f1f622 --- /dev/null +++ b/src/test/resources/custom_file_reader/custom_file_reader_without_commas_and_dots.txt @@ -0,0 +1,2 @@ +file without commas and dots +another line of file without commas and dots \ No newline at end of file From 40d6fd5aa09b0432b66545a07210ff8f6f1139f2 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Mon, 16 Aug 2021 13:31:41 +0300 Subject: [PATCH 17/33] HW4 Singleton with tests added --- src/main/java/homework_4/singleton/Main.java | 11 ++++++++ .../java/homework_4/singleton/Singleton.java | 25 +++++++++++++++++++ .../singleton_test/SingletonTest.java | 17 +++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 src/main/java/homework_4/singleton/Main.java create mode 100644 src/main/java/homework_4/singleton/Singleton.java create mode 100644 src/test/java/homework_4/singleton_test/SingletonTest.java diff --git a/src/main/java/homework_4/singleton/Main.java b/src/main/java/homework_4/singleton/Main.java new file mode 100644 index 00000000..e7b4f186 --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,11 @@ +package homework_4.singleton; + +public class Main { + + public static void main(String[] args) { + Singleton singleton = Singleton.getInstance(); + Singleton secondSingleton = Singleton.getInstance(); + + System.out.println(singleton == secondSingleton); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..2e7b9a1e --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,25 @@ +package homework_4.singleton; + +public class Singleton { + private static Singleton instance = null; + + private Singleton(){} + + /* + * Reason to do double check and make second check synchronized: + * most of the time instance won't be null, + * so there's no need to restrict threads access to the first if-clause. + * If there is a real suspicion that instance might be null, then + * we double check in sync block + */ + public static Singleton getInstance() { + if (instance == null) { + synchronized (Singleton.class) { + if (instance == null) { + instance = new Singleton(); + } + } + } + return instance; + } +} diff --git a/src/test/java/homework_4/singleton_test/SingletonTest.java b/src/test/java/homework_4/singleton_test/SingletonTest.java new file mode 100644 index 00000000..731d6b6c --- /dev/null +++ b/src/test/java/homework_4/singleton_test/SingletonTest.java @@ -0,0 +1,17 @@ +package homework_4.singleton_test; + +import homework_4.singleton.Singleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertSame; + +public class SingletonTest { + + @Test + void givenNothing_whenCreateTwoInstancesOfSingleton_thenTheyAreOneInstance() { + Singleton singleton1 = Singleton.getInstance(); + Singleton singleton2 = Singleton.getInstance(); + + assertSame(singleton1, singleton2); + } +} From 94a4ebb5b0ba6091ed9043fd4f281cb1a30c9d90 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Mon, 16 Aug 2021 13:49:29 +0300 Subject: [PATCH 18/33] HW4 CustomAnnotation with tests added --- .../homework_4/custom_annotation/Cat.java | 29 +++++++++++++++++++ .../custom_annotation/CustomAnnotation.java | 13 +++++++++ .../CustomAnnotationTest.java | 27 +++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 src/main/java/homework_4/custom_annotation/Cat.java create mode 100644 src/main/java/homework_4/custom_annotation/CustomAnnotation.java create mode 100644 src/test/java/homework_4/custom_annotation_tests/CustomAnnotationTest.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..37375c0f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Cat.java @@ -0,0 +1,29 @@ +package homework_4.custom_annotation; + +@CustomAnnotation(name = "Barsik", weight = 3.09) +public class Cat { + private final String name; + private final double weight; + private final double tailLength; + + public Cat() { + CustomAnnotation annotation = Cat.class.getAnnotation(CustomAnnotation.class); + name = annotation.name(); + weight = annotation.weight(); + tailLength = 0.5; + } + + public Cat(String name, double weight) { + this.name = name; + this.weight = weight; + tailLength = 0.5; + } + + public String getName() { + return name; + } + + public double getWeight() { + return weight; + } +} diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java new file mode 100644 index 00000000..5834435d --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -0,0 +1,13 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface CustomAnnotation { + String name(); + double weight(); +} diff --git a/src/test/java/homework_4/custom_annotation_tests/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation_tests/CustomAnnotationTest.java new file mode 100644 index 00000000..115e1a71 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation_tests/CustomAnnotationTest.java @@ -0,0 +1,27 @@ +package homework_4.custom_annotation_tests; + +import homework_4.custom_annotation.Cat; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomAnnotationTest { + + @Test + void givenNothing_whenCreateNewCatWithoutNameNorWeight_thenCreatedCatWithNameAndWeightSetInAnnotation() { + Cat cat = new Cat(); + + assertEquals("Barsik", cat.getName()); + assertEquals(3.09, cat.getWeight()); + } + + @Test + void givenNameAndWeight_whenCreateNewCatWithNameAndWeight_thenCreatedCatWithNameAndWeightPassedToConstructor() { + final String name = "Murzik"; + final double weight = 4.0; + Cat cat = new Cat(name, weight); + + assertEquals(name, cat.getName()); + assertEquals(weight, cat.getWeight()); + } +} From c971308839b66a42b74c814fe0df2d4de1bea774 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Mon, 16 Aug 2021 13:57:10 +0300 Subject: [PATCH 19/33] HW4 README.md updated --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 24ce1a89..962226cd 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,13 @@ | HW 2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/pyramid_printer) | The app that prints pyramid of 'x' chars based on user input | | HW 2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_2/random_chars_table) | The app that reads length, width and strategy from the console and generates table of random chars and prints even/odd letters according to strategy | | HW 3 | [Immutable Class Cat](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_3) | The app that reads length, width and strategy from the console and generates table of random chars and prints even/odd letters according to strategy | +| HW 4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_file_reader) | Class with three read-from-file approaches implementations: BufferedReader, NIO, Scanner | +| HW 4.2 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/singleton) | Singleton pattern implementation | +| HW 4.3 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_annotation) | Custom annotation and its use with class cat | | | | | | Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | | Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | +| Tests HW 4 | [Tests for HM 4 Custom File Reader, Singleton and Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_4) | JUnit tests for apps from homework 4 | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 114b25927b126f2473a62d4199e7101d8093fb27 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 18 Aug 2021 19:34:17 +0300 Subject: [PATCH 20/33] HW5 done (by verbal task description) --- src/main/java/homework_5/Main.java | 11 ++++ src/main/java/homework_5/PowerRecursion.java | 25 ++++++++ .../java/homework_5/PowerRecursionTest.java | 60 +++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 src/main/java/homework_5/Main.java create mode 100644 src/main/java/homework_5/PowerRecursion.java create mode 100644 src/test/java/homework_5/PowerRecursionTest.java diff --git a/src/main/java/homework_5/Main.java b/src/main/java/homework_5/Main.java new file mode 100644 index 00000000..44535694 --- /dev/null +++ b/src/main/java/homework_5/Main.java @@ -0,0 +1,11 @@ +package homework_5; + +public class Main { + + public static void main(String[] args) { + int n = 2; + int power = -4; + + System.out.println(new PowerRecursion(n, power).run()); + } +} diff --git a/src/main/java/homework_5/PowerRecursion.java b/src/main/java/homework_5/PowerRecursion.java new file mode 100644 index 00000000..278c2ef7 --- /dev/null +++ b/src/main/java/homework_5/PowerRecursion.java @@ -0,0 +1,25 @@ +package homework_5; + +public class PowerRecursion { + private int n; + private int power; + + public PowerRecursion(int n, int power) { + if (power < 0) { + throw new IllegalArgumentException(); + } + this.n = n; + this.power = power; + } + + public long run() { + return power(1, 0); + } + + private long power(int res, int count) { + if (count == power) { + return res; + } + return power(n * res, ++count); + } +} diff --git a/src/test/java/homework_5/PowerRecursionTest.java b/src/test/java/homework_5/PowerRecursionTest.java new file mode 100644 index 00000000..20bafe14 --- /dev/null +++ b/src/test/java/homework_5/PowerRecursionTest.java @@ -0,0 +1,60 @@ +package homework_5; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class PowerRecursionTest { + + @Test + void given2inPower5_whenRun_thenReturn32() { + final int num = 2; + final int power = 5; + + final int expected = 32; + final long actual = new PowerRecursion(num, power).run(); + + assertEquals(expected, actual); + } + + @Test + void given8inPower0_whenRun_thenReturn1() { + final int num = 8; + final int power = 0; + + final int expected = 1; + final long actual = new PowerRecursion(num, power).run(); + + assertEquals(expected, actual); + } + + @Test + void given9inPower1_whenRun_thenReturn9() { + final int num = 9; + final int power = 1; + + final int expected = 9; + final long actual = new PowerRecursion(num, power).run(); + + assertEquals(expected, actual); + } + + @Test + void givenNegative3inPower4AndPositive3InPower4_whenRunAndCompare_thenEqual() { + final int num1 = -3; + final int num2 = 3; + final int power = 4; + + assertEquals(new PowerRecursion(num1, power).run(), new PowerRecursion(num2, power).run()); + } + + @Test() + void givenNegativePower_whenRun_thenThrowException() { + final int num = 7; + final int power = -8; + + assertThrows(IllegalArgumentException.class, () -> new PowerRecursion(num, power).run()); + + } +} From 8c050c3e89713f71f8dbca75b02fd6c0ea19776c Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 18 Aug 2021 19:39:54 +0300 Subject: [PATCH 21/33] HW5 README.md updated --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 962226cd..1c6cad68 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,12 @@ | HW 4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_file_reader) | Class with three read-from-file approaches implementations: BufferedReader, NIO, Scanner | | HW 4.2 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/singleton) | Singleton pattern implementation | | HW 4.3 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_annotation) | Custom annotation and its use with class cat | +| HW 5 | [Power by Recursion](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5) | Power by recursion | | | | | | Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | | Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | | Tests HW 4 | [Tests for HM 4 Custom File Reader, Singleton and Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_4) | JUnit tests for apps from homework 4 | +| Tests HW 5 | [Tests for HM 5 Power by recursion](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_5) | JUnit tests for app from homework 5 | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 78691222eeac53f33a02cde8c7a4d9df95bc1210 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Mon, 6 Sep 2021 14:03:51 +0300 Subject: [PATCH 22/33] HW5 change PowerOfNumber according to written task in teams --- README.md | 4 +- src/main/java/homework_5/Main.java | 11 ---- src/main/java/homework_5/PowerRecursion.java | 25 -------- .../power_of_number/InputReader.java | 46 +++++++++++++ .../java/homework_5/power_of_number/Main.java | 8 +++ .../power_of_number/PowerOfNumber.java | 31 +++++++++ .../java/homework_5/PowerOfNumberTest.java | 64 +++++++++++++++++++ .../java/homework_5/PowerRecursionTest.java | 60 ----------------- 8 files changed, 151 insertions(+), 98 deletions(-) delete mode 100644 src/main/java/homework_5/Main.java delete mode 100644 src/main/java/homework_5/PowerRecursion.java create mode 100644 src/main/java/homework_5/power_of_number/InputReader.java 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/PowerOfNumberTest.java delete mode 100644 src/test/java/homework_5/PowerRecursionTest.java diff --git a/README.md b/README.md index 1c6cad68..e9838c56 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,12 @@ | HW 4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_file_reader) | Class with three read-from-file approaches implementations: BufferedReader, NIO, Scanner | | HW 4.2 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/singleton) | Singleton pattern implementation | | HW 4.3 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_annotation) | Custom annotation and its use with class cat | -| HW 5 | [Power by Recursion](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5) | Power by recursion | +| HW 5 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5) | Power function implementation with recursion | | | | | | Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | | Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | | Tests HW 4 | [Tests for HM 4 Custom File Reader, Singleton and Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_4) | JUnit tests for apps from homework 4 | -| Tests HW 5 | [Tests for HM 5 Power by recursion](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_5) | JUnit tests for app from homework 5 | +| Tests HW 5 | [Tests for HM 5 Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_5) | JUnit tests for app from homework 5 | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/homework_5/Main.java b/src/main/java/homework_5/Main.java deleted file mode 100644 index 44535694..00000000 --- a/src/main/java/homework_5/Main.java +++ /dev/null @@ -1,11 +0,0 @@ -package homework_5; - -public class Main { - - public static void main(String[] args) { - int n = 2; - int power = -4; - - System.out.println(new PowerRecursion(n, power).run()); - } -} diff --git a/src/main/java/homework_5/PowerRecursion.java b/src/main/java/homework_5/PowerRecursion.java deleted file mode 100644 index 278c2ef7..00000000 --- a/src/main/java/homework_5/PowerRecursion.java +++ /dev/null @@ -1,25 +0,0 @@ -package homework_5; - -public class PowerRecursion { - private int n; - private int power; - - public PowerRecursion(int n, int power) { - if (power < 0) { - throw new IllegalArgumentException(); - } - this.n = n; - this.power = power; - } - - public long run() { - return power(1, 0); - } - - private long power(int res, int count) { - if (count == power) { - return res; - } - return power(n * res, ++count); - } -} diff --git a/src/main/java/homework_5/power_of_number/InputReader.java b/src/main/java/homework_5/power_of_number/InputReader.java new file mode 100644 index 00000000..63f9eb08 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/InputReader.java @@ -0,0 +1,46 @@ +package homework_5.power_of_number; + +import homework_2.WrongInputException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class InputReader { + private final String ERROR_MSG = "Only 2 non-negative integers are allowed"; + + protected int[] readParams() throws IOException, WrongInputException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + String input = br.readLine(); + if (input == null) { + throw new WrongInputException(ERROR_MSG); + } else { + return parseInput(input); + } + } + } + + private int[] parseInput(String input) throws WrongInputException { + String[] params = input.split(" +"); + try { + if (params.length == 2) { + int number = Integer.parseInt(params[0]); + int power = Integer.parseInt(params[1]); + + if (power >= 0 && number >= 0) { + int[] paramsInt = new int[params.length]; + for (int i = 0; i < params.length; i++) { + paramsInt[i] = Integer.parseInt(params[i]); + } + return paramsInt; + } else { + throw new WrongInputException(ERROR_MSG); + } + } else { + throw new WrongInputException(ERROR_MSG); + } + } catch (IllegalArgumentException e) { + throw new WrongInputException(ERROR_MSG); + } + } +} 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..ff23303d --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,31 @@ +package homework_5.power_of_number; + +import homework_2.WrongInputException; + +import java.io.IOException; + +public class PowerOfNumber { + private int number; + private int power; + + public void run() { + try { + InputReader inputReader = new InputReader(); + int[] params = inputReader.readParams(); + this.number = params[0]; + this.power = params[1]; + + System.out.println(String.valueOf(power(1, 0))); + + } catch (WrongInputException | IOException e) { + System.out.println(e.getMessage()); + } + } + + private long power(int res, int count) { + if (count == power) { + return res; + } + return power(number * res, ++count); + } +} diff --git a/src/test/java/homework_5/PowerOfNumberTest.java b/src/test/java/homework_5/PowerOfNumberTest.java new file mode 100644 index 00000000..45a12822 --- /dev/null +++ b/src/test/java/homework_5/PowerOfNumberTest.java @@ -0,0 +1,64 @@ +package homework_5; + +import base.UnitBase; +import homework_5.power_of_number.PowerOfNumber; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PowerOfNumberTest extends UnitBase { + + @Test + void given2inPower5_whenRun_thenReturn32() { + setInput("2 5"); + + new PowerOfNumber().run(); + + assertEquals("32", getOutputLines()[0]); + } + + @Test + void given8inPower0_whenRun_thenReturn1() { + setInput("8 0"); + + new PowerOfNumber().run(); + + assertEquals("1", getOutputLines()[0]); + } + + @Test + void given9inPower1_whenRun_thenReturn9() { + setInput("9 1"); + + new PowerOfNumber().run(); + + assertEquals("9", getOutputLines()[0]); + } + + @Test() + void givenNegativePower_whenRun_thenPrintErrorMsg() { + setInput("9 -1"); + + new PowerOfNumber().run(); + + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test() + void givenNegativeNumber_whenRun_thenPrintErrorMsg() { + setInput("-9 1"); + + new PowerOfNumber().run(); + + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test() + void givenNotInteger_whenRun_thenPrintErrorMsg() { + setInput("Hello hi"); + + new PowerOfNumber().run(); + + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } +} diff --git a/src/test/java/homework_5/PowerRecursionTest.java b/src/test/java/homework_5/PowerRecursionTest.java deleted file mode 100644 index 20bafe14..00000000 --- a/src/test/java/homework_5/PowerRecursionTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package homework_5; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class PowerRecursionTest { - - @Test - void given2inPower5_whenRun_thenReturn32() { - final int num = 2; - final int power = 5; - - final int expected = 32; - final long actual = new PowerRecursion(num, power).run(); - - assertEquals(expected, actual); - } - - @Test - void given8inPower0_whenRun_thenReturn1() { - final int num = 8; - final int power = 0; - - final int expected = 1; - final long actual = new PowerRecursion(num, power).run(); - - assertEquals(expected, actual); - } - - @Test - void given9inPower1_whenRun_thenReturn9() { - final int num = 9; - final int power = 1; - - final int expected = 9; - final long actual = new PowerRecursion(num, power).run(); - - assertEquals(expected, actual); - } - - @Test - void givenNegative3inPower4AndPositive3InPower4_whenRunAndCompare_thenEqual() { - final int num1 = -3; - final int num2 = 3; - final int power = 4; - - assertEquals(new PowerRecursion(num1, power).run(), new PowerRecursion(num2, power).run()); - } - - @Test() - void givenNegativePower_whenRun_thenThrowException() { - final int num = 7; - final int power = -8; - - assertThrows(IllegalArgumentException.class, () -> new PowerRecursion(num, power).run()); - - } -} From dd780163d36d6a0c34fc305ec5d0f9c553af50dd Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Mon, 6 Sep 2021 15:45:24 +0300 Subject: [PATCH 23/33] HW5 custom regex matcher done --- README.md | 5 ++- .../CustomRegexMatcher.java | 39 ++++++++++++++++++ .../homework_5/custom_regex_matcher/Main.java | 8 ++++ .../homework_5/CustomRegexMatcherTest.java | 40 +++++++++++++++++++ 4 files changed, 90 insertions(+), 2 deletions(-) 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/CustomRegexMatcherTest.java diff --git a/README.md b/README.md index e9838c56..7cd81a53 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,13 @@ | HW 4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_file_reader) | Class with three read-from-file approaches implementations: BufferedReader, NIO, Scanner | | HW 4.2 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/singleton) | Singleton pattern implementation | | HW 4.3 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_annotation) | Custom annotation and its use with class cat | -| HW 5 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5) | Power function implementation with recursion | +| HW 5.1 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5/power_of_number) | Power function implementation with recursion | +| HW 5.2 | [Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5/custom_regex_matcher) | Custom regex matcher to check passport data of Russian Federation citizen | | | | | | Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | | Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | | Tests HW 4 | [Tests for HM 4 Custom File Reader, Singleton and Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_4) | JUnit tests for apps from homework 4 | -| Tests HW 5 | [Tests for HM 5 Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_5) | JUnit tests for app from homework 5 | +| Tests HW 5 | [Tests for HM 5 Power of Number, Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_5) | JUnit tests for app from homework 5 | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) 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..43621688 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,39 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * CustomRegexMatcher + * checks Russian Federation citizen passport data + * in a current format: + * [Passport Series] [Passport Number] [Surname] [Name] [Fathers name | optional] + * + * Examples which do match: + * 9876 867576 Saltikova-Schedrina Mary-Jane Ivanovna + * 9876867576 Saltikova Mary Semenova + * 9876867576 Saltikova Mary-Jane + * 9876 867576 Saltikova-Schedrina Mary-Jane Ivanovna + * + * + * Examples which do not match: + * 9876 867576 saltikova-Schedrina Mary-jane ivanovna + * 9876 867576Schedrina MaryIvanovna + */ + + +public class CustomRegexMatcher { + private final String russianFederationPassportData = "[0-9]{4} *[0-9]{6}( +[A-Z][a-z]+(-[A-Z][a-z]+)?){2,3}"; + + public void run() { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + String input = br.readLine(); + + System.out.println(input.matches(russianFederationPassportData)); + + } catch (IOException e) { + e.printStackTrace(); + } + } +} 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/CustomRegexMatcherTest.java b/src/test/java/homework_5/CustomRegexMatcherTest.java new file mode 100644 index 00000000..39c2670d --- /dev/null +++ b/src/test/java/homework_5/CustomRegexMatcherTest.java @@ -0,0 +1,40 @@ +package homework_5; + +import base.UnitBase; +import homework_5.custom_regex_matcher.CustomRegexMatcher; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CustomRegexMatcherTest extends UnitBase { + + @Test + void givenCorrectInputs_whenRun_thenReturnTrue() { + setInput("9876 867576 Saltikova-Schedrina Mary-Jane Ivanovna"); + new CustomRegexMatcher().run(); + assertTrue(Boolean.parseBoolean(getOutputLines()[0])); + + setInput("9876867576 Saltikova Mary Semenova"); + new CustomRegexMatcher().run(); + assertTrue(Boolean.parseBoolean(getOutputLines()[1])); + + setInput("9876867576 Saltikova Mary-Jane"); + new CustomRegexMatcher().run(); + assertTrue(Boolean.parseBoolean(getOutputLines()[2])); + + setInput("9876 867576 Saltikova-Schedrina Mary-Jane Ivanovna"); + new CustomRegexMatcher().run(); + assertTrue(Boolean.parseBoolean(getOutputLines()[3])); + } + + @Test + void givenInCorrectInputs_whenRun_thenReturnTrue() { + setInput("9876 867576 saltikova-Schedrina Mary-jane ivanovna"); + new CustomRegexMatcher().run(); + assertFalse(Boolean.parseBoolean(getOutputLines()[0])); + + setInput("9876 867576Schedrina MaryIvanovna"); + new CustomRegexMatcher().run(); + assertFalse(Boolean.parseBoolean(getOutputLines()[1])); + } +} From 0240b4ae3f975b092eccc1cd977417fe054cc13a Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Tue, 14 Sep 2021 12:19:58 +0300 Subject: [PATCH 24/33] HW6 done --- README.md | 1 + build.gradle | 1 + src/main/java/homework_6/Main.java | 15 +++++++++++++++ .../homework_6/MapProblemsCollisionGenerator.java | 9 +++++++++ .../homework_6/MapProblemsMutableGenerator.java | 12 ++++++++++++ 5 files changed, 38 insertions(+) create mode 100644 src/main/java/homework_6/Main.java create mode 100644 src/main/java/homework_6/MapProblemsCollisionGenerator.java create mode 100644 src/main/java/homework_6/MapProblemsMutableGenerator.java diff --git a/README.md b/README.md index 7cd81a53..8e418782 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ | HW 4.3 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_4/custom_annotation) | Custom annotation and its use with class cat | | HW 5.1 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5/power_of_number) | Power function implementation with recursion | | HW 5.2 | [Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5/custom_regex_matcher) | Custom regex matcher to check passport data of Russian Federation citizen | +| HW 6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_6) | Map problems generators | | | | | | Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | | Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | diff --git a/build.gradle b/build.gradle index b91dc843..563d44c5 100644 --- a/build.gradle +++ b/build.gradle @@ -10,6 +10,7 @@ repositories { } dependencies { + implementation 'org.projectlombok:lombok:1.18.18' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' } diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..279aabc6 --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,15 @@ +package homework_6; + +import java.util.HashMap; + +public class Main { + public static void main(String[] args) { + HashMap myHashMap = new HashMap<>(); + MapProblemsMutableGenerator mapProblemsMutableGenerator = new MapProblemsMutableGenerator(1); + + myHashMap.put(mapProblemsMutableGenerator, "A"); + + mapProblemsMutableGenerator.setValue(2); + System.out.println(myHashMap.get(mapProblemsMutableGenerator)); + } +} diff --git a/src/main/java/homework_6/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..2f0569b8 --- /dev/null +++ b/src/main/java/homework_6/MapProblemsCollisionGenerator.java @@ -0,0 +1,9 @@ +package homework_6; + +public class MapProblemsCollisionGenerator { + + @Override + public int hashCode() { + return 0; + } +} diff --git a/src/main/java/homework_6/MapProblemsMutableGenerator.java b/src/main/java/homework_6/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..5d95196f --- /dev/null +++ b/src/main/java/homework_6/MapProblemsMutableGenerator.java @@ -0,0 +1,12 @@ +package homework_6; + +import lombok.Data; + +@Data +public class MapProblemsMutableGenerator { + int value; + + public MapProblemsMutableGenerator(int value) { + this.value = value; + } +} From 1666f8618c799ae8eac873e5154389be8dc2cb4a Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Thu, 16 Sep 2021 11:08:09 +0300 Subject: [PATCH 25/33] Course project basics, setting ships --- src/main/java/course_project/Main.java | 11 +++ .../java/course_project/sea_battle/Game.java | 67 ++++++++++++++++ .../input_readers/InputConsoleReader.java | 29 +++++++ .../input_readers/InputFileReader.java | 32 ++++++++ .../sea_battle/input_readers/InputReader.java | 40 ++++++++++ .../sea_battle/players/ComputerPlayer.java | 48 ++++++++++++ .../sea_battle/players/HumanPlayer.java | 53 +++++++++++++ .../sea_battle/players/Player.java | 42 ++++++++++ .../sea_battle/playground/CellData.java | 27 +++++++ .../sea_battle/playground/Playground.java | 77 +++++++++++++++++++ .../sea_battle/playground/PlaygroundCell.java | 22 ++++++ .../course_project/sea_battle/ships/Ship.java | 23 ++++++ .../sea_battle/ships/ShipType.java | 19 +++++ .../sea_battle/utils/RandomGenerator.java | 8 ++ .../sea_battle/utils/ShotResultCode.java | 7 ++ .../computer_ships_sets/set1.txt | 17 ++++ .../computer_ships_sets/set2.txt | 17 ++++ .../computer_ships_sets/set3.txt | 17 ++++ .../resources/course_project/sea_battle.txt | 34 ++++++++ 19 files changed, 590 insertions(+) create mode 100644 src/main/java/course_project/Main.java create mode 100644 src/main/java/course_project/sea_battle/Game.java create mode 100644 src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java create mode 100644 src/main/java/course_project/sea_battle/input_readers/InputFileReader.java create mode 100644 src/main/java/course_project/sea_battle/input_readers/InputReader.java create mode 100644 src/main/java/course_project/sea_battle/players/ComputerPlayer.java create mode 100644 src/main/java/course_project/sea_battle/players/HumanPlayer.java create mode 100644 src/main/java/course_project/sea_battle/players/Player.java create mode 100644 src/main/java/course_project/sea_battle/playground/CellData.java create mode 100644 src/main/java/course_project/sea_battle/playground/Playground.java create mode 100644 src/main/java/course_project/sea_battle/playground/PlaygroundCell.java create mode 100644 src/main/java/course_project/sea_battle/ships/Ship.java create mode 100644 src/main/java/course_project/sea_battle/ships/ShipType.java create mode 100644 src/main/java/course_project/sea_battle/utils/RandomGenerator.java create mode 100644 src/main/java/course_project/sea_battle/utils/ShotResultCode.java create mode 100644 src/main/resources/course_project/computer_ships_sets/set1.txt create mode 100644 src/main/resources/course_project/computer_ships_sets/set2.txt create mode 100644 src/main/resources/course_project/computer_ships_sets/set3.txt create mode 100644 src/main/resources/course_project/sea_battle.txt diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..939710f7 --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +import course_project.sea_battle.Game; + +import java.io.FileNotFoundException; + +public class Main { + public static void main(String[] args) throws FileNotFoundException { + new Game().play(); + } +} diff --git a/src/main/java/course_project/sea_battle/Game.java b/src/main/java/course_project/sea_battle/Game.java new file mode 100644 index 00000000..b48da4b7 --- /dev/null +++ b/src/main/java/course_project/sea_battle/Game.java @@ -0,0 +1,67 @@ +package course_project.sea_battle; + +import course_project.sea_battle.input_readers.InputConsoleReader; +import course_project.sea_battle.input_readers.InputFileReader; +import course_project.sea_battle.players.ComputerPlayer; +import course_project.sea_battle.players.HumanPlayer; +import course_project.sea_battle.players.Player; +import homework_2.WrongInputException; + +import java.io.FileNotFoundException; +import java.io.IOException; + +public class Game { + private Player player; + private Player computer; + private InputConsoleReader inputConsoleReader; + private InputFileReader inputFileReader; + + public Game() throws FileNotFoundException { + this.inputConsoleReader = new InputConsoleReader(); + this.inputFileReader = new InputFileReader(); + + this.player = new HumanPlayer(inputConsoleReader); + this.computer = new ComputerPlayer(inputFileReader); + } + + public void play() { + System.out.println("Hi there, ready to play?"); + + try { + setShips(); + printPlaygrounds(); + + } catch (IOException e) { + e.printStackTrace(); + } catch (WrongInputException e) { + System.out.println(e.getMessage()); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + try { + inputConsoleReader.close(); + inputFileReader.close(); + } catch (IOException e) { + System.out.println("IO Exception"); + } + } + } + + private void setShips() throws IOException, WrongInputException, InterruptedException { + System.out.println(player.getPlayground().toStringMine()); + player.setShips(); + + System.out.println("Setting ships for computer...\n"); + computer.setShips(); + + //imitating AI thinking while setting ships + Thread.sleep(2000); + } + + private void printPlaygrounds() { + System.out.println("Computers playground:"); + System.out.println(computer.getPlayground().toStringOthers()); + System.out.println("Your playground:"); + System.out.println(player.getPlayground().toStringMine()); + } +} diff --git a/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java b/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java new file mode 100644 index 00000000..8d159210 --- /dev/null +++ b/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java @@ -0,0 +1,29 @@ +package course_project.sea_battle.input_readers; + +import course_project.sea_battle.playground.CellData; +import homework_2.WrongInputException; + +import java.io.*; + +public class InputConsoleReader extends InputReader { + private BufferedReader br; + + public InputConsoleReader() throws FileNotFoundException { + super("Can't parse input. Please, follow the format: [char A-J]-[integer 1-10]"); + + // temporary reading user ships set from file (for quick debugging and testing) + br = new BufferedReader(new FileReader(new File("src/main/resources/course_project/sea_battle.txt"))); +// br = new BufferedReader(new InputStreamReader(System.in)); + } + + @Override + public CellData readShotData() throws WrongInputException, IOException { + String input = br.readLine(); + return parseInput(input); + } + + @Override + public void close() throws IOException { + br.close(); + } +} diff --git a/src/main/java/course_project/sea_battle/input_readers/InputFileReader.java b/src/main/java/course_project/sea_battle/input_readers/InputFileReader.java new file mode 100644 index 00000000..2e30d660 --- /dev/null +++ b/src/main/java/course_project/sea_battle/input_readers/InputFileReader.java @@ -0,0 +1,32 @@ +package course_project.sea_battle.input_readers; + +import course_project.sea_battle.playground.CellData; +import course_project.sea_battle.utils.RandomGenerator; +import homework_2.WrongInputException; + +import java.io.*; + +public class InputFileReader extends InputReader { + private final int NUMBER_OF_COMPUTER_SHIPS_SETS = 3; + private final BufferedReader br; + + public InputFileReader() throws FileNotFoundException { + super("Can't set computers ships. Check resource folder for sets text files."); + br = new BufferedReader(new FileReader("src/main/resources/course_project/computer_ships_sets/" + getFileName())); + } + + @Override + public CellData readShotData() throws WrongInputException, IOException { + String input = br.readLine(); + return parseInput(input); + } + + @Override + public void close() throws IOException { + br.close(); + } + + private String getFileName() { + return "set" + RandomGenerator.getRandomInRange(1, NUMBER_OF_COMPUTER_SHIPS_SETS) + ".txt"; + } +} diff --git a/src/main/java/course_project/sea_battle/input_readers/InputReader.java b/src/main/java/course_project/sea_battle/input_readers/InputReader.java new file mode 100644 index 00000000..c6fe2300 --- /dev/null +++ b/src/main/java/course_project/sea_battle/input_readers/InputReader.java @@ -0,0 +1,40 @@ +package course_project.sea_battle.input_readers; + +import course_project.sea_battle.playground.CellData; +import homework_2.WrongInputException; + +import java.io.IOException; + +public abstract class InputReader { + private final String ERROR_MSG; + + protected InputReader(String error_msg) { + ERROR_MSG = error_msg; + } + + public abstract void close() throws IOException; + + public abstract CellData readShotData() throws WrongInputException, IOException; + + protected CellData parseInput(String input) throws WrongInputException { + try { + String[] data = input.split("-"); + if (data.length != 2) { + throw new WrongInputException(ERROR_MSG); + } + if (data[0].length() != 1) { + throw new WrongInputException(ERROR_MSG); + } + + char line = data[0].charAt(0); + int col = Integer.parseInt(data[1]); + + if (col < 1 || col > 10) { + throw new WrongInputException(ERROR_MSG); + } + return new CellData(line, col); + } catch (NumberFormatException e) { + throw new WrongInputException(ERROR_MSG); + } + } +} diff --git a/src/main/java/course_project/sea_battle/players/ComputerPlayer.java b/src/main/java/course_project/sea_battle/players/ComputerPlayer.java new file mode 100644 index 00000000..82afc643 --- /dev/null +++ b/src/main/java/course_project/sea_battle/players/ComputerPlayer.java @@ -0,0 +1,48 @@ +package course_project.sea_battle.players; + +import course_project.sea_battle.input_readers.InputFileReader; +import course_project.sea_battle.playground.CellData; +import course_project.sea_battle.playground.Playground; +import course_project.sea_battle.ships.Ship; +import course_project.sea_battle.ships.ShipType; +import course_project.sea_battle.utils.ShotResultCode; +import homework_2.WrongInputException; +import lombok.Getter; + +import java.io.IOException; + +@Getter +public class ComputerPlayer extends Player { + + private final Playground playground; + + public ComputerPlayer(InputFileReader inputReader) { + super(inputReader); + this.playground = new Playground(); + } + + @Override + public void setShips() throws IOException, WrongInputException { + final int SHIP_AMOUNT = 5; + Ship[] ships = new Ship[SHIP_AMOUNT]; + + for (int i = 0; i < SHIP_AMOUNT; i++) { + ships[i] = new Ship(ShipType.values()[i]); + new Helper().setShip(ships[i]); + } + } + + @Override + CellData makeMove() { + // somehow figure next move data + // randomly or need to apply some algorithm + //.. + + return new CellData('J', 3); + } + + @Override + ShotResultCode checkOwnField(CellData cellData) { + return ShotResultCode.MISS; + } +} diff --git a/src/main/java/course_project/sea_battle/players/HumanPlayer.java b/src/main/java/course_project/sea_battle/players/HumanPlayer.java new file mode 100644 index 00000000..3fec7be8 --- /dev/null +++ b/src/main/java/course_project/sea_battle/players/HumanPlayer.java @@ -0,0 +1,53 @@ +package course_project.sea_battle.players; + +import course_project.sea_battle.input_readers.InputConsoleReader; +import course_project.sea_battle.playground.CellData; +import course_project.sea_battle.playground.Playground; +import course_project.sea_battle.ships.Ship; +import course_project.sea_battle.ships.ShipType; +import course_project.sea_battle.utils.ShotResultCode; +import homework_2.WrongInputException; +import lombok.Getter; + +import java.io.IOException; + +@Getter +public class HumanPlayer extends Player { + private Playground playground; + + public HumanPlayer(InputConsoleReader inputReader) { + super(inputReader); + this.playground = new Playground(); + } + + @Override + public void setShips() throws IOException, WrongInputException { + final int SHIP_AMOUNT = 5; + Ship[] ships = new Ship[SHIP_AMOUNT]; + + for (int i = 0; i < SHIP_AMOUNT; i++) { + ships[i] = new Ship(ShipType.values()[i]); + System.out.println("Let's set " + ships[i].getShipType().name() + " (" + ships[i].getShipType().getLength() + " cells):"); + new Helper().setShip(ships[i]); + System.out.println("Ship " + ships[i].getShipType().name() + " set successfully!"); + System.out.println(playground.toStringMine()); + } + } + + @Override + CellData makeMove() { + //read the console + //.. + + //return ShotData + return new CellData('A', 4); + } + + @Override + ShotResultCode checkOwnField(CellData cellData) { + //somehow use playground + //.. + + return ShotResultCode.MISS; + } +} diff --git a/src/main/java/course_project/sea_battle/players/Player.java b/src/main/java/course_project/sea_battle/players/Player.java new file mode 100644 index 00000000..450d115b --- /dev/null +++ b/src/main/java/course_project/sea_battle/players/Player.java @@ -0,0 +1,42 @@ +package course_project.sea_battle.players; + +import course_project.sea_battle.playground.CellData; +import course_project.sea_battle.ships.Ship; +import course_project.sea_battle.utils.ShotResultCode; +import course_project.sea_battle.input_readers.InputReader; +import course_project.sea_battle.playground.Playground; +import course_project.sea_battle.playground.PlaygroundCell; +import homework_2.WrongInputException; +import lombok.Getter; + + +import java.io.IOException; + +@Getter +public abstract class Player { + private Playground playground; + private InputReader inputReader; + + public Player(InputReader inputReader) { + this.inputReader = inputReader; + } + + public abstract void setShips() throws IOException, WrongInputException; + + abstract CellData makeMove(); + + abstract ShotResultCode checkOwnField(CellData cellData); + + class Helper { + + void setShip(Ship ship) throws IOException, WrongInputException { + for (int i = 0; i < ship.getShipType().getLength(); i++) { + CellData data = inputReader.readShotData(); + //TODO: check if the cells are together + PlaygroundCell currentCell = getPlayground().getCell(data); + currentCell.setOccupied(true); + currentCell.setShip(ship); + } + } + } +} diff --git a/src/main/java/course_project/sea_battle/playground/CellData.java b/src/main/java/course_project/sea_battle/playground/CellData.java new file mode 100644 index 00000000..61d1ad34 --- /dev/null +++ b/src/main/java/course_project/sea_battle/playground/CellData.java @@ -0,0 +1,27 @@ +package course_project.sea_battle.playground; + +import course_project.sea_battle.utils.RandomGenerator; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class CellData { + private char line; + private int col; + private int row; + + public CellData(char line, int col) { + this.line = line; + this.col = col; + this.row = line - 65; + } + + public CellData generateCellData() { + return new CellData((char) (getRandomPosition() + 65), getRandomPosition() + 1); + } + + private int getRandomPosition() { + return RandomGenerator.getRandomInRange(Playground.getFieldSize() - 1, 0); + } +} diff --git a/src/main/java/course_project/sea_battle/playground/Playground.java b/src/main/java/course_project/sea_battle/playground/Playground.java new file mode 100644 index 00000000..1ff9b61f --- /dev/null +++ b/src/main/java/course_project/sea_battle/playground/Playground.java @@ -0,0 +1,77 @@ +package course_project.sea_battle.playground; + +import lombok.Getter; + +@Getter +public class Playground { + static final int FIELD_SIZE = 10; + final private PlaygroundCell[][] cells; + + public Playground () { + cells = new PlaygroundCell[FIELD_SIZE][FIELD_SIZE]; + + for (int i = 0; i < FIELD_SIZE; i++) { + for (int j = 0; j < FIELD_SIZE; j++) { + cells[i][j] = new PlaygroundCell(); + } + } + } + + public PlaygroundCell getCell(CellData data) { + return cells[data.getRow()][data.getCol() - 1]; + } + + public static int getFieldSize() { + return FIELD_SIZE; + } + + public String toStringMine() { + return toStringBoth(true); + } + + public String toStringOthers() { + return toStringBoth(false); + } + + public String toStringBoth(boolean isMine) { + final String INIT_SYMBOL = "-"; + final String MISSED_SYMBOL = "_"; + final String HIT_SYMBOL = "x"; + final String KILLED_SYMBOL = "X"; + + final String OCCUPIED_SYMBOL = isMine ? "#" : INIT_SYMBOL; + + StringBuilder stringBuilder = new StringBuilder("\n "); + for (int i = 0; i < FIELD_SIZE; i++) { + stringBuilder.append(i + 1).append(" "); + } + stringBuilder.append("\n"); + + for (int i = 0; i < FIELD_SIZE; i++) { + stringBuilder.append((char) (i + 'A')).append(" "); + for (int j = 0; j < FIELD_SIZE; j++) { + PlaygroundCell currentCell = cells[i][j]; + if (currentCell.isHit()) { + if (currentCell.getShip().isKilled()) { + stringBuilder.append(KILLED_SYMBOL).append(" "); + } else { + stringBuilder.append(HIT_SYMBOL).append(" "); + } + } else { + if (currentCell.isMissed()) { + stringBuilder.append(MISSED_SYMBOL).append(" "); + } else { + if (currentCell.isOccupied()) { + stringBuilder.append(OCCUPIED_SYMBOL).append(" "); + } else { + stringBuilder.append(INIT_SYMBOL).append(" "); + } + } + } + } + stringBuilder.append("\n"); + } + + return stringBuilder.toString(); + } +} diff --git a/src/main/java/course_project/sea_battle/playground/PlaygroundCell.java b/src/main/java/course_project/sea_battle/playground/PlaygroundCell.java new file mode 100644 index 00000000..8fd40491 --- /dev/null +++ b/src/main/java/course_project/sea_battle/playground/PlaygroundCell.java @@ -0,0 +1,22 @@ +package course_project.sea_battle.playground; + +import course_project.sea_battle.ships.Ship; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class PlaygroundCell { + private boolean isOccupied; + private boolean isHit; + private boolean isMissed; + + private Ship ship; + + public PlaygroundCell() { + this.isOccupied = false; + this.isHit = false; + this.isMissed = false; + this.ship = null; + } +} diff --git a/src/main/java/course_project/sea_battle/ships/Ship.java b/src/main/java/course_project/sea_battle/ships/Ship.java new file mode 100644 index 00000000..b5f24d55 --- /dev/null +++ b/src/main/java/course_project/sea_battle/ships/Ship.java @@ -0,0 +1,23 @@ +package course_project.sea_battle.ships; + +public class Ship { + private ShipType shipType; + private boolean isKilled; + + public boolean isKilled() { + return isKilled; + } + + public void setKilled(boolean killed) { + isKilled = killed; + } + + public Ship(ShipType shipType) { + this.shipType = shipType; + this.isKilled = false; + } + + public ShipType getShipType() { + return shipType; + } +} diff --git a/src/main/java/course_project/sea_battle/ships/ShipType.java b/src/main/java/course_project/sea_battle/ships/ShipType.java new file mode 100644 index 00000000..6dff79ab --- /dev/null +++ b/src/main/java/course_project/sea_battle/ships/ShipType.java @@ -0,0 +1,19 @@ +package course_project.sea_battle.ships; + +public enum ShipType { + CARRIER(5), + BATTLESHIP(4), + CRUISER(3), + SUBMARINE(3), + DESTROYER(2); + + private int length; + + ShipType(int length) { + this.length = length; + } + + public int getLength() { + return length; + } +} diff --git a/src/main/java/course_project/sea_battle/utils/RandomGenerator.java b/src/main/java/course_project/sea_battle/utils/RandomGenerator.java new file mode 100644 index 00000000..86f8d5f7 --- /dev/null +++ b/src/main/java/course_project/sea_battle/utils/RandomGenerator.java @@ -0,0 +1,8 @@ +package course_project.sea_battle.utils; + +public class RandomGenerator { + + public static int getRandomInRange(int max, int min) { + return (int) ((Math.random() * (max - min - 1)) + min + 1); + } +} diff --git a/src/main/java/course_project/sea_battle/utils/ShotResultCode.java b/src/main/java/course_project/sea_battle/utils/ShotResultCode.java new file mode 100644 index 00000000..93245940 --- /dev/null +++ b/src/main/java/course_project/sea_battle/utils/ShotResultCode.java @@ -0,0 +1,7 @@ +package course_project.sea_battle.utils; + +public enum ShotResultCode { + MISS, + HIT, + KILL +} diff --git a/src/main/resources/course_project/computer_ships_sets/set1.txt b/src/main/resources/course_project/computer_ships_sets/set1.txt new file mode 100644 index 00000000..d4984ee7 --- /dev/null +++ b/src/main/resources/course_project/computer_ships_sets/set1.txt @@ -0,0 +1,17 @@ +B-2 +B-3 +B-4 +B-5 +B-6 +D-2 +D-3 +D-4 +D-5 +F-2 +F-3 +F-4 +B-8 +B-9 +B-10 +J-4 +J-3 \ No newline at end of file diff --git a/src/main/resources/course_project/computer_ships_sets/set2.txt b/src/main/resources/course_project/computer_ships_sets/set2.txt new file mode 100644 index 00000000..2cb6c85c --- /dev/null +++ b/src/main/resources/course_project/computer_ships_sets/set2.txt @@ -0,0 +1,17 @@ +A-2 +A-3 +A-4 +A-5 +A-6 +D-4 +D-5 +D-6 +D-7 +F-2 +F-3 +F-4 +B-8 +B-9 +B-10 +J-4 +J-5 \ No newline at end of file diff --git a/src/main/resources/course_project/computer_ships_sets/set3.txt b/src/main/resources/course_project/computer_ships_sets/set3.txt new file mode 100644 index 00000000..5558a59e --- /dev/null +++ b/src/main/resources/course_project/computer_ships_sets/set3.txt @@ -0,0 +1,17 @@ +A-1 +B-1 +C-1 +D-1 +E-1 +C-4 +C-5 +C-6 +C-7 +F-7 +G-7 +H-7 +I-2 +I-3 +I-4 +A-7 +A-8 \ No newline at end of file diff --git a/src/main/resources/course_project/sea_battle.txt b/src/main/resources/course_project/sea_battle.txt new file mode 100644 index 00000000..2205aa58 --- /dev/null +++ b/src/main/resources/course_project/sea_battle.txt @@ -0,0 +1,34 @@ +B-2 +B-3 +B-4 +B-5 +B-6 +D-2 +D-3 +D-4 +D-5 +F-2 +F-3 +F-4 +B-8 +B-9 +B-10 +J-4 +J-5 +B-2 +B-3 +B-4 +B-5 +B-6 +D-2 +D-3 +D-4 +D-5 +F-2 +F-3 +F-4 +B-8 +B-9 +B-10 +J-4 +J-3 \ No newline at end of file From 4f9da660e3e4a306e8690f3c26ef6be4a2d24f22 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Thu, 16 Sep 2021 16:29:52 +0300 Subject: [PATCH 26/33] main functionality implemented --- .../java/course_project/sea_battle/Game.java | 37 ++++----- .../course_project/sea_battle/Gameplay.java | 77 +++++++++++++++++++ .../input_readers/InputConsoleReader.java | 4 +- .../sea_battle/players/ComputerPlayer.java | 23 +++--- .../sea_battle/players/HumanPlayer.java | 25 +++--- .../sea_battle/players/Player.java | 27 ++++++- .../sea_battle/playground/CellData.java | 15 +++- .../sea_battle/playground/CellStatus.java | 9 +++ .../sea_battle/playground/Playground.java | 44 +++++++---- .../sea_battle/playground/PlaygroundCell.java | 22 ++++-- .../course_project/sea_battle/ships/Ship.java | 39 +++++++--- 11 files changed, 235 insertions(+), 87 deletions(-) create mode 100644 src/main/java/course_project/sea_battle/Gameplay.java create mode 100644 src/main/java/course_project/sea_battle/playground/CellStatus.java diff --git a/src/main/java/course_project/sea_battle/Game.java b/src/main/java/course_project/sea_battle/Game.java index b48da4b7..4d27af86 100644 --- a/src/main/java/course_project/sea_battle/Game.java +++ b/src/main/java/course_project/sea_battle/Game.java @@ -11,10 +11,10 @@ import java.io.IOException; public class Game { - private Player player; - private Player computer; - private InputConsoleReader inputConsoleReader; - private InputFileReader inputFileReader; + private final Player player; + private final Player computer; + private final InputConsoleReader inputConsoleReader; + private final InputFileReader inputFileReader; public Game() throws FileNotFoundException { this.inputConsoleReader = new InputConsoleReader(); @@ -26,16 +26,23 @@ public Game() throws FileNotFoundException { public void play() { System.out.println("Hi there, ready to play?"); + Player winner; try { - setShips(); - printPlaygrounds(); + Gameplay gameplay = new Gameplay(player, computer); + gameplay.setShips(); + + gameplay.printPlaygrounds(); + + winner = gameplay.getWinner(); + gameplay.printCongratsToWinner(winner); } catch (IOException e) { e.printStackTrace(); } catch (WrongInputException e) { System.out.println(e.getMessage()); } catch (InterruptedException e) { + //TODO: exception handling (everywhere) e.printStackTrace(); } finally { try { @@ -46,22 +53,4 @@ public void play() { } } } - - private void setShips() throws IOException, WrongInputException, InterruptedException { - System.out.println(player.getPlayground().toStringMine()); - player.setShips(); - - System.out.println("Setting ships for computer...\n"); - computer.setShips(); - - //imitating AI thinking while setting ships - Thread.sleep(2000); - } - - private void printPlaygrounds() { - System.out.println("Computers playground:"); - System.out.println(computer.getPlayground().toStringOthers()); - System.out.println("Your playground:"); - System.out.println(player.getPlayground().toStringMine()); - } } diff --git a/src/main/java/course_project/sea_battle/Gameplay.java b/src/main/java/course_project/sea_battle/Gameplay.java new file mode 100644 index 00000000..244fa057 --- /dev/null +++ b/src/main/java/course_project/sea_battle/Gameplay.java @@ -0,0 +1,77 @@ +package course_project.sea_battle; + +import course_project.sea_battle.players.ComputerPlayer; +import course_project.sea_battle.players.Player; +import course_project.sea_battle.playground.CellData; +import course_project.sea_battle.utils.ShotResultCode; +import homework_2.WrongInputException; + +import java.io.IOException; + +public class Gameplay { + private final Player player; + private final Player computer; + + public Gameplay(Player player, Player computer) { + this.player = player; + this.computer = computer; + } + + public void setShips() throws IOException, WrongInputException, InterruptedException { + System.out.println(player.getPlayground().toStringMine()); + player.setShips(); + + System.out.println("Setting ships for computer...\n"); + computer.setShips(); + + //imitating AI thinking while setting ships + Thread.sleep(2000); + } + + public void printPlaygrounds() { + System.out.println("Computer's playground:"); + System.out.println(computer.getPlayground().toStringOthers()); + System.out.println("Your playground:"); + System.out.println(player.getPlayground().toStringMine()); + } + + public Player getWinner() throws IOException, WrongInputException { + while (true) { + makeMove(player, computer); + if (computer.isLoser()) { + return player; + } + + makeMove(computer, player); + + if (player.isLoser()) { + return computer; + } + } + } + + private void makeMove(Player p1, Player p2) throws IOException, WrongInputException { + while (true) { + System.out.println("\n======= " + p1.toStringWhose() + " MOVE ======="); + + CellData cellData = p1.makeMove(); + ShotResultCode code = p2.checkOwnField(cellData); + + printPlaygrounds(); + if (p1 instanceof ComputerPlayer) { + System.out.println("Computer made a move: " + cellData); + } + System.out.println(code); + + if (code == ShotResultCode.MISS || p2.isLoser()) { + break; + } + } + } + + public void printCongratsToWinner(Player winner) { + System.out.println("\n\n********************"); + System.out.println(" " + winner + " WIN!"); + System.out.println("********************"); + } +} diff --git a/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java b/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java index 8d159210..be5686d0 100644 --- a/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java +++ b/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java @@ -12,8 +12,8 @@ public InputConsoleReader() throws FileNotFoundException { super("Can't parse input. Please, follow the format: [char A-J]-[integer 1-10]"); // temporary reading user ships set from file (for quick debugging and testing) - br = new BufferedReader(new FileReader(new File("src/main/resources/course_project/sea_battle.txt"))); -// br = new BufferedReader(new InputStreamReader(System.in)); +// br = new BufferedReader(new FileReader(new File("src/main/resources/course_project/sea_battle.txt"))); + br = new BufferedReader(new InputStreamReader(System.in)); } @Override diff --git a/src/main/java/course_project/sea_battle/players/ComputerPlayer.java b/src/main/java/course_project/sea_battle/players/ComputerPlayer.java index 82afc643..1d7622d3 100644 --- a/src/main/java/course_project/sea_battle/players/ComputerPlayer.java +++ b/src/main/java/course_project/sea_battle/players/ComputerPlayer.java @@ -5,7 +5,6 @@ import course_project.sea_battle.playground.Playground; import course_project.sea_battle.ships.Ship; import course_project.sea_battle.ships.ShipType; -import course_project.sea_battle.utils.ShotResultCode; import homework_2.WrongInputException; import lombok.Getter; @@ -27,22 +26,26 @@ public void setShips() throws IOException, WrongInputException { Ship[] ships = new Ship[SHIP_AMOUNT]; for (int i = 0; i < SHIP_AMOUNT; i++) { - ships[i] = new Ship(ShipType.values()[i]); + ships[i] = new Ship(ShipType.values()[i], playground); new Helper().setShip(ships[i]); } } @Override - CellData makeMove() { - // somehow figure next move data - // randomly or need to apply some algorithm - //.. - - return new CellData('J', 3); + public CellData makeMove() { + // TODO: might be some more complex logic + // check if it is hit or missed at least + CellData cellData = CellData.generateCellData(); + return cellData; +// return RandomGenerator.getRandomCellData(); } @Override - ShotResultCode checkOwnField(CellData cellData) { - return ShotResultCode.MISS; + public String toString() { + return "COMPUTER"; + } + + public String toStringWhose() { + return "COMPUTER'S"; } } diff --git a/src/main/java/course_project/sea_battle/players/HumanPlayer.java b/src/main/java/course_project/sea_battle/players/HumanPlayer.java index 3fec7be8..c8e10395 100644 --- a/src/main/java/course_project/sea_battle/players/HumanPlayer.java +++ b/src/main/java/course_project/sea_battle/players/HumanPlayer.java @@ -5,7 +5,6 @@ import course_project.sea_battle.playground.Playground; import course_project.sea_battle.ships.Ship; import course_project.sea_battle.ships.ShipType; -import course_project.sea_battle.utils.ShotResultCode; import homework_2.WrongInputException; import lombok.Getter; @@ -22,11 +21,10 @@ public HumanPlayer(InputConsoleReader inputReader) { @Override public void setShips() throws IOException, WrongInputException { - final int SHIP_AMOUNT = 5; - Ship[] ships = new Ship[SHIP_AMOUNT]; + Ship[] ships = new Ship[Playground.getShipAmount()]; - for (int i = 0; i < SHIP_AMOUNT; i++) { - ships[i] = new Ship(ShipType.values()[i]); + for (int i = 0; i < Playground.getShipAmount(); i++) { + ships[i] = new Ship(ShipType.values()[i], playground); System.out.println("Let's set " + ships[i].getShipType().name() + " (" + ships[i].getShipType().getLength() + " cells):"); new Helper().setShip(ships[i]); System.out.println("Ship " + ships[i].getShipType().name() + " set successfully!"); @@ -35,19 +33,16 @@ public void setShips() throws IOException, WrongInputException { } @Override - CellData makeMove() { - //read the console - //.. - - //return ShotData - return new CellData('A', 4); + public CellData makeMove() throws IOException, WrongInputException { + return getInputReader().readShotData(); } @Override - ShotResultCode checkOwnField(CellData cellData) { - //somehow use playground - //.. + public String toString() { + return "YOU"; + } - return ShotResultCode.MISS; + public String toStringWhose() { + return "YOUR"; } } diff --git a/src/main/java/course_project/sea_battle/players/Player.java b/src/main/java/course_project/sea_battle/players/Player.java index 450d115b..2fccfb5e 100644 --- a/src/main/java/course_project/sea_battle/players/Player.java +++ b/src/main/java/course_project/sea_battle/players/Player.java @@ -1,6 +1,7 @@ package course_project.sea_battle.players; import course_project.sea_battle.playground.CellData; +import course_project.sea_battle.playground.CellStatus; import course_project.sea_battle.ships.Ship; import course_project.sea_battle.utils.ShotResultCode; import course_project.sea_battle.input_readers.InputReader; @@ -23,9 +24,28 @@ public Player(InputReader inputReader) { public abstract void setShips() throws IOException, WrongInputException; - abstract CellData makeMove(); + public abstract CellData makeMove() throws IOException, WrongInputException; - abstract ShotResultCode checkOwnField(CellData cellData); + public ShotResultCode checkOwnField(CellData cellData) { + PlaygroundCell cell = getPlayground().getCell(cellData); + + if (cell.getStatus() == CellStatus.OCCUPIED) { + cell.setHit(); + + if (cell.getStatus() == CellStatus.KILLED) { + return ShotResultCode.KILL; + } + return ShotResultCode.HIT; + } + cell.setStatus(CellStatus.MISSED); + return ShotResultCode.MISS; + } + + public boolean isLoser() { + return getPlayground().getKilledShips() == Playground.getShipAmount(); + } + + public abstract String toStringWhose(); class Helper { @@ -34,8 +54,9 @@ void setShip(Ship ship) throws IOException, WrongInputException { CellData data = inputReader.readShotData(); //TODO: check if the cells are together PlaygroundCell currentCell = getPlayground().getCell(data); - currentCell.setOccupied(true); + currentCell.setStatus(CellStatus.OCCUPIED); currentCell.setShip(ship); + ship.setCell(data); } } } diff --git a/src/main/java/course_project/sea_battle/playground/CellData.java b/src/main/java/course_project/sea_battle/playground/CellData.java index 61d1ad34..b6c5164f 100644 --- a/src/main/java/course_project/sea_battle/playground/CellData.java +++ b/src/main/java/course_project/sea_battle/playground/CellData.java @@ -17,11 +17,22 @@ public CellData(char line, int col) { this.row = line - 65; } - public CellData generateCellData() { + public CellData(int row, int col) { + this.row = row - 1; + this.col = col; + this.line = (char) (row + 65 - 1); + } + + public static CellData generateCellData() { return new CellData((char) (getRandomPosition() + 65), getRandomPosition() + 1); } - private int getRandomPosition() { + private static int getRandomPosition() { return RandomGenerator.getRandomInRange(Playground.getFieldSize() - 1, 0); } + + @Override + public String toString() { + return line + "-" + col; + } } diff --git a/src/main/java/course_project/sea_battle/playground/CellStatus.java b/src/main/java/course_project/sea_battle/playground/CellStatus.java new file mode 100644 index 00000000..539ab758 --- /dev/null +++ b/src/main/java/course_project/sea_battle/playground/CellStatus.java @@ -0,0 +1,9 @@ +package course_project.sea_battle.playground; + +public enum CellStatus { + FREE, + OCCUPIED, + MISSED, + HIT, + KILLED +} diff --git a/src/main/java/course_project/sea_battle/playground/Playground.java b/src/main/java/course_project/sea_battle/playground/Playground.java index 1ff9b61f..abfdc7ee 100644 --- a/src/main/java/course_project/sea_battle/playground/Playground.java +++ b/src/main/java/course_project/sea_battle/playground/Playground.java @@ -5,7 +5,10 @@ @Getter public class Playground { static final int FIELD_SIZE = 10; + static final int SHIP_AMOUNT = 5; + final private PlaygroundCell[][] cells; + private int killedShips; public Playground () { cells = new PlaygroundCell[FIELD_SIZE][FIELD_SIZE]; @@ -15,6 +18,8 @@ public Playground () { cells[i][j] = new PlaygroundCell(); } } + + killedShips = 0; } public PlaygroundCell getCell(CellData data) { @@ -25,6 +30,14 @@ public static int getFieldSize() { return FIELD_SIZE; } + public static int getShipAmount() { + return SHIP_AMOUNT; + } + + public void killShip() { + killedShips++; + } + public String toStringMine() { return toStringBoth(true); } @@ -35,7 +48,7 @@ public String toStringOthers() { public String toStringBoth(boolean isMine) { final String INIT_SYMBOL = "-"; - final String MISSED_SYMBOL = "_"; + final String MISSED_SYMBOL = " "; final String HIT_SYMBOL = "x"; final String KILLED_SYMBOL = "X"; @@ -51,22 +64,23 @@ public String toStringBoth(boolean isMine) { stringBuilder.append((char) (i + 'A')).append(" "); for (int j = 0; j < FIELD_SIZE; j++) { PlaygroundCell currentCell = cells[i][j]; - if (currentCell.isHit()) { - if (currentCell.getShip().isKilled()) { - stringBuilder.append(KILLED_SYMBOL).append(" "); - } else { + + switch(currentCell.getStatus()) { + case HIT: stringBuilder.append(HIT_SYMBOL).append(" "); - } - } else { - if (currentCell.isMissed()) { + break; + case KILLED: + stringBuilder.append(KILLED_SYMBOL).append(" "); + break; + case MISSED: stringBuilder.append(MISSED_SYMBOL).append(" "); - } else { - if (currentCell.isOccupied()) { - stringBuilder.append(OCCUPIED_SYMBOL).append(" "); - } else { - stringBuilder.append(INIT_SYMBOL).append(" "); - } - } + break; + case OCCUPIED: + stringBuilder.append(OCCUPIED_SYMBOL).append(" "); + break; + default: + stringBuilder.append(INIT_SYMBOL).append(" "); + } } stringBuilder.append("\n"); diff --git a/src/main/java/course_project/sea_battle/playground/PlaygroundCell.java b/src/main/java/course_project/sea_battle/playground/PlaygroundCell.java index 8fd40491..8f2e52a9 100644 --- a/src/main/java/course_project/sea_battle/playground/PlaygroundCell.java +++ b/src/main/java/course_project/sea_battle/playground/PlaygroundCell.java @@ -4,19 +4,27 @@ import lombok.Getter; import lombok.Setter; -@Setter @Getter +@Setter public class PlaygroundCell { - private boolean isOccupied; - private boolean isHit; - private boolean isMissed; + private CellStatus status; private Ship ship; + public void setHit() { + if (status == CellStatus.HIT) { + return; + } + setStatus(CellStatus.HIT); + ship.hit(); + if (ship.isKilled()) { + status = CellStatus.KILLED; + } + } + public PlaygroundCell() { - this.isOccupied = false; - this.isHit = false; - this.isMissed = false; + status = CellStatus.FREE; + this.ship = null; } } diff --git a/src/main/java/course_project/sea_battle/ships/Ship.java b/src/main/java/course_project/sea_battle/ships/Ship.java index b5f24d55..4688a683 100644 --- a/src/main/java/course_project/sea_battle/ships/Ship.java +++ b/src/main/java/course_project/sea_battle/ships/Ship.java @@ -1,23 +1,44 @@ package course_project.sea_battle.ships; +import course_project.sea_battle.playground.CellData; +import course_project.sea_battle.playground.CellStatus; +import course_project.sea_battle.playground.Playground; +import lombok.Getter; + +import java.util.ArrayList; + +@Getter public class Ship { private ShipType shipType; private boolean isKilled; + private int length; + private int hitCells; + private ArrayList cells; + private Playground playground; - public boolean isKilled() { - return isKilled; + public Ship(ShipType shipType, Playground playground) { + this.shipType = shipType; + this.isKilled = false; + this.length = shipType.getLength(); + this.hitCells = 0; + cells = new ArrayList<>(length); + this.playground = playground; } - public void setKilled(boolean killed) { - isKilled = killed; + public void hit() { + hitCells++; + if (hitCells == length) { + kill(); + } } - public Ship(ShipType shipType) { - this.shipType = shipType; - this.isKilled = false; + public void setCell(CellData cellData) { + cells.add(cellData); } - public ShipType getShipType() { - return shipType; + private void kill() { + isKilled = true; + cells.forEach(cellData -> playground.getCell(cellData).setStatus(CellStatus.KILLED)); + playground.killShip(); } } From 1653fe4f504d8efd5df142f201404fbfab96c7bd Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 22 Sep 2021 12:36:20 +0300 Subject: [PATCH 27/33] HW 7 done --- README.md | 2 + src/main/java/homework_7/Cat.java | 30 ++++++++++++++ src/main/java/homework_7/Kitten.java | 19 +++++++++ src/main/java/homework_7/Main.java | 17 ++++++++ src/test/java/homework_7/BritishKitten.java | 11 +++++ src/test/java/homework_7/KittenToCatTest.java | 40 +++++++++++++++++++ 6 files changed, 119 insertions(+) create mode 100644 src/main/java/homework_7/Cat.java create mode 100644 src/main/java/homework_7/Kitten.java create mode 100644 src/main/java/homework_7/Main.java create mode 100644 src/test/java/homework_7/BritishKitten.java create mode 100644 src/test/java/homework_7/KittenToCatTest.java diff --git a/README.md b/README.md index 8e418782..d111eb56 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,13 @@ | HW 5.1 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5/power_of_number) | Power function implementation with recursion | | HW 5.2 | [Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5/custom_regex_matcher) | Custom regex matcher to check passport data of Russian Federation citizen | | HW 6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_6) | Map problems generators | +| HW 7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_7) | KittenToCat Functional Interface | | | | | | Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | | Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | | Tests HW 4 | [Tests for HM 4 Custom File Reader, Singleton and Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_4) | JUnit tests for apps from homework 4 | | Tests HW 5 | [Tests for HM 5 Power of Number, Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_5) | JUnit tests for app from homework 5 | +| Tests HW 7 | [Tests for HM 7 KittenToCat](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_7) | JUnit tests for app from homework 7 | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..43036cc4 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,30 @@ +package homework_7; + +import java.awt.*; + +public class Cat { + String name; + int age; + Color color; + String grownsOnlyCollar; + + public Cat(String name, int age, Color color, String grownsOnlyCollar) { + this.name = name; + this.age = age; + this.color = color; + this.grownsOnlyCollar = grownsOnlyCollar; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + ", color=" + color + + ", grownsOnlyCollar='" + grownsOnlyCollar + '\'' + + '}'; + } +} + + + diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..6be55e03 --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,19 @@ +package homework_7; + +import java.awt.*; + +public class Kitten { + String cuteName; + String fullName; + int age; + Color color; + String littleCollar; + + public Kitten(String cuteName, String fullname, int age, Color color, String littleCollar) { + this.cuteName = cuteName; + this.fullName = fullname; + this.age = age; + this.color = color; + this.littleCollar = littleCollar; + } +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..a1648453 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,17 @@ +package homework_7; + +import java.awt.*; + +public class Main { + + public static void main(String[] args) { + Kitten kitty = new Kitten("Vasilek", "Vasilii", 1, Color.RED, "Tiny blue collar"); + + KittenToCatFunction kittenToCat = kitten -> + new Cat(kitten.fullName, kitten.age + 2, kitten.color, "Grown ups init collar"); + + Cat cat = kittenToCat.grow(kitty); + + System.out.println(cat); + } +} diff --git a/src/test/java/homework_7/BritishKitten.java b/src/test/java/homework_7/BritishKitten.java new file mode 100644 index 00000000..b6aa12ba --- /dev/null +++ b/src/test/java/homework_7/BritishKitten.java @@ -0,0 +1,11 @@ +package homework_7; + +import java.awt.*; + +public class BritishKitten extends Kitten { + final String breed = "British"; + + public BritishKitten(String cuteName, String fullname, int age, Color color, String littleCollar) { + super(cuteName, fullname, age, color, littleCollar); + } +} diff --git a/src/test/java/homework_7/KittenToCatTest.java b/src/test/java/homework_7/KittenToCatTest.java new file mode 100644 index 00000000..9477b871 --- /dev/null +++ b/src/test/java/homework_7/KittenToCatTest.java @@ -0,0 +1,40 @@ +package homework_7; + +import org.junit.jupiter.api.Test; + +import java.awt.*; +import static org.junit.jupiter.api.Assertions.*; + + +public class KittenToCatTest { + + @Test + void givenKitten_whenRunKittenToCatGrow_thenCorrectCat() { + Kitten k = new Kitten("Cutie", "Cutos", 2, Color.RED, "Tiny collar"); + + KittenToCatFunction kittenToCat = kitten -> new Cat(kitten.fullName, kitten.age + 1, kitten.color, "Big collar"); + + Cat cat = kittenToCat.grow(k); + + assertEquals(cat.name, "Cutos"); + assertEquals(cat.age, 3); + assertEquals(cat.color, Color.RED); + assertEquals(cat.grownsOnlyCollar, "Big collar"); + + } + + @Test + void givenKittenSubClass_whenRunKittenToCatGrow_thenCorrectCat() { + BritishKitten k = new BritishKitten("Cutie", "Cutos", 2, Color.RED, "Tiny collar"); + + KittenToCatFunction kittenToCat = kitten -> new Cat(kitten.fullName, kitten.age + 1, kitten.color, "Big collar"); + + Cat cat = kittenToCat.grow(k); + + assertEquals(cat.name, "Cutos"); + assertEquals(cat.age, 3); + assertEquals(cat.color, Color.RED); + assertEquals(cat.grownsOnlyCollar, "Big collar"); + + } +} From 1c7b4202b053512045886562cd712e032315903c Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 22 Sep 2021 15:32:32 +0300 Subject: [PATCH 28/33] HW 7 done (added forgotten file) --- src/main/java/homework_7/KittenToCatFunction.java | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/main/java/homework_7/KittenToCatFunction.java diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..c1c2204b --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,7 @@ +package homework_7; + +@FunctionalInterface +public interface KittenToCatFunction { + + Cat grow(Kitten kitten); +} From 4129cf9c69df70b1fcf20f4d67aff9b103d07f94 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 22 Sep 2021 21:42:39 +0300 Subject: [PATCH 29/33] Course Project Tests added --- build.gradle | 2 + .../java/course_project/GameplayTest.java | 85 +++++++++++++++++++ .../java/course_project/InputReadersTest.java | 38 +++++++++ src/test/java/course_project/PlayersTest.java | 31 +++++++ .../course_project/PlaygroundCellTest.java | 44 ++++++++++ .../course_project/RandomGeneratorTest.java | 17 ++++ 6 files changed, 217 insertions(+) create mode 100644 src/test/java/course_project/GameplayTest.java create mode 100644 src/test/java/course_project/InputReadersTest.java create mode 100644 src/test/java/course_project/PlayersTest.java create mode 100644 src/test/java/course_project/PlaygroundCellTest.java create mode 100644 src/test/java/course_project/RandomGeneratorTest.java diff --git a/build.gradle b/build.gradle index 563d44c5..c5cc5355 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,9 @@ repositories { dependencies { implementation 'org.projectlombok:lombok:1.18.18' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' + compileOnly 'org.projectlombok:lombok:1.18.18' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + annotationProcessor 'org.projectlombok:lombok:1.18.18' } test { diff --git a/src/test/java/course_project/GameplayTest.java b/src/test/java/course_project/GameplayTest.java new file mode 100644 index 00000000..4bd0d1e5 --- /dev/null +++ b/src/test/java/course_project/GameplayTest.java @@ -0,0 +1,85 @@ +package course_project; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class GameplayTest extends UnitBase { + + @Test + void givenPlayersShots_whenGamePlay_thenPrintUserWon() { + setInput("B-2\n" + + "B-3\n" + + "B-4\n" + + "B-5\n" + + "B-6\n" + + "D-2\n" + + "D-3\n" + + "D-4\n" + + "D-5\n" + + "F-2\n" + + "F-3\n" + + "F-4\n" + + "B-8\n" + + "B-9\n" + + "B-10\n" + + "J-4\n" + + "J-3\n" + + "B-2\n" + + "B-3\n" + + "B-4\n" + + "B-5\n" + + "B-6\n" + + "D-2\n" + + "D-3\n" + + "D-4\n" + + "D-5\n" + + "F-2\n" + + "F-3\n" + + "F-4\n" + + "B-8\n" + + "B-9\n" + + "B-10\n" + + "J-4\n" + + "J-3\n" + + "B-2\n" + + "B-3\n" + + "B-4\n" + + "B-5\n" + + "B-6\n" + + "D-2\n" + + "D-3\n" + + "D-4\n" + + "D-5\n" + + "F-2\n" + + "F-3\n" + + "F-4\n" + + "B-8\n" + + "B-9\n" + + "B-10\n" + + "J-4\n" + + "J-3\n" + + "B-2\n" + + "B-3\n" + + "B-4\n" + + "B-5\n" + + "B-6\n" + + "D-2\n" + + "D-3\n" + + "D-4\n" + + "D-5\n" + + "F-2\n" + + "F-3\n" + + "F-4\n" + + "B-8\n" + + "B-9\n" + + "B-10\n" + + "J-4\n" + + "J-3"); + + new GameLauncher().launch(); + + assertEquals(" YOU WIN!", getOutputLines()[getOutputLines().length - 2]); + } +} diff --git a/src/test/java/course_project/InputReadersTest.java b/src/test/java/course_project/InputReadersTest.java new file mode 100644 index 00000000..632c5558 --- /dev/null +++ b/src/test/java/course_project/InputReadersTest.java @@ -0,0 +1,38 @@ +package course_project; + +import base.UnitBase; +import course_project.sea_battle.input_readers.InputConsoleReader; +import course_project.sea_battle.playground.CellData; +import homework_2.WrongInputException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + + +import java.io.IOException; + +public class InputReadersTest extends UnitBase { + + @Test + void givenInputCorrect_whenRunInputRead_thenReturnCellData() throws IOException, WrongInputException { + setInput("A-4"); + + InputConsoleReader inputConsoleReader = new InputConsoleReader(); + Object result = inputConsoleReader.readShotData(); + + assertTrue(result instanceof CellData); + assertEquals(4, ((CellData) result).getCol()); + assertEquals('A', ((CellData) result).getLine()); + assertEquals(0, ((CellData) result).getRow()); + + } + + @Test + void givenInputIncorrect_whenRunInputRead_thenThrowError() { + setInput("hello"); + + InputConsoleReader inputConsoleReader = new InputConsoleReader(); + + assertThrows(WrongInputException.class, () -> inputConsoleReader.readShotData()); + } +} diff --git a/src/test/java/course_project/PlayersTest.java b/src/test/java/course_project/PlayersTest.java new file mode 100644 index 00000000..af8ce74f --- /dev/null +++ b/src/test/java/course_project/PlayersTest.java @@ -0,0 +1,31 @@ +package course_project; + +import base.UnitBase; +import course_project.sea_battle.input_readers.InputFileReader; +import course_project.sea_battle.players.ComputerPlayer; +import course_project.sea_battle.playground.CellStatus; +import homework_2.WrongInputException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.util.Arrays; + +public class PlayersTest extends UnitBase { + + @Test + void whenComputerSetsShips_thenSetCorrectNumberOfOccupiedCells() throws IOException, WrongInputException { + ComputerPlayer pc = new ComputerPlayer(new InputFileReader()); + pc.setShips(); + + long occupiedCellsCount = Arrays.stream(pc.getPlayground() + .getCells()) + .mapToLong(cells -> Arrays.stream(cells) + .filter(cell -> (cell.getStatus() == CellStatus.OCCUPIED)) + .count()) + .sum(); + + assertEquals(occupiedCellsCount, 5 + 4 + 3 * 2 + 2); + } +} diff --git a/src/test/java/course_project/PlaygroundCellTest.java b/src/test/java/course_project/PlaygroundCellTest.java new file mode 100644 index 00000000..efd57f9e --- /dev/null +++ b/src/test/java/course_project/PlaygroundCellTest.java @@ -0,0 +1,44 @@ +package course_project; + +import course_project.sea_battle.playground.CellStatus; +import course_project.sea_battle.playground.Playground; +import course_project.sea_battle.playground.PlaygroundCell; +import course_project.sea_battle.ships.Ship; +import course_project.sea_battle.ships.ShipType; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PlaygroundCellTest { + + @Test + void whenHitCell_thenStatusIsHit() { + PlaygroundCell playgroundCell = new PlaygroundCell(); + playgroundCell.setShip(new Ship(ShipType.SUBMARINE, new Playground())); + + playgroundCell.setHit(); + + assertSame(playgroundCell.getStatus(), CellStatus.HIT); + } + + @Test + void whenHitLastCellOfShip_thenStatusIsKilledBothCellAndShip() { + PlaygroundCell playgroundCell = new PlaygroundCell(); + PlaygroundCell playgroundCell1 = new PlaygroundCell(); + PlaygroundCell playgroundCell2 = new PlaygroundCell(); + + Ship ship = new Ship(ShipType.SUBMARINE, new Playground()); + playgroundCell.setShip(ship); + playgroundCell1.setShip(ship); + playgroundCell2.setShip(ship); + + playgroundCell.setHit(); + playgroundCell1.setHit(); + playgroundCell2.setHit(); + + assertSame(playgroundCell2.getStatus(), CellStatus.KILLED); + assertTrue(playgroundCell.getShip().isKilled()); + + } +} diff --git a/src/test/java/course_project/RandomGeneratorTest.java b/src/test/java/course_project/RandomGeneratorTest.java new file mode 100644 index 00000000..2045d035 --- /dev/null +++ b/src/test/java/course_project/RandomGeneratorTest.java @@ -0,0 +1,17 @@ +package course_project; + +import course_project.sea_battle.utils.RandomGenerator; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class RandomGeneratorTest { + + @Test + void whenGenerateInRange_thenCorrect() { + int random = RandomGenerator.getRandomInRange(4, 7); + + assertTrue(random >= 4 && random <= 7); + + } +} From 2a48d11414a76ac16345c576e54b023deeada3ac Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 22 Sep 2021 21:43:48 +0300 Subject: [PATCH 30/33] Course Project refactored a bit --- .../java/course_project/GameLauncher.java | 17 +++++++++++ src/main/java/course_project/Main.java | 8 ++---- .../java/course_project/sea_battle/Game.java | 17 +++++------ .../input_readers/InputConsoleReader.java | 2 +- .../sea_battle/players/HumanPlayer.java | 1 + .../sea_battle/players/Player.java | 2 +- .../computer_ships_sets/set2.txt | 28 +++++++++++++++---- .../computer_ships_sets/set3.txt | 28 +++++++++++++++---- .../resources/course_project/sea_battle.txt | 19 ++++++++++++- 9 files changed, 95 insertions(+), 27 deletions(-) create mode 100644 src/main/java/course_project/GameLauncher.java diff --git a/src/main/java/course_project/GameLauncher.java b/src/main/java/course_project/GameLauncher.java new file mode 100644 index 00000000..72453914 --- /dev/null +++ b/src/main/java/course_project/GameLauncher.java @@ -0,0 +1,17 @@ +package course_project; + +import course_project.sea_battle.Game; +import homework_2.WrongInputException; + +import java.io.IOException; + +public class GameLauncher { + + void launch() { + try { + new Game().play(); + } catch (InterruptedException | IOException | WrongInputException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java index 939710f7..b2d3f02e 100644 --- a/src/main/java/course_project/Main.java +++ b/src/main/java/course_project/Main.java @@ -1,11 +1,7 @@ package course_project; -import course_project.sea_battle.Game; - -import java.io.FileNotFoundException; - public class Main { - public static void main(String[] args) throws FileNotFoundException { - new Game().play(); + public static void main(String[] args) { + new GameLauncher().launch(); } } diff --git a/src/main/java/course_project/sea_battle/Game.java b/src/main/java/course_project/sea_battle/Game.java index 4d27af86..6a5b9dee 100644 --- a/src/main/java/course_project/sea_battle/Game.java +++ b/src/main/java/course_project/sea_battle/Game.java @@ -18,13 +18,17 @@ public class Game { public Game() throws FileNotFoundException { this.inputConsoleReader = new InputConsoleReader(); - this.inputFileReader = new InputFileReader(); + try { + this.inputFileReader = new InputFileReader(); + } catch (FileNotFoundException e) { + throw new FileNotFoundException("Input files might be damaged. Please look at resources folder"); + } this.player = new HumanPlayer(inputConsoleReader); this.computer = new ComputerPlayer(inputFileReader); } - public void play() { + public void play() throws InterruptedException, IOException, WrongInputException { System.out.println("Hi there, ready to play?"); Player winner; @@ -38,18 +42,15 @@ public void play() { gameplay.printCongratsToWinner(winner); } catch (IOException e) { - e.printStackTrace(); - } catch (WrongInputException e) { - System.out.println(e.getMessage()); + throw new IOException("Please check input files in resources folder", e); } catch (InterruptedException e) { - //TODO: exception handling (everywhere) - e.printStackTrace(); + throw new InterruptedException("Couldn't simulate computer player thinking, it got interrupted"); } finally { try { inputConsoleReader.close(); inputFileReader.close(); } catch (IOException e) { - System.out.println("IO Exception"); + throw new IOException("Couldn't manage to close resources", e); } } } diff --git a/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java b/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java index be5686d0..e0758fd1 100644 --- a/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java +++ b/src/main/java/course_project/sea_battle/input_readers/InputConsoleReader.java @@ -8,7 +8,7 @@ public class InputConsoleReader extends InputReader { private BufferedReader br; - public InputConsoleReader() throws FileNotFoundException { + public InputConsoleReader() { super("Can't parse input. Please, follow the format: [char A-J]-[integer 1-10]"); // temporary reading user ships set from file (for quick debugging and testing) diff --git a/src/main/java/course_project/sea_battle/players/HumanPlayer.java b/src/main/java/course_project/sea_battle/players/HumanPlayer.java index c8e10395..f823cfdf 100644 --- a/src/main/java/course_project/sea_battle/players/HumanPlayer.java +++ b/src/main/java/course_project/sea_battle/players/HumanPlayer.java @@ -26,6 +26,7 @@ public void setShips() throws IOException, WrongInputException { for (int i = 0; i < Playground.getShipAmount(); i++) { ships[i] = new Ship(ShipType.values()[i], playground); System.out.println("Let's set " + ships[i].getShipType().name() + " (" + ships[i].getShipType().getLength() + " cells):"); + System.out.println("e.g. A-1"); new Helper().setShip(ships[i]); System.out.println("Ship " + ships[i].getShipType().name() + " set successfully!"); System.out.println(playground.toStringMine()); diff --git a/src/main/java/course_project/sea_battle/players/Player.java b/src/main/java/course_project/sea_battle/players/Player.java index 2fccfb5e..7b751458 100644 --- a/src/main/java/course_project/sea_battle/players/Player.java +++ b/src/main/java/course_project/sea_battle/players/Player.java @@ -52,7 +52,7 @@ class Helper { void setShip(Ship ship) throws IOException, WrongInputException { for (int i = 0; i < ship.getShipType().getLength(); i++) { CellData data = inputReader.readShotData(); - //TODO: check if the cells are together + PlaygroundCell currentCell = getPlayground().getCell(data); currentCell.setStatus(CellStatus.OCCUPIED); currentCell.setShip(ship); diff --git a/src/main/resources/course_project/computer_ships_sets/set2.txt b/src/main/resources/course_project/computer_ships_sets/set2.txt index 2cb6c85c..ad3ec242 100644 --- a/src/main/resources/course_project/computer_ships_sets/set2.txt +++ b/src/main/resources/course_project/computer_ships_sets/set2.txt @@ -1,8 +1,26 @@ -A-2 -A-3 -A-4 -A-5 -A-6 +B-2 +B-3 +B-4 +B-5 +B-6 +D-2 +D-3 +D-4 +D-5 +F-2 +F-3 +F-4 +B-8 +B-9 +B-10 +J-4 +J-3 + +B-2 +B-3 +B-4 +B-5 +B-6 D-4 D-5 D-6 diff --git a/src/main/resources/course_project/computer_ships_sets/set3.txt b/src/main/resources/course_project/computer_ships_sets/set3.txt index 5558a59e..8165e29e 100644 --- a/src/main/resources/course_project/computer_ships_sets/set3.txt +++ b/src/main/resources/course_project/computer_ships_sets/set3.txt @@ -1,8 +1,26 @@ -A-1 -B-1 -C-1 -D-1 -E-1 +B-2 +B-3 +B-4 +B-5 +B-6 +D-2 +D-3 +D-4 +D-5 +F-2 +F-3 +F-4 +B-8 +B-9 +B-10 +J-4 +J-3 + +B-2 +B-3 +B-4 +B-5 +B-6 C-4 C-5 C-6 diff --git a/src/main/resources/course_project/sea_battle.txt b/src/main/resources/course_project/sea_battle.txt index 2205aa58..591c20f1 100644 --- a/src/main/resources/course_project/sea_battle.txt +++ b/src/main/resources/course_project/sea_battle.txt @@ -31,4 +31,21 @@ B-8 B-9 B-10 J-4 -J-3 \ No newline at end of file +J-3 +B-2 +B-3 +B-4 +B-5 +B-6 +D-2 +D-7 +D-4 +D-5 +F-2 +F-3 +F-4 +B-7 +B-9 +B-10 +J-4 +J-5 \ No newline at end of file From a86d72ca592107c5378c50da9af57fc06fb95b25 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 22 Sep 2021 21:53:34 +0300 Subject: [PATCH 31/33] Course Project local README.md added --- src/main/java/course_project/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/main/java/course_project/README.md diff --git a/src/main/java/course_project/README.md b/src/main/java/course_project/README.md new file mode 100644 index 00000000..aed42796 --- /dev/null +++ b/src/main/java/course_project/README.md @@ -0,0 +1,7 @@ +

Sea Battle Game

+
+ +Sea Battle Game project for Java Core June 2021. + +Please, input 'letter minus digit' without spaces for the correct cell data.
+Example of the correct input:
A-3
B-9
... \ No newline at end of file From 1844e26ba72267cff0b629c032511eb1a0650c38 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Wed, 22 Sep 2021 21:56:53 +0300 Subject: [PATCH 32/33] Course Project README.md updated --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d111eb56..6ef25c9a 100644 --- a/README.md +++ b/README.md @@ -16,12 +16,14 @@ | HW 5.2 | [Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_5/custom_regex_matcher) | Custom regex matcher to check passport data of Russian Federation citizen | | HW 6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_6) | Map problems generators | | HW 7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/homework_7) | KittenToCat Functional Interface | +| Course Project | [Sea Battle Course project](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/main/java/course_project) | Sea Battle Course Project | | | | | | Tests HM 1 | [Tests for HM 1 Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_1) | JUnit tests for console printer from homework 1 | | Tests HW 2 | [Tests for HM 2 Traffic Light, Pyramid Printer and Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_2) | JUnit tests for apps from homework 2 | | Tests HW 4 | [Tests for HM 4 Custom File Reader, Singleton and Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_4) | JUnit tests for apps from homework 4 | | Tests HW 5 | [Tests for HM 5 Power of Number, Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_5) | JUnit tests for app from homework 5 | | Tests HW 7 | [Tests for HM 7 KittenToCat](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/homework_7) | JUnit tests for app from homework 7 | +| Tests HW 7 | [Tests for course project](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/TatianaDzenzura/src/test/java/course_project) | JUnit tests for course project | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 48f105083e6c5308b64f1ec3401ff26d18dcc839 Mon Sep 17 00:00:00 2001 From: tatianadzn Date: Thu, 23 Sep 2021 13:00:05 +0300 Subject: [PATCH 33/33] Course Project ui simplified and more convenient --- .../java/course_project/sea_battle/Game.java | 18 ++++++---- .../course_project/sea_battle/Gameplay.java | 17 +++++---- .../input_readers/InputFileReader.java | 4 +-- .../sea_battle/players/HumanPlayer.java | 11 +++--- .../sea_battle/players/Player.java | 11 +++++- .../course_project/player_ships_sets/set1.txt | 17 +++++++++ .../course_project/player_ships_sets/set2.txt | 17 +++++++++ .../course_project/player_ships_sets/set3.txt | 35 +++++++++++++++++++ src/test/java/course_project/PlayersTest.java | 2 +- 9 files changed, 108 insertions(+), 24 deletions(-) create mode 100644 src/main/resources/course_project/player_ships_sets/set1.txt create mode 100644 src/main/resources/course_project/player_ships_sets/set2.txt create mode 100644 src/main/resources/course_project/player_ships_sets/set3.txt diff --git a/src/main/java/course_project/sea_battle/Game.java b/src/main/java/course_project/sea_battle/Game.java index 6a5b9dee..3eca73e0 100644 --- a/src/main/java/course_project/sea_battle/Game.java +++ b/src/main/java/course_project/sea_battle/Game.java @@ -13,19 +13,22 @@ public class Game { private final Player player; private final Player computer; + private final InputConsoleReader inputConsoleReader; - private final InputFileReader inputFileReader; + private final InputFileReader inputFileReaderComp; + private final InputFileReader inputFileReaderPlayer; public Game() throws FileNotFoundException { this.inputConsoleReader = new InputConsoleReader(); try { - this.inputFileReader = new InputFileReader(); + this.inputFileReaderComp = new InputFileReader("computer_ships_sets"); + this.inputFileReaderPlayer = new InputFileReader("computer_ships_sets"); } catch (FileNotFoundException e) { throw new FileNotFoundException("Input files might be damaged. Please look at resources folder"); } - this.player = new HumanPlayer(inputConsoleReader); - this.computer = new ComputerPlayer(inputFileReader); + this.player = new HumanPlayer(inputFileReaderPlayer, inputConsoleReader); + this.computer = new ComputerPlayer(inputFileReaderComp); } public void play() throws InterruptedException, IOException, WrongInputException { @@ -36,7 +39,7 @@ public void play() throws InterruptedException, IOException, WrongInputException Gameplay gameplay = new Gameplay(player, computer); gameplay.setShips(); - gameplay.printPlaygrounds(); +// gameplay.printPlaygrounds(); winner = gameplay.getWinner(); gameplay.printCongratsToWinner(winner); @@ -44,11 +47,12 @@ public void play() throws InterruptedException, IOException, WrongInputException } catch (IOException e) { throw new IOException("Please check input files in resources folder", e); } catch (InterruptedException e) { - throw new InterruptedException("Couldn't simulate computer player thinking, it got interrupted"); + throw new InterruptedException("Couldn't simulate computer thinking, it got interrupted"); } finally { try { inputConsoleReader.close(); - inputFileReader.close(); + inputFileReaderComp.close(); + inputFileReaderPlayer.close(); } catch (IOException e) { throw new IOException("Couldn't manage to close resources", e); } diff --git a/src/main/java/course_project/sea_battle/Gameplay.java b/src/main/java/course_project/sea_battle/Gameplay.java index 244fa057..f6ece3da 100644 --- a/src/main/java/course_project/sea_battle/Gameplay.java +++ b/src/main/java/course_project/sea_battle/Gameplay.java @@ -1,6 +1,7 @@ package course_project.sea_battle; import course_project.sea_battle.players.ComputerPlayer; +import course_project.sea_battle.players.HumanPlayer; import course_project.sea_battle.players.Player; import course_project.sea_battle.playground.CellData; import course_project.sea_battle.utils.ShotResultCode; @@ -18,10 +19,9 @@ public Gameplay(Player player, Player computer) { } public void setShips() throws IOException, WrongInputException, InterruptedException { - System.out.println(player.getPlayground().toStringMine()); player.setShips(); - System.out.println("Setting ships for computer...\n"); + System.out.println("Setting ships for computer and you...\n"); computer.setShips(); //imitating AI thinking while setting ships @@ -35,7 +35,7 @@ public void printPlaygrounds() { System.out.println(player.getPlayground().toStringMine()); } - public Player getWinner() throws IOException, WrongInputException { + public Player getWinner() throws IOException, WrongInputException, InterruptedException { while (true) { makeMove(player, computer); if (computer.isLoser()) { @@ -50,18 +50,23 @@ public Player getWinner() throws IOException, WrongInputException { } } - private void makeMove(Player p1, Player p2) throws IOException, WrongInputException { + private void makeMove(Player p1, Player p2) throws IOException, WrongInputException, InterruptedException { while (true) { + if (p1 instanceof HumanPlayer) { + printPlaygrounds(); + } System.out.println("\n======= " + p1.toStringWhose() + " MOVE ======="); CellData cellData = p1.makeMove(); ShotResultCode code = p2.checkOwnField(cellData); - printPlaygrounds(); if (p1 instanceof ComputerPlayer) { System.out.println("Computer made a move: " + cellData); + System.out.println(code); + Thread.sleep(2000); + } else { + System.out.println(code); } - System.out.println(code); if (code == ShotResultCode.MISS || p2.isLoser()) { break; diff --git a/src/main/java/course_project/sea_battle/input_readers/InputFileReader.java b/src/main/java/course_project/sea_battle/input_readers/InputFileReader.java index 2e30d660..7c54b49c 100644 --- a/src/main/java/course_project/sea_battle/input_readers/InputFileReader.java +++ b/src/main/java/course_project/sea_battle/input_readers/InputFileReader.java @@ -10,9 +10,9 @@ public class InputFileReader extends InputReader { private final int NUMBER_OF_COMPUTER_SHIPS_SETS = 3; private final BufferedReader br; - public InputFileReader() throws FileNotFoundException { + public InputFileReader(String pack) throws FileNotFoundException { super("Can't set computers ships. Check resource folder for sets text files."); - br = new BufferedReader(new FileReader("src/main/resources/course_project/computer_ships_sets/" + getFileName())); + br = new BufferedReader(new FileReader("src/main/resources/course_project/" + pack + "/" + getFileName())); } @Override diff --git a/src/main/java/course_project/sea_battle/players/HumanPlayer.java b/src/main/java/course_project/sea_battle/players/HumanPlayer.java index f823cfdf..c5d78099 100644 --- a/src/main/java/course_project/sea_battle/players/HumanPlayer.java +++ b/src/main/java/course_project/sea_battle/players/HumanPlayer.java @@ -1,6 +1,7 @@ package course_project.sea_battle.players; import course_project.sea_battle.input_readers.InputConsoleReader; +import course_project.sea_battle.input_readers.InputFileReader; import course_project.sea_battle.playground.CellData; import course_project.sea_battle.playground.Playground; import course_project.sea_battle.ships.Ship; @@ -14,8 +15,8 @@ public class HumanPlayer extends Player { private Playground playground; - public HumanPlayer(InputConsoleReader inputReader) { - super(inputReader); + public HumanPlayer(InputFileReader inputReader, InputConsoleReader inputConsoleReader) { + super(inputReader, inputConsoleReader); this.playground = new Playground(); } @@ -25,17 +26,13 @@ public void setShips() throws IOException, WrongInputException { for (int i = 0; i < Playground.getShipAmount(); i++) { ships[i] = new Ship(ShipType.values()[i], playground); - System.out.println("Let's set " + ships[i].getShipType().name() + " (" + ships[i].getShipType().getLength() + " cells):"); - System.out.println("e.g. A-1"); new Helper().setShip(ships[i]); - System.out.println("Ship " + ships[i].getShipType().name() + " set successfully!"); - System.out.println(playground.toStringMine()); } } @Override public CellData makeMove() throws IOException, WrongInputException { - return getInputReader().readShotData(); + return getInputConsoleReader().readShotData(); } @Override diff --git a/src/main/java/course_project/sea_battle/players/Player.java b/src/main/java/course_project/sea_battle/players/Player.java index 7b751458..a7c52a45 100644 --- a/src/main/java/course_project/sea_battle/players/Player.java +++ b/src/main/java/course_project/sea_battle/players/Player.java @@ -1,5 +1,7 @@ package course_project.sea_battle.players; +import course_project.sea_battle.input_readers.InputConsoleReader; +import course_project.sea_battle.input_readers.InputFileReader; import course_project.sea_battle.playground.CellData; import course_project.sea_battle.playground.CellStatus; import course_project.sea_battle.ships.Ship; @@ -16,10 +18,17 @@ @Getter public abstract class Player { private Playground playground; - private InputReader inputReader; + private final InputReader inputReader; + private final InputConsoleReader inputConsoleReader; public Player(InputReader inputReader) { this.inputReader = inputReader; + this.inputConsoleReader = null; + } + + public Player(InputFileReader inputFileReader, InputConsoleReader inputConsoleReader) { + this.inputReader = inputFileReader; + this.inputConsoleReader = inputConsoleReader; } public abstract void setShips() throws IOException, WrongInputException; diff --git a/src/main/resources/course_project/player_ships_sets/set1.txt b/src/main/resources/course_project/player_ships_sets/set1.txt new file mode 100644 index 00000000..bf39ff87 --- /dev/null +++ b/src/main/resources/course_project/player_ships_sets/set1.txt @@ -0,0 +1,17 @@ +A-1 +A-2 +A-3 +A-4 +A-5 +C-1 +D-1 +E-1 +F-1 +C-3 +C-4 +C-5 +F-9 +F-8 +F-7 +J-3 +J-4 \ No newline at end of file diff --git a/src/main/resources/course_project/player_ships_sets/set2.txt b/src/main/resources/course_project/player_ships_sets/set2.txt new file mode 100644 index 00000000..c45c3ce6 --- /dev/null +++ b/src/main/resources/course_project/player_ships_sets/set2.txt @@ -0,0 +1,17 @@ +B-1 +B-2 +B-3 +B-4 +B-5 +C-9 +D-9 +E-9 +F-9 +C-6 +C-4 +C-5 +F-9 +F-8 +F-7 +F-4 +J-4 \ No newline at end of file diff --git a/src/main/resources/course_project/player_ships_sets/set3.txt b/src/main/resources/course_project/player_ships_sets/set3.txt new file mode 100644 index 00000000..8165e29e --- /dev/null +++ b/src/main/resources/course_project/player_ships_sets/set3.txt @@ -0,0 +1,35 @@ +B-2 +B-3 +B-4 +B-5 +B-6 +D-2 +D-3 +D-4 +D-5 +F-2 +F-3 +F-4 +B-8 +B-9 +B-10 +J-4 +J-3 + +B-2 +B-3 +B-4 +B-5 +B-6 +C-4 +C-5 +C-6 +C-7 +F-7 +G-7 +H-7 +I-2 +I-3 +I-4 +A-7 +A-8 \ No newline at end of file diff --git a/src/test/java/course_project/PlayersTest.java b/src/test/java/course_project/PlayersTest.java index af8ce74f..b4b9e3dc 100644 --- a/src/test/java/course_project/PlayersTest.java +++ b/src/test/java/course_project/PlayersTest.java @@ -16,7 +16,7 @@ public class PlayersTest extends UnitBase { @Test void whenComputerSetsShips_thenSetCorrectNumberOfOccupiedCells() throws IOException, WrongInputException { - ComputerPlayer pc = new ComputerPlayer(new InputFileReader()); + ComputerPlayer pc = new ComputerPlayer(new InputFileReader("computer_ships_sets")); pc.setShips(); long occupiedCellsCount = Arrays.stream(pc.getPlayground()