From fbe96c1440e7255df179dd1b7fdeda1f1b851016 Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 5 Jul 2021 19:36:15 +0300 Subject: [PATCH 01/55] Update Main --- src/main/java/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 9f28e436..79a1fa9b 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,7 +1,7 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello, World!"); + System.out.println("Hello, Russia!"); } } From 13973026fe2a0531abd20a5feccbd43c818ed01e Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 5 Jul 2021 20:14:37 +0300 Subject: [PATCH 02/55] Gitignore update --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8a0a60d2..8d7d939e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ # Project exclude paths /.gradle/ /build/ -/build/classes/java/main/ \ No newline at end of file +/build/classes/java/main/ +/.idea/ +/gradle/ +/.DS_Stor \ No newline at end of file From e0cce8b359fa653f70e34eb00bda78427f89134d Mon Sep 17 00:00:00 2001 From: Waranko Date: Tue, 6 Jul 2021 01:33:17 +0300 Subject: [PATCH 03/55] Gitignore update 2 --- .gitignore | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8d7d939e..14f3f265 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,34 @@ /build/classes/java/main/ /.idea/ /gradle/ -/.DS_Stor \ No newline at end of file +/.DS_Store/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#Ignore files +out +target +*.iml +.idea \ No newline at end of file From 43970c3d5436ca084d0ed3997bbe3a27c6c47c38 Mon Sep 17 00:00:00 2001 From: Waranko Date: Tue, 6 Jul 2021 03:12:23 +0300 Subject: [PATCH 04/55] Add homework 1 --- src/main/java/homework_1/HomeWork1.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/main/java/homework_1/HomeWork1.java diff --git a/src/main/java/homework_1/HomeWork1.java b/src/main/java/homework_1/HomeWork1.java new file mode 100644 index 00000000..aa4e6ba1 --- /dev/null +++ b/src/main/java/homework_1/HomeWork1.java @@ -0,0 +1,17 @@ +package homework_1; + +public class HomeWork1 { + + private static final String RED = (char) 27 + "[31m"; + private static final String RESET = (char) 27 + "[0m"; + + public static void main(String[] args) { + for(String argument: args){ + if(argument.equals("ошибка")){ + System.out.println(RED + "Тревога!" + RESET); + break; + } + System.out.println(argument + ": " + argument.length() + " букв"); + } + } +} From 1a59785554695b80c6cfed4eaf3c3ccc755fd1bf Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 11 Jul 2021 00:53:07 +0300 Subject: [PATCH 05/55] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af7aa356..842125b6 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,6 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/MariaVoronko/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/MariaVoronko/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 b4298b60d65892d83c732577a2d75db1e2dde205 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 11 Jul 2021 22:40:57 +0300 Subject: [PATCH 06/55] Style fix --- src/main/java/homework_1/HomeWork1.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_1/HomeWork1.java b/src/main/java/homework_1/HomeWork1.java index aa4e6ba1..b36a215d 100644 --- a/src/main/java/homework_1/HomeWork1.java +++ b/src/main/java/homework_1/HomeWork1.java @@ -2,8 +2,8 @@ public class HomeWork1 { - private static final String RED = (char) 27 + "[31m"; - private static final String RESET = (char) 27 + "[0m"; + private static final String RED = "\u001B[31m"; + private static final String RESET = "\u001B[0m"; public static void main(String[] args) { for(String argument: args){ From abb0216b3b59e7e578887d2eadcda2f4212b41c2 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 15 Jul 2021 23:30:21 +0300 Subject: [PATCH 07/55] Pyramid Printer --- src/main/java/homework_2/pyramid_printer/PyramidPrinter.java | 2 ++ 1 file changed, 2 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..f9979af5 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,2 @@ +package homework_2.pyramid_printer;public class PyramidPrinter { +} From 3a09f3f9dc86a35b1f9452e2d5cffae184ed80ef Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 15 Jul 2021 23:33:47 +0300 Subject: [PATCH 08/55] Pyramid Printer done --- .../pyramid_printer/PyramidPrinter.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index f9979af5..b0301b99 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -1,2 +1,19 @@ -package homework_2.pyramid_printer;public class PyramidPrinter { +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int pyramidSize = Integer.parseInt(br.readLine()); + for (int i = 1; i <= pyramidSize; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("x "); + } + System.out.println(); + } + } } From aa7e29491afe204ffb9d5edab3d2c9b0874af563 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 15 Jul 2021 23:54:04 +0300 Subject: [PATCH 09/55] Traffic light --- .../traffic_light/TrafficLight.java | 35 +++++++++++++++++++ 1 file changed, 35 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..7cd6026d --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,35 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int seconds; + try { + seconds = Integer.parseInt(br.readLine()); + } catch (NumberFormatException nfe) { + System.out.println("Input error: The number of seconds can be a number only!"); + return; + } + if (seconds < 0) { + System.out.println("Input error: The number of seconds should be positive!"); + return; + } + + if (seconds > 86399) { + System.out.println("Input error: The number of seconds is too big. The day is already over!"); + return; + } + if (seconds % 60 < 35) { + System.out.println("Green"); + } else if (seconds % 60 < 40 || seconds % 60 >= 55) { + System.out.println("Yellow"); + } else { + System.out.println("Red"); + } + } +} From b62a3a844f21aa227bcdc8a28e13cec0f71444a4 Mon Sep 17 00:00:00 2001 From: Waranko Date: Fri, 16 Jul 2021 00:31:41 +0300 Subject: [PATCH 10/55] Random Chars Table --- .../random_chars_table/RandomCharsTable.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTable.java 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..c9d7f81d --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,42 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +public class RandomCharsTable { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] inputValues = br.readLine().split(" "); + + int rows = Integer.parseInt(inputValues[0]); + int columns = Integer.parseInt(inputValues[1]); + boolean isEven = inputValues[2].equals("even"); + if (!isEven && !inputValues[2].equals("odd")) { + System.out.println("Input error: Unrecognized strategy!"); + return; + } + + ArrayList selectedChars = new ArrayList<>(); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + char ch = (char) ('A' + Math.random() * 26); + if ((isEven && (int) ch % 2 == 0) || (!isEven && (int) ch % 2 == 1)) { + selectedChars.add(ch); + } + System.out.print(ch + "|"); + } + System.out.println(); + } + + if (isEven) { + System.out.print("Even letters - "); + } else { + System.out.print("Odd letters - "); + } + String letters = selectedChars.toString(); + System.out.println(letters.substring(1, letters.length() - 1)); + } +} From 0dec12291d7fcec8ed437d9d226e9f394917cfb1 Mon Sep 17 00:00:00 2001 From: Waranko Date: Fri, 16 Jul 2021 00:44:23 +0300 Subject: [PATCH 11/55] README update --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 842125b6..bd659394 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/MariaVoronko/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/MariaVoronko/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument. | +| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer) | The app that reads pyramid size and prints pyramid of 'x' of given size. | +| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table) | The app that prints a table of random chars and finds odd or even letters in it. | [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From bdf3eff886a5708f029e3adcea601f6218af75d6 Mon Sep 17 00:00:00 2001 From: Waranko Date: Fri, 16 Jul 2021 03:19:33 +0300 Subject: [PATCH 12/55] Traffic Light add mode --- .../traffic_light/TrafficLight.java | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 7cd6026d..58051194 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -7,14 +7,37 @@ public class TrafficLight { public static void main(String[] args) throws IOException { + System.out.println("Choose input mode:\n1 - number of seconds\n2 - hh:mm:ss"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String answer = br.readLine(); + int seconds; - try { - seconds = Integer.parseInt(br.readLine()); - } catch (NumberFormatException nfe) { - System.out.println("Input error: The number of seconds can be a number only!"); + if(answer.equals("1")){ + try { + seconds = Integer.parseInt(br.readLine()); + } catch (NumberFormatException nfe) { + System.out.println("Input error: The number of seconds can be a number only!"); + return; + } + } else if(answer.equals("2")){ + String[] time = br.readLine().split(":"); + if(time.length != 3){ + System.out.println("Input error: Wrong input format!"); + return; + } + try { + int hours = Integer.parseInt(time[0]); + int minutes = Integer.parseInt(time[1]); + seconds = 60 * 60 * hours + 60 * minutes + Integer.parseInt(time[2]); + } catch (NumberFormatException nfe) { + System.out.println("Input error: Values can be numbers only!"); + return; + } + } else{ + System.out.println("Unrecognizable answer!"); return; } + if (seconds < 0) { System.out.println("Input error: The number of seconds should be positive!"); return; From ca9fc3e89a3f8c42d4ac3e65108fb499ca3ac98d Mon Sep 17 00:00:00 2001 From: Waranko Date: Fri, 16 Jul 2021 03:23:20 +0300 Subject: [PATCH 13/55] README update --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bd659394..f3768bb3 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument. | -| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | -| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer) | The app that reads pyramid size and prints pyramid of 'x' of given size. | -| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table) | The app that prints a table of random chars and finds odd or even letters in it. | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_1/HomeWork1.java) | The app that reads input arguments and prints them, until "error" argument. | +| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light/TrafficLight.java) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java) | The app that reads pyramid size and prints pyramid of 'x' of given size. | +| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table/RandomCharsTable.java) | The app that prints a table of random chars and finds odd or even letters in it. | [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From e74728a5f333d0381f2008a42f07ec9ef415404f Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 25 Jul 2021 03:23:24 +0300 Subject: [PATCH 14/55] PyramidPrinter hw3 --- .../java/homework_2/pyramid_printer/Main.java | 8 ++ .../pyramid_printer/PyramidPrinter.java | 25 +++++- .../java/homework_2/PyramidPrinterTest.java | 78 +++++++++++++++++++ 3 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 src/main/java/homework_2/pyramid_printer/Main.java create mode 100644 src/test/java/homework_2/PyramidPrinterTest.java diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..71e33035 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,8 @@ +package homework_2.pyramid_printer; + +public class Main { + + public static void main(String[] args) { + new PyramidPrinter().run(); + } +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index b0301b99..744002e1 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,12 +6,29 @@ public class PyramidPrinter { - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - int pyramidSize = Integer.parseInt(br.readLine()); + private int pyramidSize; + + public void run() { + System.out.println("Please, input number:"); + + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + pyramidSize = Integer.parseInt(br.readLine()); + } catch (NumberFormatException | IOException ex) { + System.out.println("Wrong input format!"); + return; + } + if (pyramidSize < 0) { + System.out.println("Number should be non-negative!"); + return; + } + + printPyramid(); + } + + private void printPyramid() { for (int i = 1; i <= pyramidSize; i++) { for (int j = 1; j <= i; j++) { - System.out.print("x "); + System.out.print("x"); } System.out.println(); } diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java new file mode 100644 index 00000000..a3b58a79 --- /dev/null +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -0,0 +1,78 @@ +package homework_2; + +import homework_2.pyramid_printer.PyramidPrinter; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PyramidPrinterTest extends base.UnitBase { + + @Test + void correctInputTest1() { + setInput("2"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input number:"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + } + + @Test + void correctInputTest2() { + setInput("8"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input number:"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xxxx", getOutputLines()[3]); + assertEquals("xxxxxxxx", getOutputLines()[7]); + } + + @Test + void nullInputTest(){ + setInput("0"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input number:"); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void negativeInputTest(){ + setInput("-10"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input number:"); + + assertEquals("Number should be non-negative!", getOutput()); + } + + @Test + void stringInputTest(){ + setInput("string"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input number:"); + + assertEquals("Wrong input format!", getOutput()); + } + + @Test + void bigNumberInputTest(){ + setInput("5666677772444198455342456"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input number:"); + + assertEquals("Wrong input format!", getOutput()); + } +} From bcf657b218f9490e6e97ccb7678aa676f21fe47e Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 25 Jul 2021 04:14:27 +0300 Subject: [PATCH 15/55] RandomCharsTable add classes --- .../homework_2/random_chars_table/Main.java | 8 +++ .../random_chars_table/RandomCharsTable.java | 60 +++++++++++++++---- .../RandomCharsTableCreator.java | 22 +++++++ 3 files changed, 77 insertions(+), 13 deletions(-) create mode 100644 src/main/java/homework_2/random_chars_table/Main.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..be586c4b --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,8 @@ +package homework_2.random_chars_table; + +public class Main { + + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index c9d7f81d..1a5ecc94 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -7,30 +7,64 @@ public class RandomCharsTable { - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - String[] inputValues = br.readLine().split(" "); - - int rows = Integer.parseInt(inputValues[0]); - int columns = Integer.parseInt(inputValues[1]); - boolean isEven = inputValues[2].equals("even"); - if (!isEven && !inputValues[2].equals("odd")) { - System.out.println("Input error: Unrecognized strategy!"); + private final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + private boolean isEven; + private char[][] randomCharsTable; + private final ArrayList selectedChars = new ArrayList<>(); + + public void run() { + System.out.println("Please, enter array length, array width and strategy (odd or even):"); + + int rows, columns; + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + String[] inputValues = br.readLine().split(" "); + if(inputValues.length != 3){ + System.out.println(ERROR_MESSAGE); + return; + } + rows = Integer.parseInt(inputValues[0]); + columns = Integer.parseInt(inputValues[1]); + if(rows <= 0 || columns <= 0){ + System.out.println(ERROR_MESSAGE); + return; + } + isEven = inputValues[2].equals("even"); + if (!isEven && !inputValues[2].equals("odd")) { + System.out.println(ERROR_MESSAGE); + return; + } + } catch (IOException | NumberFormatException e) { + System.out.println(ERROR_MESSAGE); return; } - ArrayList selectedChars = new ArrayList<>(); - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - char ch = (char) ('A' + Math.random() * 26); + randomCharsTable = new RandomCharsTableCreator(rows, columns).createTable(); + findSelectedChars(); + printTable(); + printSelection(); + } + + private void findSelectedChars(){ + for (char[] row : randomCharsTable) { + for (char ch : row) { if ((isEven && (int) ch % 2 == 0) || (!isEven && (int) ch % 2 == 1)) { selectedChars.add(ch); } + } + } + } + + private void printTable(){ + for (char[] row : randomCharsTable) { + System.out.print("|"); + for (char ch : row) { System.out.print(ch + "|"); } System.out.println(); } + } + private void printSelection(){ if (isEven) { System.out.print("Even letters - "); } else { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java new file mode 100644 index 00000000..a17046fd --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -0,0 +1,22 @@ +package homework_2.random_chars_table; + +public class RandomCharsTableCreator { + + private final int rows; + private final int columns; + + RandomCharsTableCreator(int rows, int columns){ + this.rows = rows; + this.columns = columns; + } + + public char[][] createTable(){ + char[][] table = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + table[i][j] = (char) ('A' + Math.random() * 26); + } + } + return table; + } +} From 8e59c3a570b93d14ed2862c012ba5114c58db816 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 25 Jul 2021 04:17:20 +0300 Subject: [PATCH 16/55] PyramidPrinter error message fix --- src/main/java/homework_2/pyramid_printer/PyramidPrinter.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 744002e1..8dacfb05 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,6 +6,7 @@ public class PyramidPrinter { + private final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; private int pyramidSize; public void run() { @@ -14,11 +15,11 @@ public void run() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { pyramidSize = Integer.parseInt(br.readLine()); } catch (NumberFormatException | IOException ex) { - System.out.println("Wrong input format!"); + System.out.println(ERROR_MESSAGE); return; } if (pyramidSize < 0) { - System.out.println("Number should be non-negative!"); + System.out.println(ERROR_MESSAGE); return; } From ea61e8ed6943e0f349c7c5a2fbe229c6a397d7cb Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 26 Jul 2021 12:21:49 +0300 Subject: [PATCH 17/55] PyramidPrinter tests fix --- .../pyramid_printer/PyramidPrinter.java | 2 +- src/test/java/homework_2/PyramidPrinterTest.java | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 8dacfb05..d2fa13ae 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,7 +6,7 @@ public class PyramidPrinter { - private final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; private int pyramidSize; public void run() { diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java index a3b58a79..538b9a59 100644 --- a/src/test/java/homework_2/PyramidPrinterTest.java +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static homework_2.pyramid_printer.PyramidPrinter.ERROR_MESSAGE; public class PyramidPrinterTest extends base.UnitBase { @@ -33,7 +34,7 @@ void correctInputTest2() { } @Test - void nullInputTest(){ + void nullInputTest() { setInput("0"); new PyramidPrinter().run(); @@ -44,35 +45,35 @@ void nullInputTest(){ } @Test - void negativeInputTest(){ + void negativeInputTest() { setInput("-10"); new PyramidPrinter().run(); printOut(); removeFromOutput("Please, input number:"); - assertEquals("Number should be non-negative!", getOutput()); + assertEquals(ERROR_MESSAGE, getOutput()); } @Test - void stringInputTest(){ + void stringInputTest() { setInput("string"); new PyramidPrinter().run(); printOut(); removeFromOutput("Please, input number:"); - assertEquals("Wrong input format!", getOutput()); + assertEquals(ERROR_MESSAGE, getOutput()); } @Test - void bigNumberInputTest(){ + void bigNumberInputTest() { setInput("5666677772444198455342456"); new PyramidPrinter().run(); printOut(); removeFromOutput("Please, input number:"); - assertEquals("Wrong input format!", getOutput()); + assertEquals(ERROR_MESSAGE, getOutput()); } } From fc31c5c632443bb4d59bb7bdecbcd309bdd6a66e Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 26 Jul 2021 13:46:43 +0300 Subject: [PATCH 18/55] RandomCharsTable tests --- .../random_chars_table/RandomCharsTable.java | 15 +- .../RandomCharsTableCreator.java | 4 +- .../java/homework_2/RandomCharsTableTest.java | 138 ++++++++++++++++++ 3 files changed, 148 insertions(+), 9 deletions(-) create mode 100644 src/test/java/homework_2/RandomCharsTableTest.java 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 1a5ecc94..bd993f7e 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -7,24 +7,25 @@ public class RandomCharsTable { - private final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + public static final String START_MESSAGE = "Please, enter array length, array width and strategy (odd or even):"; private boolean isEven; private char[][] randomCharsTable; private final ArrayList selectedChars = new ArrayList<>(); public void run() { - System.out.println("Please, enter array length, array width and strategy (odd or even):"); + System.out.println(START_MESSAGE); int rows, columns; try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { String[] inputValues = br.readLine().split(" "); - if(inputValues.length != 3){ + if (inputValues.length != 3) { System.out.println(ERROR_MESSAGE); return; } rows = Integer.parseInt(inputValues[0]); columns = Integer.parseInt(inputValues[1]); - if(rows <= 0 || columns <= 0){ + if (rows <= 0 || columns <= 0) { System.out.println(ERROR_MESSAGE); return; } @@ -44,7 +45,7 @@ public void run() { printSelection(); } - private void findSelectedChars(){ + private void findSelectedChars() { for (char[] row : randomCharsTable) { for (char ch : row) { if ((isEven && (int) ch % 2 == 0) || (!isEven && (int) ch % 2 == 1)) { @@ -54,7 +55,7 @@ private void findSelectedChars(){ } } - private void printTable(){ + private void printTable() { for (char[] row : randomCharsTable) { System.out.print("|"); for (char ch : row) { @@ -64,7 +65,7 @@ private void printTable(){ } } - private void printSelection(){ + private void printSelection() { if (isEven) { System.out.print("Even letters - "); } else { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java index a17046fd..b36820db 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -5,12 +5,12 @@ public class RandomCharsTableCreator { private final int rows; private final int columns; - RandomCharsTableCreator(int rows, int columns){ + RandomCharsTableCreator(int rows, int columns) { this.rows = rows; this.columns = columns; } - public char[][] createTable(){ + public char[][] createTable() { char[][] table = new char[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java new file mode 100644 index 00000000..679a8931 --- /dev/null +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -0,0 +1,138 @@ +package homework_2; + +import homework_2.random_chars_table.RandomCharsTable; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static homework_2.random_chars_table.RandomCharsTable.ERROR_MESSAGE; +import static homework_2.random_chars_table.RandomCharsTable.START_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class RandomCharsTableTest extends base.UnitBase { + + @Test + void findOddTest() { + setInput("2 3 odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + String oddChar = getOutputLines()[getOutputLines().length - 1]; + removeFromOutput(oddChar); + oddChar = oddChar.replaceFirst("Odd letters - ", ""); + oddChar = oddChar.replaceAll(", ", ""); + for (char ch : oddChar.toCharArray()) { + assertEquals((int) ch % 2, 1); + } + + assertEquals(getOutputLines().length, 2); + int oddCount = 0; + for (String row : getOutputLines()) { + row = row.replaceAll("\\|", ""); + for (char ch : row.toCharArray()) { + assertTrue((65 <= (int) ch) && ((int) ch <= 91)); + if ((int) ch % 2 == 1) { + oddCount++; + } + } + } + assertEquals(oddCount, oddChar.toCharArray().length); + } + + @Test + void findEvenTest() { + setInput("5 4 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + String evenChar = getOutputLines()[getOutputLines().length - 1]; + removeFromOutput(evenChar); + evenChar = evenChar.replaceFirst("Even letters - ", ""); + evenChar = evenChar.replaceAll(", ", ""); + for (char ch : evenChar.toCharArray()) { + assertEquals((int) ch % 2, 0); + } + + assertEquals(getOutputLines().length, 5); + int evenCount = 0; + for (String row : getOutputLines()) { + row = row.replaceAll("\\|", ""); + for (char ch : row.toCharArray()) { + assertTrue((65 <= (int) ch) && ((int) ch <= 91)); + if ((int) ch % 2 == 0) { + evenCount++; + } + } + } + assertEquals(evenCount, evenChar.toCharArray().length); + } + + @Test + void biggerAmountOfArgumentsInputTest() { + setInput("3 4 8 odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void smallerAmountOfArgumentsInputTest() { + setInput("3 4"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void nullAndNegativeInputTest() { + setInput("-3 0 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void unrecognizedStrategyTest() { + setInput("3 8 hello"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void wrongNumberInputTest() { + setInput("u and odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void tooBigNumberInputTest() { + setInput("399372544437489926467 8 hello"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } +} From c582fe9d2194088ccebf3e6316cb8971dcc6db0e Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 26 Jul 2021 13:49:28 +0300 Subject: [PATCH 19/55] PyramidPrinter tests fix --- .../homework_2/pyramid_printer/PyramidPrinter.java | 3 ++- src/test/java/homework_2/PyramidPrinterTest.java | 13 +++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index d2fa13ae..e9e54b79 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -7,10 +7,11 @@ public class PyramidPrinter { public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String START_MESSAGE = "Please, input number:"; private int pyramidSize; public void run() { - System.out.println("Please, input number:"); + System.out.println(START_MESSAGE); try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { pyramidSize = Integer.parseInt(br.readLine()); diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java index 538b9a59..ff0aa234 100644 --- a/src/test/java/homework_2/PyramidPrinterTest.java +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static homework_2.pyramid_printer.PyramidPrinter.ERROR_MESSAGE; +import static homework_2.pyramid_printer.PyramidPrinter.START_MESSAGE; public class PyramidPrinterTest extends base.UnitBase { @@ -14,7 +15,7 @@ void correctInputTest1() { new PyramidPrinter().run(); printOut(); - removeFromOutput("Please, input number:"); + removeFromOutput(START_MESSAGE); assertEquals("x", getOutputLines()[0]); assertEquals("xx", getOutputLines()[1]); @@ -26,7 +27,7 @@ void correctInputTest2() { new PyramidPrinter().run(); printOut(); - removeFromOutput("Please, input number:"); + removeFromOutput(START_MESSAGE); assertEquals("x", getOutputLines()[0]); assertEquals("xxxx", getOutputLines()[3]); @@ -39,7 +40,7 @@ void nullInputTest() { new PyramidPrinter().run(); printOut(); - removeFromOutput("Please, input number:"); + removeFromOutput(START_MESSAGE); assertEquals("", getOutputLines()[0]); } @@ -50,7 +51,7 @@ void negativeInputTest() { new PyramidPrinter().run(); printOut(); - removeFromOutput("Please, input number:"); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } @@ -61,7 +62,7 @@ void stringInputTest() { new PyramidPrinter().run(); printOut(); - removeFromOutput("Please, input number:"); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } @@ -72,7 +73,7 @@ void bigNumberInputTest() { new PyramidPrinter().run(); printOut(); - removeFromOutput("Please, input number:"); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } From 38d7e094676535f694c36e891f96e8bb8d8ead3d Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 26 Jul 2021 19:09:32 +0300 Subject: [PATCH 20/55] TrafficLight tests --- .../java/homework_2/traffic_light/Main.java | 8 ++ .../traffic_light/TrafficLight.java | 59 +++++------- .../java/homework_2/TrafficLightTest.java | 91 +++++++++++++++++++ 3 files changed, 123 insertions(+), 35 deletions(-) create mode 100644 src/main/java/homework_2/traffic_light/Main.java create mode 100644 src/test/java/homework_2/TrafficLightTest.java 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..3ff7f428 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,8 @@ +package homework_2.traffic_light; + +public class Main { + + public static void main(String[] args) { + new TrafficLight().run(); + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 58051194..1fb4eacd 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -6,53 +6,42 @@ public class TrafficLight { - public static void main(String[] args) throws IOException { - System.out.println("Choose input mode:\n1 - number of seconds\n2 - hh:mm:ss"); - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - String answer = br.readLine(); + public static final String RESET = "\u001B[0m"; + public static final String RED = "\u001B[31m"; + public static final String YELLOW = "\u001B[33m"; + public static final String GREEN = "\u001B[32m"; + public static final String START_MESSAGE = "Please, input number of seconds:"; + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + private int seconds; - int seconds; - if(answer.equals("1")){ - try { - seconds = Integer.parseInt(br.readLine()); - } catch (NumberFormatException nfe) { - System.out.println("Input error: The number of seconds can be a number only!"); - return; - } - } else if(answer.equals("2")){ - String[] time = br.readLine().split(":"); - if(time.length != 3){ - System.out.println("Input error: Wrong input format!"); - return; - } - try { - int hours = Integer.parseInt(time[0]); - int minutes = Integer.parseInt(time[1]); - seconds = 60 * 60 * hours + 60 * minutes + Integer.parseInt(time[2]); - } catch (NumberFormatException nfe) { - System.out.println("Input error: Values can be numbers only!"); - return; - } - } else{ - System.out.println("Unrecognizable answer!"); + public void run() { + System.out.println(START_MESSAGE); + + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + seconds = Integer.parseInt(br.readLine()); + } catch (IOException | NumberFormatException e) { + System.out.println(ERROR_MESSAGE); return; } - if (seconds < 0) { - System.out.println("Input error: The number of seconds should be positive!"); + System.out.println(ERROR_MESSAGE); return; } - if (seconds > 86399) { - System.out.println("Input error: The number of seconds is too big. The day is already over!"); + System.out.println(ERROR_MESSAGE); return; } + + printColor(); + } + + private void printColor() { if (seconds % 60 < 35) { - System.out.println("Green"); + System.out.println(GREEN + "GREEN" + RESET); } else if (seconds % 60 < 40 || seconds % 60 >= 55) { - System.out.println("Yellow"); + System.out.println(YELLOW + "YELLOW" + RESET); } else { - System.out.println("Red"); + System.out.println(RED + "RED" + RESET); } } } diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java new file mode 100644 index 00000000..cbf89ac3 --- /dev/null +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -0,0 +1,91 @@ +package homework_2; + +import homework_2.traffic_light.TrafficLight; +import org.junit.jupiter.api.Test; + +import static homework_2.traffic_light.TrafficLight.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightTest extends base.UnitBase { + + private final String RED_VALUE = RED.substring(1); + private final String YELLOW_VALUE = YELLOW.substring(1); + private final String GREEN_VALUE = GREEN.substring(1); + + @Test + void getGreenTest() { + setInput("5"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + } + + @Test + void getYellowTest() { + setInput("35"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(YELLOW_VALUE + "YELLOW" + RESET, getOutput()); + } + + @Test + void getRedTest() { + setInput("54"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(RED_VALUE + "RED" + RESET, getOutput()); + } + + @Test + void nullInputTest() { + setInput("0"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + } + + @Test + void tooBigInputTest() { + setInput("86401"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void stringInputTest() { + setInput("string"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void charInputTest() { + setInput("c"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } +} From eb53c5e97e728ba913b26385927d77f7760a38d6 Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 26 Jul 2021 19:15:47 +0300 Subject: [PATCH 21/55] Add link to codingbat --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f3768bb3..3f4d3ddb 100644 --- a/README.md +++ b/README.md @@ -9,4 +9,6 @@ | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java) | The app that reads pyramid size and prints pyramid of 'x' of given size. | | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table/RandomCharsTable.java) | The app that prints a table of random chars and finds odd or even letters in it. | +[Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) + [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 213734624a98360deb00b44eb990522695be7a33 Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 26 Jul 2021 20:27:04 +0300 Subject: [PATCH 22/55] Immutable class --- src/main/java/homework_3/ImmutableCat.java | 45 ++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/homework_3/ImmutableCat.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..02485e21 --- /dev/null +++ b/src/main/java/homework_3/ImmutableCat.java @@ -0,0 +1,45 @@ +package homework_3; + +import java.util.ArrayList; + +/* + Список требований к ImmutableClass: + - Класс должен быть final. + - Поля класса должны быть private. + - Поля класса должны быть final. + - Параметризированные конструкторы должны инициализировать поля ссылочного типа, + используя глубокое копирование. + - В методых класса не изменяем поля класса, а возвращем его измененную копию. + */ + +public final class ImmutableCat { + + private final String name; + private final int yearOfBirth; + private final ArrayList favouriteFood = new ArrayList<>(); + + + public ImmutableCat(String name, int yearOfBirth, ArrayList favouriteFood) { + this.name = name; + this.yearOfBirth = yearOfBirth; + this.favouriteFood.addAll(favouriteFood); + } + + public ImmutableCat(String name){ + this.name = name; + yearOfBirth = 2020; + } + + public ImmutableCat(){ + this.name = "Cat"; + yearOfBirth = 2020; + } + + public ImmutableCat setNewName(String name){ + return new ImmutableCat(name); + } + + public ImmutableCat setNewData(String name, int yearOfBirth, ArrayList favouriteFood){ + return new ImmutableCat(name, yearOfBirth, favouriteFood); + } +} From f671dbcaf94826d5e67d419c3ed74aabddb99f34 Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 26 Jul 2021 20:27:22 +0300 Subject: [PATCH 23/55] RandomCharsTableCreator update --- .../homework_2/random_chars_table/RandomCharsTableCreator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java index b36820db..353981be 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -5,7 +5,7 @@ public class RandomCharsTableCreator { private final int rows; private final int columns; - RandomCharsTableCreator(int rows, int columns) { + public RandomCharsTableCreator(int rows, int columns) { this.rows = rows; this.columns = columns; } From ac5c12c7aff5815517e110d0a25302d632df8c7e Mon Sep 17 00:00:00 2001 From: Waranko Date: Wed, 28 Jul 2021 03:07:29 +0300 Subject: [PATCH 24/55] TrafficLight add ExtraMode --- .../java/homework_2/traffic_light/Main.java | 6 +- .../traffic_light/TrafficLight.java | 4 +- .../traffic_light/TrafficLightExtraMode.java | 42 +++++++ .../homework_2/TrafficLightExtraModeTest.java | 117 ++++++++++++++++++ .../java/homework_2/TrafficLightTest.java | 6 +- 5 files changed, 169 insertions(+), 6 deletions(-) create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java create mode 100644 src/test/java/homework_2/TrafficLightExtraModeTest.java diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index 3ff7f428..fbd5c4ca 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -3,6 +3,10 @@ public class Main { public static void main(String[] args) { - new TrafficLight().run(); + if (args.length != 0 && args[0].equals("ExtraMode")) { + new TrafficLightExtraMode().run(); + } else { + 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 1fb4eacd..6f172fc7 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -12,7 +12,7 @@ public class TrafficLight { public static final String GREEN = "\u001B[32m"; public static final String START_MESSAGE = "Please, input number of seconds:"; public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; - private int seconds; + protected int seconds; public void run() { System.out.println(START_MESSAGE); @@ -35,7 +35,7 @@ public void run() { printColor(); } - private void printColor() { + protected void printColor() { if (seconds % 60 < 35) { System.out.println(GREEN + "GREEN" + RESET); } else if (seconds % 60 < 40 || seconds % 60 >= 55) { diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java new file mode 100644 index 00000000..54e42110 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -0,0 +1,42 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLightExtraMode extends TrafficLight { + + public static final String ERROR_MESSAGE = "Only input in format hh:mm:ss is allowed"; + + @Override + public void run() { + System.out.println(START_MESSAGE); + + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + String input = br.readLine(); + if (!input.contains(":")) { + System.out.println(ERROR_MESSAGE); + return; + } + String[] time = input.split(":"); + if (time.length != 3) { + System.out.println(ERROR_MESSAGE); + return; + } + int hours = Integer.parseInt(time[0]); + int minutes = Integer.parseInt(time[1]); + seconds = Integer.parseInt(time[2]); + if ((hours < 0 || hours > 23) + || (minutes < 0 || minutes > 59) + || (seconds < 0 || seconds > 59)) { + System.out.println(ERROR_MESSAGE); + return; + } + } catch (IOException | NumberFormatException e) { + System.out.println(ERROR_MESSAGE); + return; + } + + printColor(); + } +} diff --git a/src/test/java/homework_2/TrafficLightExtraModeTest.java b/src/test/java/homework_2/TrafficLightExtraModeTest.java new file mode 100644 index 00000000..7dc3206c --- /dev/null +++ b/src/test/java/homework_2/TrafficLightExtraModeTest.java @@ -0,0 +1,117 @@ +package homework_2; + +import homework_2.traffic_light.TrafficLightExtraMode; +import org.junit.jupiter.api.Test; + +import static homework_2.traffic_light.TrafficLightExtraMode.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightExtraModeTest extends TrafficLightTest { + + @Override + @Test + void getGreenTest() { + setInput("11:08:5"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + } + + @Override + @Test + void getYellowTest() { + setInput("09:18:36"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(YELLOW_VALUE + "YELLOW" + RESET, getOutput()); + } + + @Override + @Test + void getRedTest() { + setInput("01:59:49"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(RED_VALUE + "RED" + RESET, getOutput()); + } + + @Override + @Test + void nullInputTest() { + setInput("00:00:00"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + } + + @Override + @Test + void charInputTest() { + setInput("14:08:t"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Override + @Test + void stringInputTest() { + setInput("string"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Override + @Test + void tooBigInputTest() { + setInput("24:01:00"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void wrongTimeParametersNumberTest() { + setInput("04:58"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void wrongTimeFormatTest() { + setInput("04:61:89"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + +} diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java index cbf89ac3..cb55a5e1 100644 --- a/src/test/java/homework_2/TrafficLightTest.java +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -8,9 +8,9 @@ public class TrafficLightTest extends base.UnitBase { - private final String RED_VALUE = RED.substring(1); - private final String YELLOW_VALUE = YELLOW.substring(1); - private final String GREEN_VALUE = GREEN.substring(1); + protected final String RED_VALUE = RED.substring(1); + protected final String YELLOW_VALUE = YELLOW.substring(1); + protected final String GREEN_VALUE = GREEN.substring(1); @Test void getGreenTest() { From 81e2f7cb51922834730a4c2706fa9b18db6b0626 Mon Sep 17 00:00:00 2001 From: Waranko Date: Wed, 28 Jul 2021 03:11:38 +0300 Subject: [PATCH 25/55] README add HW3 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3f4d3ddb..a862c466 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light/TrafficLight.java) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java) | The app that reads pyramid size and prints pyramid of 'x' of given size. | | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table/RandomCharsTable.java) | The app that prints a table of random chars and finds odd or even letters in it. | +| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_3/ImmutableCat.java) | To create an immutable class and write its requirements in comments. | [Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) From d02a92b28f8e2bb5f8cd6b6ba25642d93ee76cd1 Mon Sep 17 00:00:00 2001 From: Waranko Date: Wed, 28 Jul 2021 22:07:53 +0300 Subject: [PATCH 26/55] HW2 style fix --- .../java/homework_2/pyramid_printer/Main.java | 1 + .../pyramid_printer/PyramidPrinter.java | 17 +++++----- .../random_chars_table/RandomCharsTable.java | 34 +++++++++---------- .../traffic_light/TrafficLight.java | 25 +++++++------- .../traffic_light/TrafficLightExtraMode.java | 22 ++++++------ 5 files changed, 50 insertions(+), 49 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index 71e33035..37e93643 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -5,4 +5,5 @@ public class Main { 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 e9e54b79..be779062 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -12,19 +12,20 @@ public class PyramidPrinter { public void run() { System.out.println(START_MESSAGE); + if (validation()) { + printPyramid(); + } else { + System.out.println(ERROR_MESSAGE); + } + } + private boolean validation() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { pyramidSize = Integer.parseInt(br.readLine()); } catch (NumberFormatException | IOException ex) { - System.out.println(ERROR_MESSAGE); - return; + return false; } - if (pyramidSize < 0) { - System.out.println(ERROR_MESSAGE); - return; - } - - printPyramid(); + return pyramidSize >= 0; } private void printPyramid() { 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 bd993f7e..8d3ea55c 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -10,39 +10,39 @@ public class RandomCharsTable { public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; public static final String START_MESSAGE = "Please, enter array length, array width and strategy (odd or even):"; private boolean isEven; + int rows, columns; private char[][] randomCharsTable; private final ArrayList selectedChars = new ArrayList<>(); public void run() { System.out.println(START_MESSAGE); + if (validation()) { + randomCharsTable = new RandomCharsTableCreator(rows, columns).createTable(); + findSelectedChars(); + printTable(); + printSelection(); + } else { + System.out.println(ERROR_MESSAGE); + } + } - int rows, columns; + private boolean validation() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { String[] inputValues = br.readLine().split(" "); if (inputValues.length != 3) { - System.out.println(ERROR_MESSAGE); - return; + return false; } rows = Integer.parseInt(inputValues[0]); columns = Integer.parseInt(inputValues[1]); - if (rows <= 0 || columns <= 0) { - System.out.println(ERROR_MESSAGE); - return; + if (rows <= 0 || columns <= 0 || + (!inputValues[2].equals("even") && !inputValues[2].equals("odd"))) { + return false; } isEven = inputValues[2].equals("even"); - if (!isEven && !inputValues[2].equals("odd")) { - System.out.println(ERROR_MESSAGE); - return; - } } catch (IOException | NumberFormatException e) { - System.out.println(ERROR_MESSAGE); - return; + return false; } - - randomCharsTable = new RandomCharsTableCreator(rows, columns).createTable(); - findSelectedChars(); - printTable(); - printSelection(); + return true; } private void findSelectedChars() { diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 6f172fc7..975d4757 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -16,23 +16,20 @@ public class TrafficLight { public void run() { System.out.println(START_MESSAGE); + if (validation()) { + printColor(); + } else { + printErrorMessage(); + } + } + protected boolean validation() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { seconds = Integer.parseInt(br.readLine()); } catch (IOException | NumberFormatException e) { - System.out.println(ERROR_MESSAGE); - return; - } - if (seconds < 0) { - System.out.println(ERROR_MESSAGE); - return; + return false; } - if (seconds > 86399) { - System.out.println(ERROR_MESSAGE); - return; - } - - printColor(); + return seconds >= 0 && seconds <= 86399; } protected void printColor() { @@ -44,4 +41,8 @@ protected void printColor() { System.out.println(RED + "RED" + RESET); } } + + protected void printErrorMessage() { + System.out.println(ERROR_MESSAGE); + } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index 54e42110..c5c8f0f8 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -9,19 +9,15 @@ public class TrafficLightExtraMode extends TrafficLight { public static final String ERROR_MESSAGE = "Only input in format hh:mm:ss is allowed"; @Override - public void run() { - System.out.println(START_MESSAGE); - + protected boolean validation() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { String input = br.readLine(); if (!input.contains(":")) { - System.out.println(ERROR_MESSAGE); - return; + return false; } String[] time = input.split(":"); if (time.length != 3) { - System.out.println(ERROR_MESSAGE); - return; + return false; } int hours = Integer.parseInt(time[0]); int minutes = Integer.parseInt(time[1]); @@ -29,14 +25,16 @@ public void run() { if ((hours < 0 || hours > 23) || (minutes < 0 || minutes > 59) || (seconds < 0 || seconds > 59)) { - System.out.println(ERROR_MESSAGE); - return; + return false; } } catch (IOException | NumberFormatException e) { - System.out.println(ERROR_MESSAGE); - return; + return false; } + return true; + } - printColor(); + @Override + protected void printErrorMessage() { + System.out.println(ERROR_MESSAGE); } } From 71a7349a80971ac451848df8bd8b3a7f8cf6933b Mon Sep 17 00:00:00 2001 From: Waranko Date: Wed, 28 Jul 2021 22:11:34 +0300 Subject: [PATCH 27/55] README add hw2 tests link --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a862c466..fd95ce48 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,10 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_1/HomeWork1.java) | The app that reads input arguments and prints them, until "error" argument. | -| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light/TrafficLight.java) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | +| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java) | The app that reads pyramid size and prints pyramid of 'x' of given size. | | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table/RandomCharsTable.java) | The app that prints a table of random chars and finds odd or even letters in it. | +| HW2 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_2) | Tests for homework 2. | | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_3/ImmutableCat.java) | To create an immutable class and write its requirements in comments. | [Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) From ff8a35cb360de3a5f44a12638758f766e313e878 Mon Sep 17 00:00:00 2001 From: Waranko Date: Wed, 28 Jul 2021 22:41:25 +0300 Subject: [PATCH 28/55] HW2 tests update --- .../pyramid_printer/PyramidPrinter.java | 6 ++---- .../random_chars_table/RandomCharsTable.java | 6 ++---- .../traffic_light/TrafficLight.java | 19 +++++++++---------- .../traffic_light/TrafficLightExtraMode.java | 4 +--- .../java/homework_2/PyramidPrinterTest.java | 5 +++-- .../java/homework_2/RandomCharsTableTest.java | 5 +++-- .../homework_2/TrafficLightExtraModeTest.java | 12 +++++++----- .../java/homework_2/TrafficLightTest.java | 15 +++++++-------- 8 files changed, 34 insertions(+), 38 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index be779062..744cd012 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,16 +6,14 @@ public class PyramidPrinter { - public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; - public static final String START_MESSAGE = "Please, input number:"; private int pyramidSize; public void run() { - System.out.println(START_MESSAGE); + System.out.println("Please, input number:"); if (validation()) { printPyramid(); } else { - System.out.println(ERROR_MESSAGE); + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } } 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 8d3ea55c..13d4b8e2 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -7,22 +7,20 @@ public class RandomCharsTable { - public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; - public static final String START_MESSAGE = "Please, enter array length, array width and strategy (odd or even):"; private boolean isEven; int rows, columns; private char[][] randomCharsTable; private final ArrayList selectedChars = new ArrayList<>(); public void run() { - System.out.println(START_MESSAGE); + System.out.println("Please, enter array length, array width and strategy (odd or even):"); if (validation()) { randomCharsTable = new RandomCharsTableCreator(rows, columns).createTable(); findSelectedChars(); printTable(); printSelection(); } else { - System.out.println(ERROR_MESSAGE); + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 975d4757..19056462 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -6,16 +6,14 @@ public class TrafficLight { - public static final String RESET = "\u001B[0m"; - public static final String RED = "\u001B[31m"; - public static final String YELLOW = "\u001B[33m"; - public static final String GREEN = "\u001B[32m"; - public static final String START_MESSAGE = "Please, input number of seconds:"; - public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + private static final String RESET = "\u001B[0m"; + private static final String RED = "\u001B[31m"; + private static final String YELLOW = "\u001B[33m"; + private static final String GREEN = "\u001B[32m"; protected int seconds; public void run() { - System.out.println(START_MESSAGE); + System.out.println("Please, input time:"); if (validation()) { printColor(); } else { @@ -24,7 +22,8 @@ public void run() { } protected boolean validation() { - try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + try (BufferedReader br = + new BufferedReader(new InputStreamReader(System.in))) { seconds = Integer.parseInt(br.readLine()); } catch (IOException | NumberFormatException e) { return false; @@ -32,7 +31,7 @@ protected boolean validation() { return seconds >= 0 && seconds <= 86399; } - protected void printColor() { + private void printColor() { if (seconds % 60 < 35) { System.out.println(GREEN + "GREEN" + RESET); } else if (seconds % 60 < 40 || seconds % 60 >= 55) { @@ -43,6 +42,6 @@ protected void printColor() { } protected void printErrorMessage() { - System.out.println(ERROR_MESSAGE); + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index c5c8f0f8..3952d262 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -6,8 +6,6 @@ public class TrafficLightExtraMode extends TrafficLight { - public static final String ERROR_MESSAGE = "Only input in format hh:mm:ss is allowed"; - @Override protected boolean validation() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { @@ -35,6 +33,6 @@ protected boolean validation() { @Override protected void printErrorMessage() { - System.out.println(ERROR_MESSAGE); + System.out.println("Only input in format hh:mm:ss is allowed"); } } diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java index ff0aa234..42e0cce5 100644 --- a/src/test/java/homework_2/PyramidPrinterTest.java +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -4,11 +4,12 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static homework_2.pyramid_printer.PyramidPrinter.ERROR_MESSAGE; -import static homework_2.pyramid_printer.PyramidPrinter.START_MESSAGE; public class PyramidPrinterTest extends base.UnitBase { + private final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + private final String START_MESSAGE = "Please, input number:"; + @Test void correctInputTest1() { setInput("2"); diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java index 679a8931..9a1dda73 100644 --- a/src/test/java/homework_2/RandomCharsTableTest.java +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -4,12 +4,13 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static homework_2.random_chars_table.RandomCharsTable.ERROR_MESSAGE; -import static homework_2.random_chars_table.RandomCharsTable.START_MESSAGE; import static org.junit.jupiter.api.Assertions.assertTrue; public class RandomCharsTableTest extends base.UnitBase { + private final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + private final String START_MESSAGE = "Please, enter array length, array width and strategy (odd or even):"; + @Test void findOddTest() { setInput("2 3 odd"); diff --git a/src/test/java/homework_2/TrafficLightExtraModeTest.java b/src/test/java/homework_2/TrafficLightExtraModeTest.java index 7dc3206c..382cb176 100644 --- a/src/test/java/homework_2/TrafficLightExtraModeTest.java +++ b/src/test/java/homework_2/TrafficLightExtraModeTest.java @@ -3,11 +3,13 @@ import homework_2.traffic_light.TrafficLightExtraMode; import org.junit.jupiter.api.Test; -import static homework_2.traffic_light.TrafficLightExtraMode.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TrafficLightExtraModeTest extends TrafficLightTest { + private final String ERROR_MESSAGE = "Only input in format hh:mm:ss is allowed"; + @Override @Test void getGreenTest() { @@ -17,7 +19,7 @@ void getGreenTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + assertTrue(getOutput().contains("GREEN")); } @Override @@ -29,7 +31,7 @@ void getYellowTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(YELLOW_VALUE + "YELLOW" + RESET, getOutput()); + assertTrue(getOutput().contains("YELLOW")); } @Override @@ -41,7 +43,7 @@ void getRedTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(RED_VALUE + "RED" + RESET, getOutput()); + assertTrue(getOutput().contains("RED")); } @Override @@ -53,7 +55,7 @@ void nullInputTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + assertTrue(getOutput().contains("GREEN")); } @Override diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java index cb55a5e1..e3e9236b 100644 --- a/src/test/java/homework_2/TrafficLightTest.java +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -3,14 +3,13 @@ import homework_2.traffic_light.TrafficLight; import org.junit.jupiter.api.Test; -import static homework_2.traffic_light.TrafficLight.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TrafficLightTest extends base.UnitBase { - protected final String RED_VALUE = RED.substring(1); - protected final String YELLOW_VALUE = YELLOW.substring(1); - protected final String GREEN_VALUE = GREEN.substring(1); + protected final String START_MESSAGE = "Please, input time:"; + private final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; @Test void getGreenTest() { @@ -20,7 +19,7 @@ void getGreenTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + assertTrue(getOutput().contains("GREEN")); } @Test @@ -31,7 +30,7 @@ void getYellowTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(YELLOW_VALUE + "YELLOW" + RESET, getOutput()); + assertTrue(getOutput().contains("YELLOW")); } @Test @@ -42,7 +41,7 @@ void getRedTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(RED_VALUE + "RED" + RESET, getOutput()); + assertTrue(getOutput().contains("RED")); } @Test @@ -53,7 +52,7 @@ void nullInputTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(GREEN_VALUE + "GREEN" + RESET, getOutput()); + assertTrue(getOutput().contains("GREEN")); } @Test From b7edb8ee8be4dd0922deb3a46efd140dbebae4f4 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 12 Aug 2021 21:37:59 +0300 Subject: [PATCH 29/55] HW4 CustomFileReader done --- .../custom_file_reader/CustomFileReader.java | 53 +++++++++++++++++++ .../homework_4/custom_file_reader/Main.java | 14 +++++ src/main/resources/custom_file_reader | 4 ++ 3 files changed, 71 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 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..ce1482b9 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,53 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; + +public class CustomFileReader { + + private final String fileName = "src/main/resources/custom_file_reader"; + + public void run1() throws IOException { + try (FileReader fileReader = new FileReader(fileName)) { + int charCode; + while ((charCode = fileReader.read()) != -1) { + processAndPrintChar(charCode); + } + System.out.println(); + } + } + + public void run2() throws IOException { + try (FileInputStream fileInputStream = new FileInputStream(fileName)) { + int charCode; + while ((charCode = fileInputStream.read()) != -1) { + processAndPrintChar(charCode); + } + System.out.println(); + } + } + + public void run3() throws IOException { + RandomAccessFile file = new RandomAccessFile(fileName, "r"); + FileChannel fileChannel = file.getChannel(); + ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size()); + while (fileChannel.read(byteBuffer) > 0) { + String content = new String(byteBuffer.array(), StandardCharsets.UTF_8); + content = content.replaceAll("[.,]", ""); + System.out.println(content); + byteBuffer.clear(); + } + fileChannel.close(); + file.close(); + } + + private void processAndPrintChar(int charCode) { + char ch = (char) charCode; + if (ch != ',' && ch != '.') { + System.out.print(ch); + } + } + +} 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..df3e83d4 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,14 @@ +package homework_4.custom_file_reader; + +import java.io.IOException; + +public class Main { + + public static void main(String[] args) throws IOException { + CustomFileReader cfr = new CustomFileReader(); + cfr.run1(); + cfr.run2(); + cfr.run3(); + } + +} diff --git a/src/main/resources/custom_file_reader b/src/main/resources/custom_file_reader new file mode 100644 index 00000000..d34a5471 --- /dev/null +++ b/src/main/resources/custom_file_reader @@ -0,0 +1,4 @@ +Hello, world! +second... line... +.,.,.,.,.,,.,, +...=)... \ No newline at end of file From 23cfe1a609d10f42a07b1d82c659d339cbc58b72 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 12 Aug 2021 23:34:38 +0300 Subject: [PATCH 30/55] HW4 CustomFileReader tests --- build.gradle | 1 + src/main/resources/custom_file_reader | 1 - .../java/homework_4/CustomFileReaderTest.java | 69 +++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 src/test/java/homework_4/CustomFileReaderTest.java diff --git a/build.gradle b/build.gradle index b91dc843..11cbecd8 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testCompile("org.junit.jupiter:junit-jupiter-params:5.7.0") } test { diff --git a/src/main/resources/custom_file_reader b/src/main/resources/custom_file_reader index d34a5471..b6fb1981 100644 --- a/src/main/resources/custom_file_reader +++ b/src/main/resources/custom_file_reader @@ -1,4 +1,3 @@ Hello, world! second... line... -.,.,.,.,.,,.,, ...=)... \ No newline at end of file diff --git a/src/test/java/homework_4/CustomFileReaderTest.java b/src/test/java/homework_4/CustomFileReaderTest.java new file mode 100644 index 00000000..a6ea3a2b --- /dev/null +++ b/src/test/java/homework_4/CustomFileReaderTest.java @@ -0,0 +1,69 @@ +package homework_4; + +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +public class CustomFileReaderTest extends base.UnitBase { + + private final String fileName = "src/main/resources/custom_file_reader"; + CustomFileReader cfr = new CustomFileReader(); + + public static Stream testCases() { + return Stream.of( + arguments("First test.\nHello, World...\n...last,, line.", "First test\nHello World\nlast line"), + arguments("..2 test,\n:)/|,:;.", "2 test\n:)/|:;"), + arguments("...", ""), + arguments(",,,", ""), + arguments("", "") + ); + } + + @ParameterizedTest + @MethodSource("testCases") + void run1Test(String fileContent, String expected) throws IOException { + try (PrintWriter pw = new PrintWriter(fileName)) { + pw.print(fileContent); + } + + cfr.run1(); + printOut(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCases") + void run2Test(String fileContent, String expected) throws IOException { + try (PrintWriter pw = new PrintWriter(fileName)) { + pw.print(fileContent); + } + + cfr.run2(); + printOut(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCases") + void run3Test(String fileContent, String expected) throws IOException { + try (PrintWriter pw = new PrintWriter(fileName)) { + pw.print(fileContent); + } + + cfr.run2(); + printOut(); + + assertEquals(expected, getOutput()); + } + +} From 4e4bcb7823bfd081b81e5a691a57bb5cc137377d Mon Sep 17 00:00:00 2001 From: Waranko Date: Fri, 13 Aug 2021 00:34:05 +0300 Subject: [PATCH 31/55] HW4 Singleton done --- src/main/java/homework_4/singleton/Main.java | 9 +++++++ .../java/homework_4/singleton/Singleton.java | 25 ++++++++++++++++++ src/test/java/homework_4/SingletonTest.java | 26 +++++++++++++++++++ 3 files changed, 60 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/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..82cd6ab8 --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,9 @@ +package homework_4.singleton; + +public class Main { + + public static void main(String[] args) { + Singleton singleton = Singleton.getInstance(); + } + +} 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..97d471f6 --- /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 singletonInstance; + private String state = "created"; + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + private Singleton() {} + + public static Singleton getInstance() { + if (singletonInstance == null) { + singletonInstance = new Singleton(); + } + return singletonInstance; + } + +} diff --git a/src/test/java/homework_4/SingletonTest.java b/src/test/java/homework_4/SingletonTest.java new file mode 100644 index 00000000..11b6a593 --- /dev/null +++ b/src/test/java/homework_4/SingletonTest.java @@ -0,0 +1,26 @@ +package homework_4; + +import homework_4.singleton.Singleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SingletonTest { + + @Test + void singletonFeaturesTest() { + Singleton singleton1 = Singleton.getInstance(); + Singleton singleton2 = Singleton.getInstance(); + + assertEquals("created", singleton1.getState()); + assertEquals("created", singleton2.getState()); + + singleton1.setState("changed"); + + assertEquals("changed", singleton1.getState()); + assertEquals("changed", singleton2.getState()); + + assertEquals(singleton2, singleton1); + } + +} From 3de36b402a2f3d8c37513b46438867fddedba024 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 14 Aug 2021 06:32:29 +0300 Subject: [PATCH 32/55] HW4 CustomAnnotation done --- build.gradle | 7 +++ .../homework_4/custom_annotation/Book.java | 41 +++++++++++++ .../FieldPriorityComparator.java | 15 +++++ .../custom_annotation/ImportantField.java | 18 ++++++ .../homework_4/custom_annotation/Main.java | 13 +++++ .../java/homework_4/ImportantFieldTest.java | 57 +++++++++++++++++++ 6 files changed, 151 insertions(+) create mode 100644 src/main/java/homework_4/custom_annotation/Book.java create mode 100644 src/main/java/homework_4/custom_annotation/FieldPriorityComparator.java create mode 100644 src/main/java/homework_4/custom_annotation/ImportantField.java create mode 100644 src/main/java/homework_4/custom_annotation/Main.java create mode 100644 src/test/java/homework_4/ImportantFieldTest.java diff --git a/build.gradle b/build.gradle index 11cbecd8..820ef2b2 100644 --- a/build.gradle +++ b/build.gradle @@ -10,8 +10,15 @@ repositories { } dependencies { + compileOnly 'org.projectlombok:lombok:1.18.20' + annotationProcessor 'org.projectlombok:lombok:1.18.20' + + testCompileOnly 'org.projectlombok:lombok:1.18.20' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.20' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testCompile("org.junit.jupiter:junit-jupiter-params:5.7.0") } diff --git a/src/main/java/homework_4/custom_annotation/Book.java b/src/main/java/homework_4/custom_annotation/Book.java new file mode 100644 index 00000000..1b08b74e --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Book.java @@ -0,0 +1,41 @@ +package homework_4.custom_annotation; + +import lombok.Data; + +import java.lang.reflect.Field; +import java.util.ArrayList; + +@Data +public class Book { + + @ImportantField(priority = 1) + private String title; + @ImportantField(priority = 3) + private String genre = "not specified"; + private String description = ""; + @ImportantField(priority = 2) + private String author = "not specified"; + private int year; + private String publisher = "not specified"; + @ImportantField(priority = 4) + private double cost = 0.00; + + public Book(String title) { + this.title = title; + } + + public void printImportant() throws IllegalAccessException { + ArrayList importantFields = new ArrayList<>(); + for (Field field : this.getClass().getDeclaredFields()) { + if (field.isAnnotationPresent(ImportantField.class)) { + importantFields.add(field); + } + } + FieldPriorityComparator comparator = new FieldPriorityComparator(); + importantFields.sort(comparator); + for (Field field : importantFields) { + System.out.println(field.getName() + ": " + field.get(this) + ";"); + } + } + +} diff --git a/src/main/java/homework_4/custom_annotation/FieldPriorityComparator.java b/src/main/java/homework_4/custom_annotation/FieldPriorityComparator.java new file mode 100644 index 00000000..96449f26 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/FieldPriorityComparator.java @@ -0,0 +1,15 @@ +package homework_4.custom_annotation; + +import java.lang.reflect.Field; +import java.util.Comparator; + +public class FieldPriorityComparator implements Comparator { + + @Override + public int compare(Field f1, Field f2) { + int priority1 = f1.getDeclaredAnnotation(ImportantField.class).priority(); + int priority2 = f2.getDeclaredAnnotation(ImportantField.class).priority(); + return priority1 - priority2; + } + +} diff --git a/src/main/java/homework_4/custom_annotation/ImportantField.java b/src/main/java/homework_4/custom_annotation/ImportantField.java new file mode 100644 index 00000000..941d62a0 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/ImportantField.java @@ -0,0 +1,18 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; + +//аннотация отмечает поля класса как важные +//priority - приоритет поля при выводе + +@Retention(RetentionPolicy.RUNTIME) +@Target(FIELD) +public @interface ImportantField { + + int priority(); + +} diff --git a/src/main/java/homework_4/custom_annotation/Main.java b/src/main/java/homework_4/custom_annotation/Main.java new file mode 100644 index 00000000..70d3b132 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Main.java @@ -0,0 +1,13 @@ +package homework_4.custom_annotation; + +public class Main { + + public static void main(String[] args) throws IllegalAccessException { + Book book = new Book("My Book"); + book.setAuthor("Someone"); + book.setGenre("fantasy"); + book.setCost(300.0); + book.printImportant(); + } + +} diff --git a/src/test/java/homework_4/ImportantFieldTest.java b/src/test/java/homework_4/ImportantFieldTest.java new file mode 100644 index 00000000..35d1726b --- /dev/null +++ b/src/test/java/homework_4/ImportantFieldTest.java @@ -0,0 +1,57 @@ +package homework_4; + +import homework_4.custom_annotation.Book; +import homework_4.custom_annotation.ImportantField; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ImportantFieldTest extends base.UnitBase { + + private Book book; + + @BeforeEach + void init() { + book = new Book("Some book"); + } + + @Test + void annotationTest() throws NoSuchFieldException { + ArrayList importantFields = new ArrayList<>(); + for (Field field : book.getClass().getDeclaredFields()) { + if (field.isAnnotationPresent(ImportantField.class)) { + importantFields.add(field); + } + } + + assertEquals(4, importantFields.size()); + assertEquals(1, book.getClass().getDeclaredField("title") + .getAnnotation(ImportantField.class).priority()); + assertEquals(2, book.getClass().getDeclaredField("author") + .getAnnotation(ImportantField.class).priority()); + assertEquals(3, book.getClass().getDeclaredField("genre") + .getAnnotation(ImportantField.class).priority()); + assertEquals(4, book.getClass().getDeclaredField("cost") + .getAnnotation(ImportantField.class).priority()); + } + + @Test + void printImportantTest() throws IllegalAccessException { + book.setCost(300.0); + + book.printImportant(); + printOut(); + + assertEquals(4, getOutputLines().length); + assertEquals("title: Some book;", getOutputLines()[0]); + assertTrue(getOutputLines()[1].contains("author")); + assertTrue(getOutputLines()[2].contains("genre")); + assertEquals("cost: 300.0;", getOutputLines()[3]); + } + +} From bf3d4c66bf3b0edb78d6240081aa852f41dc5460 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 14 Aug 2021 06:38:54 +0300 Subject: [PATCH 33/55] README add HW4 --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index fd95ce48..09e8d253 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,10 @@ | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table/RandomCharsTable.java) | The app that prints a table of random chars and finds odd or even letters in it. | | HW2 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_2) | Tests for homework 2. | | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_3/ImmutableCat.java) | To create an immutable class and write its requirements in comments. | +| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/custom_file_reader) | The app that reads data from file and prints it to the console. | +| HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/singleton) | Singleton design pattern implementation. | +| HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/custom_annotation) | Annotation. | +| HW4 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_4) | Tests for homework 4. | [Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) From 84e00e4151990f808a0fd14c69f7a930c69ce19a Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 14 Aug 2021 06:55:09 +0300 Subject: [PATCH 34/55] HW2 style update --- .../java/homework_2/random_chars_table/RandomCharsTable.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 13d4b8e2..1a368d5f 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -8,7 +8,7 @@ public class RandomCharsTable { private boolean isEven; - int rows, columns; + private int rows, columns; private char[][] randomCharsTable; private final ArrayList selectedChars = new ArrayList<>(); @@ -46,7 +46,7 @@ private boolean validation() { private void findSelectedChars() { for (char[] row : randomCharsTable) { for (char ch : row) { - if ((isEven && (int) ch % 2 == 0) || (!isEven && (int) ch % 2 == 1)) { + if ((isEven && ch % 2 == 0) || (!isEven && ch % 2 == 1)) { selectedChars.add(ch); } } From 7e5b2a3c9490d282b8bfd36bd088beb17abf8346 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 22 Aug 2021 18:34:14 +0300 Subject: [PATCH 35/55] HW5 PowerOfNumber done --- .../java/homework_5/power_of_number/Main.java | 10 ++ .../power_of_number/PowerOfNumber.java | 55 +++++++++++ .../java/homework_5/PowerOfNumberTest.java | 98 +++++++++++++++++++ 3 files changed, 163 insertions(+) create mode 100644 src/main/java/homework_5/power_of_number/Main.java create mode 100644 src/main/java/homework_5/power_of_number/PowerOfNumber.java create mode 100644 src/test/java/homework_5/PowerOfNumberTest.java diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..737b1d9e --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,10 @@ +package homework_5.power_of_number; + +public class Main { + + public static void main(String[] args) { + PowerOfNumber pon = new PowerOfNumber(); + pon.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..21c0e2cb --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,55 @@ +package homework_5.power_of_number; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.regex.Pattern; + +public class PowerOfNumber { + + private int number; + private int power; + + public void run() { + System.out.println("Please, input number and power."); + if (validation()) { + System.out.println(numberToPower(number, power)); + } else { + System.out.println("Only 2 non-negative integers are allowed"); + } + } + + private int numberToPower(int number, int power) { + if (power == 0) { + return 1; + } + return number * numberToPower(number, power - 1); + } + + private boolean validation() { + try { + String inputLine = readInputData(); + if (inputLine == null) { + return false; + } + inputLine = inputLine.trim(); + if (!Pattern.matches("\\d+\\s\\d+", inputLine)) { + return false; + } + String[] values = inputLine.split(" "); + number = Integer.parseInt(values[0]); + power = Integer.parseInt(values[1]); + } catch (IOException | NumberFormatException e) { + e.printStackTrace(); + return false; + } + return true; + } + + private String readInputData() throws IOException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } + } + +} diff --git a/src/test/java/homework_5/PowerOfNumberTest.java b/src/test/java/homework_5/PowerOfNumberTest.java new file mode 100644 index 00000000..527955c6 --- /dev/null +++ b/src/test/java/homework_5/PowerOfNumberTest.java @@ -0,0 +1,98 @@ +package homework_5; + +import homework_5.power_of_number.PowerOfNumber; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +public class PowerOfNumberTest extends base.UnitBase { + + private final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; + + @Test + void negativeInputTest() { + setInput("-2 4"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please, input number and power."); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void moreArgumentsTest() { + setInput("2 1 8"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please, input number and power."); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void oneArgumentTest() { + setInput("5"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please, input number and power."); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void noArgumentsTest() { + setInput(" "); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please, input number and power."); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void stringInputTest() { + setInput("string input"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please, input number and power."); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCases") + void calculationTest(String input, String expected) { + setInput(input); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please, input number and power."); + + assertEquals(expected, getOutput()); + } + + public static Stream testCases() { + return Stream.of( + arguments("2 2", "4"), + arguments("2 1", "2"), + arguments("4 0", "1"), + arguments("0 17", "0"), + arguments("3 5", "243"), + arguments("2 10", "1024"), + arguments("10 4", "10000"), + arguments("7 3", "343") + ); + } + +} From 123c6b4a2505140ccd94c7afbac95cc985e1505d Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 22 Aug 2021 18:39:28 +0300 Subject: [PATCH 36/55] HW5 PowerOfNumber fix --- .../custom_regex_matcher/CustomRegexMatcher.java | 7 +++++++ src/test/java/homework_5/PowerOfNumberTest.java | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..9447295e --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class CustomRegexMatcher { + + + +} diff --git a/src/test/java/homework_5/PowerOfNumberTest.java b/src/test/java/homework_5/PowerOfNumberTest.java index 527955c6..c675aa3b 100644 --- a/src/test/java/homework_5/PowerOfNumberTest.java +++ b/src/test/java/homework_5/PowerOfNumberTest.java @@ -50,7 +50,7 @@ void oneArgumentTest() { @Test void noArgumentsTest() { - setInput(" "); + setInput(""); new PowerOfNumber().run(); printOut(); From 73191e140e882288dcb866965f69c85200984580 Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 23 Aug 2021 00:32:41 +0300 Subject: [PATCH 37/55] HW5 CustomRegexMatcher done --- .../CustomRegexMatcher.java | 24 +++++++ .../homework_5/custom_regex_matcher/Main.java | 10 +++ .../homework_5/CustomRegexMatcherTest.java | 69 +++++++++++++++++++ 3 files changed, 103 insertions(+) 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/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java index 9447295e..646f0317 100644 --- a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -1,7 +1,31 @@ package homework_5.custom_regex_matcher; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.regex.Pattern; + public class CustomRegexMatcher { + private final String javaFolder = "(java(\\/\\w+)*\\/[A-Z][a-z, A-Z, \\d]*\\.java)"; + private final String regex = "src\\/(main\\/(" + javaFolder + "|resources\\/\\w+(\\.[a-z]+)?)|test\\/" + javaFolder + ")"; + + public void run() { + System.out.println("Regex for a file path in java project starting in src/\n" + + "Example: src/main/java/package_1/Class1.java"); + System.out.println(match()); + } + private boolean match() { + return Pattern.matches(regex, readString()); + } + private String readString() { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } } 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..4dddddc1 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,10 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + CustomRegexMatcher crm = new CustomRegexMatcher(); + crm.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..8c968446 --- /dev/null +++ b/src/test/java/homework_5/CustomRegexMatcherTest.java @@ -0,0 +1,69 @@ +package homework_5; + +import homework_5.custom_regex_matcher.CustomRegexMatcher; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +public class CustomRegexMatcherTest extends base.UnitBase { + + private final String START_MESSAGE = "Regex for a file path in java project starting in src/\n" + + "Example: src/main/java/package_1/Class1.java"; + + @ParameterizedTest + @MethodSource("validTestCases") + void validInputTest(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("true", getOutput()); + } + + @ParameterizedTest + @MethodSource("invalidTestCases") + void invalidInputTest(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("false", getOutput()); + } + + public static Stream validTestCases() { + return Stream.of( + arguments("src/main/java/package_1/MyClass.java"), + arguments("src/main/java/package_1/subpackage/MyClass.java"), + arguments("src/main/java/MyClass.java"), + arguments("src/main/resources/my_file"), + arguments("src/main/resources/File.txt"), + arguments("src/main/resources/some_file.html"), + arguments("src/test/java/package_1/MyClassTest.java"), + arguments("src/main/java/package_1/subpackage/MyClassTest.java"), + arguments("src/main/java/MyTest.java") + ); + } + + public static Stream invalidTestCases() { + return Stream.of( + arguments("string"), + arguments("src/main/java/myClass.java"), + arguments("src/main/java/my_package.java/MyClass.java"), + arguments("src/main/resources/file.txt.html"), + arguments("src//main/java/package_1/subpackage/MyClass.java"), + arguments("src/main/java/package_1/subpackage/MyClassTest"), + arguments("src/main/java/package_1/subpackage/"), + arguments("src/main/resources/") + ); + } + +} From 36a3eee2e2dc163e2238abd9624b77f5f7b862be Mon Sep 17 00:00:00 2001 From: Waranko Date: Mon, 23 Aug 2021 00:34:26 +0300 Subject: [PATCH 38/55] HW5 PowerOfNumberTest fix --- src/test/java/homework_5/PowerOfNumberTest.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/test/java/homework_5/PowerOfNumberTest.java b/src/test/java/homework_5/PowerOfNumberTest.java index c675aa3b..38676da6 100644 --- a/src/test/java/homework_5/PowerOfNumberTest.java +++ b/src/test/java/homework_5/PowerOfNumberTest.java @@ -13,6 +13,7 @@ public class PowerOfNumberTest extends base.UnitBase { + private final String START_MESSAGE = "Please, input number and power."; private final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; @Test @@ -21,7 +22,7 @@ void negativeInputTest() { new PowerOfNumber().run(); printOut(); - removeFromOutput("Please, input number and power."); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } @@ -32,7 +33,7 @@ void moreArgumentsTest() { new PowerOfNumber().run(); printOut(); - removeFromOutput("Please, input number and power."); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } @@ -43,7 +44,7 @@ void oneArgumentTest() { new PowerOfNumber().run(); printOut(); - removeFromOutput("Please, input number and power."); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } @@ -54,7 +55,7 @@ void noArgumentsTest() { new PowerOfNumber().run(); printOut(); - removeFromOutput("Please, input number and power."); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } @@ -65,7 +66,7 @@ void stringInputTest() { new PowerOfNumber().run(); printOut(); - removeFromOutput("Please, input number and power."); + removeFromOutput(START_MESSAGE); assertEquals(ERROR_MESSAGE, getOutput()); } @@ -77,7 +78,7 @@ void calculationTest(String input, String expected) { new PowerOfNumber().run(); printOut(); - removeFromOutput("Please, input number and power."); + removeFromOutput(START_MESSAGE); assertEquals(expected, getOutput()); } From 4f126e81c2ab89b9e443928d8cbbcdefad01b308 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 2 Sep 2021 15:53:04 +0300 Subject: [PATCH 39/55] HW6 done --- src/main/java/homework_6/Main.java | 30 ++++++++++++++++ .../MapProblemsCollisionGenerator.java | 34 +++++++++++++++++++ .../MapProblemsMutableGenerator.java | 34 +++++++++++++++++++ 3 files changed, 98 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/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..8e8e6567 --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,30 @@ +package homework_6; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + + public static void main(String[] args) { + mapCollisionProblems(); + mapMutableProblems(); + } + + public static void mapCollisionProblems() { + MapProblemsCollisionGenerator mpcg1 = new MapProblemsCollisionGenerator("Generator 1"); + MapProblemsCollisionGenerator mpcg2 = new MapProblemsCollisionGenerator("Generator 2"); + Map collisionMap = new HashMap<>(); + collisionMap.put(mpcg1, 1); + collisionMap.put(mpcg2, 2); + System.out.println(collisionMap.toString()); + } + + public static void mapMutableProblems() { + MapProblemsMutableGenerator mpmg1 = new MapProblemsMutableGenerator(1000); + Map mutableKeyMap = new HashMap<>(); + mutableKeyMap.put(mpmg1, 1000); + mpmg1.setGeneratorID(2000); + System.out.println(mutableKeyMap.containsKey(mpmg1)); + } + +} diff --git a/src/main/java/homework_6/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..7eb62b6c --- /dev/null +++ b/src/main/java/homework_6/MapProblemsCollisionGenerator.java @@ -0,0 +1,34 @@ +package homework_6; + +public class MapProblemsCollisionGenerator { + + private final String generatorName; + + public MapProblemsCollisionGenerator(String generatorName) { + this.generatorName = generatorName; + } + + @Override + public int hashCode() { + return 1234; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (obj.getClass() == this.getClass()) { + return false; + } + return this.generatorName.equals(((MapProblemsCollisionGenerator) obj).generatorName); + } + + @Override + public String toString() { + return generatorName; + } +} diff --git a/src/main/java/homework_6/MapProblemsMutableGenerator.java b/src/main/java/homework_6/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..fd7803ad --- /dev/null +++ b/src/main/java/homework_6/MapProblemsMutableGenerator.java @@ -0,0 +1,34 @@ +package homework_6; + +public class MapProblemsMutableGenerator { + + private int generatorID; + + public MapProblemsMutableGenerator(int generatorID) { + this.generatorID = generatorID; + } + + public void setGeneratorID(int generatorID) { + this.generatorID = generatorID; + } + + @Override + public int hashCode() { + return Integer.hashCode(generatorID); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (obj.getClass() == this.getClass()) { + return false; + } + return this.generatorID == ((MapProblemsMutableGenerator) obj).generatorID; + } + +} From 03f127857c32c08269bc06e6addaa8f59d25d878 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 2 Sep 2021 16:00:21 +0300 Subject: [PATCH 40/55] README.md update --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 09e8d253..7ce974de 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ | HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/singleton) | Singleton design pattern implementation. | | HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/custom_annotation) | Annotation. | | HW4 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_4) | Tests for homework 4. | +| HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_5/custom_regex_mathcer) | The app that checks if input string matches pattern. | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_5/power_of_number) | The app that calculates a number in a power using recursion. | +| HW5 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_5) | Tests for homework 5. | +| HW6 | [MapProblemsCollisionGenerator & MapProblemMutableGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_6) | Classes that create problems in HashMap. | [Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) From 934190a1f8be709c857b5ee55880a6ee8c61e459 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 2 Sep 2021 18:49:15 +0300 Subject: [PATCH 41/55] HW2 style fix --- .../pyramid_printer/PyramidPrinter.java | 30 ++++++--- .../random_chars_table/RandomCharsTable.java | 67 ++++++++++--------- .../traffic_light/TrafficLight.java | 39 ++++++++--- .../traffic_light/TrafficLightExtraMode.java | 41 +++++++----- .../homework_2/TrafficLightExtraModeTest.java | 2 +- .../java/homework_2/TrafficLightTest.java | 2 +- 6 files changed, 113 insertions(+), 68 deletions(-) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 744cd012..55e04fc5 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,27 +6,39 @@ public class PyramidPrinter { - private int pyramidSize; - public void run() { System.out.println("Please, input number:"); - if (validation()) { - printPyramid(); + String input = setInput(); + if (isValid(input)) { + printPyramid(Integer.parseInt(input)); } else { System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } } - private boolean validation() { - try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { - pyramidSize = Integer.parseInt(br.readLine()); - } catch (NumberFormatException | IOException ex) { + protected String setInput() { + try(BufferedReader br = + new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + private boolean isValid(String inputString) { + if(inputString == null) { + return false; + } + int pyramidSize; + try { + pyramidSize = Integer.parseInt(inputString); + } catch (NumberFormatException ex) { return false; } return pyramidSize >= 0; } - private void printPyramid() { + private void printPyramid(int pyramidSize) { for (int i = 1; i <= pyramidSize; i++) { for (int j = 1; j <= i; j++) { System.out.print("x"); 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 1a368d5f..c2f58e05 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -7,54 +7,61 @@ public class RandomCharsTable { - private boolean isEven; - private int rows, columns; - private char[][] randomCharsTable; - private final ArrayList selectedChars = new ArrayList<>(); - public void run() { System.out.println("Please, enter array length, array width and strategy (odd or even):"); - if (validation()) { - randomCharsTable = new RandomCharsTableCreator(rows, columns).createTable(); - findSelectedChars(); - printTable(); - printSelection(); + String input = setInput(); + if (isValid(input)) { + char[][] randomCharsTable = new RandomCharsTableCreator(getRows(input), getColumns(input)).createTable(); + ArrayList selectedChars = findSelectedChars(randomCharsTable, isEven(input)); + printTable(randomCharsTable); + printSelection(selectedChars, isEven(input)); } else { System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } } - private boolean validation() { - try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { - String[] inputValues = br.readLine().split(" "); - if (inputValues.length != 3) { - return false; - } - rows = Integer.parseInt(inputValues[0]); - columns = Integer.parseInt(inputValues[1]); - if (rows <= 0 || columns <= 0 || - (!inputValues[2].equals("even") && !inputValues[2].equals("odd"))) { - return false; - } - isEven = inputValues[2].equals("even"); - } catch (IOException | NumberFormatException e) { + protected String setInput() { + try(BufferedReader br = + new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + private boolean isValid(String inputString) { + if(inputString == null) { return false; } - return true; + return inputString.matches("\\d+ \\d+ (odd|even)"); + } + + private int getRows(String inputString) { + return Integer.parseInt(inputString.split(" ")[0]); + } + + private int getColumns(String inputString) { + return Integer.parseInt(inputString.split(" ")[1]); + } + + private boolean isEven(String inputString) { + return inputString.split(" ")[2].equals("even"); } - private void findSelectedChars() { - for (char[] row : randomCharsTable) { + private ArrayList findSelectedChars(char[][] table, boolean isEven) { + ArrayList selectedChars = new ArrayList<>(); + for (char[] row : table) { for (char ch : row) { if ((isEven && ch % 2 == 0) || (!isEven && ch % 2 == 1)) { selectedChars.add(ch); } } } + return selectedChars; } - private void printTable() { - for (char[] row : randomCharsTable) { + private void printTable(char[][] table) { + for (char[] row : table) { System.out.print("|"); for (char ch : row) { System.out.print(ch + "|"); @@ -63,7 +70,7 @@ private void printTable() { } } - private void printSelection() { + private void printSelection(ArrayList selectedChars, boolean isEven) { if (isEven) { System.out.print("Even letters - "); } else { diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 19056462..0b1d0c98 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -10,28 +10,43 @@ public class TrafficLight { private static final String RED = "\u001B[31m"; private static final String YELLOW = "\u001B[33m"; private static final String GREEN = "\u001B[32m"; - protected int seconds; public void run() { System.out.println("Please, input time:"); - if (validation()) { - printColor(); + String input = setInput(); + if (isValid(input)) { + int seconds = getSeconds(input); + printColor(seconds); } else { printErrorMessage(); } } - protected boolean validation() { - try (BufferedReader br = - new BufferedReader(new InputStreamReader(System.in))) { - seconds = Integer.parseInt(br.readLine()); - } catch (IOException | NumberFormatException e) { + protected String setInput() { + try(BufferedReader br = + new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + protected boolean isValid(String inputString) { + if(inputString == null) { return false; } - return seconds >= 0 && seconds <= 86399; + return inputString.matches("\\d+"); + } + + protected int getSeconds(String inputValue) { + return Integer.parseInt(inputValue); } - private void printColor() { + private void printColor(int seconds) { + if (isDayOver(seconds)) { + System.out.println("day is over"); + return; + } if (seconds % 60 < 35) { System.out.println(GREEN + "GREEN" + RESET); } else if (seconds % 60 < 40 || seconds % 60 >= 55) { @@ -41,6 +56,10 @@ private void printColor() { } } + protected boolean isDayOver(int seconds) { + return seconds > 86399; + } + protected void printErrorMessage() { System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index 3952d262..d3e18457 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -1,36 +1,43 @@ package homework_2.traffic_light; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - public class TrafficLightExtraMode extends TrafficLight { @Override - protected boolean validation() { - try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { - String input = br.readLine(); - if (!input.contains(":")) { - return false; - } - String[] time = input.split(":"); - if (time.length != 3) { - return false; - } + protected boolean isValid(String inputString) { + if(inputString == null) { + return false; + } + if (!inputString.contains(":")) { + return false; + } + String[] time = inputString.split(":"); + if (time.length != 3) { + return false; + } + try { int hours = Integer.parseInt(time[0]); int minutes = Integer.parseInt(time[1]); - seconds = Integer.parseInt(time[2]); - if ((hours < 0 || hours > 23) + int seconds = Integer.parseInt(time[2]); + if ((hours < 0) || (minutes < 0 || minutes > 59) || (seconds < 0 || seconds > 59)) { return false; } - } catch (IOException | NumberFormatException e) { + } catch (NumberFormatException e) { return false; } return true; } + @Override + protected int getSeconds(String inputString) { + String[] time = inputString.split(":"); + int hours = Integer.parseInt(time[0]); + int minutes = Integer.parseInt(time[1]); + int seconds = Integer.parseInt(time[2]); + return hours * 60 * 60 + minutes * 60 + seconds; + } + @Override protected void printErrorMessage() { System.out.println("Only input in format hh:mm:ss is allowed"); diff --git a/src/test/java/homework_2/TrafficLightExtraModeTest.java b/src/test/java/homework_2/TrafficLightExtraModeTest.java index 382cb176..8c4b9239 100644 --- a/src/test/java/homework_2/TrafficLightExtraModeTest.java +++ b/src/test/java/homework_2/TrafficLightExtraModeTest.java @@ -91,7 +91,7 @@ void tooBigInputTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(ERROR_MESSAGE, getOutput()); + assertEquals("day is over", getOutput()); } @Test diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java index e3e9236b..740587d4 100644 --- a/src/test/java/homework_2/TrafficLightTest.java +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -63,7 +63,7 @@ void tooBigInputTest() { printOut(); removeFromOutput(START_MESSAGE); - assertEquals(ERROR_MESSAGE, getOutput()); + assertEquals("day is over", getOutput()); } @Test From a7bcd75679b89fffc8f9f728a1041d075a3c73f7 Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 2 Sep 2021 19:12:19 +0300 Subject: [PATCH 42/55] HW5 PowerOfNumber validation fix --- .../power_of_number/PowerOfNumber.java | 39 ++++++++----------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java index 21c0e2cb..75f6dd98 100644 --- a/src/main/java/homework_5/power_of_number/PowerOfNumber.java +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -7,13 +7,11 @@ public class PowerOfNumber { - private int number; - private int power; - public void run() { System.out.println("Please, input number and power."); - if (validation()) { - System.out.println(numberToPower(number, power)); + String input = setInput(); + if (isValid(input)) { + System.out.println(numberToPower(getNumber(input), getPower(input))); } else { System.out.println("Only 2 non-negative integers are allowed"); } @@ -26,29 +24,26 @@ private int numberToPower(int number, int power) { return number * numberToPower(number, power - 1); } - private boolean validation() { - try { - String inputLine = readInputData(); - if (inputLine == null) { - return false; - } - inputLine = inputLine.trim(); - if (!Pattern.matches("\\d+\\s\\d+", inputLine)) { - return false; - } - String[] values = inputLine.split(" "); - number = Integer.parseInt(values[0]); - power = Integer.parseInt(values[1]); - } catch (IOException | NumberFormatException e) { - e.printStackTrace(); + private boolean isValid(String inputString) { + if(inputString == null) { return false; } - return true; + return Pattern.matches("\\d+\\s\\d+", inputString); + } + + private int getNumber(String inputString) { + return Integer.parseInt(inputString.split(" ")[0]); + } + + private int getPower(String inputString) { + return Integer.parseInt(inputString.split(" ")[1]); } - private String readInputData() throws IOException { + private String setInput() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { return br.readLine(); + } catch (IOException e) { + return null; } } From 171ccfbd1a1a7e46ae5721a2eb3bb53219e4ad1f Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 12 Sep 2021 20:41:00 +0300 Subject: [PATCH 43/55] HW7 done --- src/main/java/homework_7/Cat.java | 35 +++++++++++++++++++ src/main/java/homework_7/Kitten.java | 31 ++++++++++++++++ .../java/homework_7/KittenToCatFunction.java | 7 ++++ src/main/java/homework_7/Main.java | 14 ++++++++ .../homework_7/KittenToCatFunctionTest.java | 23 ++++++++++++ 5 files changed, 110 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/KittenToCatFunction.java create mode 100644 src/main/java/homework_7/Main.java create mode 100644 src/test/java/homework_7/KittenToCatFunctionTest.java diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..624e6c47 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,35 @@ +package homework_7; + +public class Cat { + + private final String name; + private final double weight; + private final int whiskersLength; + + public Cat(String name, double weight, int whiskersLength) { + this.name = name; + this.weight = weight; + this.whiskersLength = whiskersLength; + } + + public String getName() { + return name; + } + + public double getWeight() { + return weight; + } + + public int getWhiskersLength() { + return whiskersLength; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", weight=" + weight + + ", whiskers length=" + whiskersLength + + '}'; + } +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..e9b29c8a --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,31 @@ +package homework_7; + +public class Kitten { + + private final String name; + private final double weight; + private final int whiskersLength; + + public Kitten(String name, double weight, int whiskersLength) { + this.name = name; + this.weight = weight; + this.whiskersLength = whiskersLength; + } + + public String getName() { + return name; + } + + public double getWeight() { + return weight; + } + + @Override + public String toString() { + return "Kitten{" + + "name='" + name + '\'' + + ", weight=" + weight + + ", whiskersLength=" + whiskersLength + + '}'; + } +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..cf029011 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,7 @@ +package homework_7; + +public interface KittenToCatFunction { + + Cat grow(Kitten kitten); + +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..801fb0f7 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,14 @@ +package homework_7; + +public class Main { + + public static void main(String[] args) { + Kitten barsik = new Kitten("Barsik", 2.5, 4); + System.out.println(barsik.toString()); + + KittenToCatFunction ktc = kitten -> new Cat(kitten.getName(), kitten.getWeight() + 3, 10); + + Cat grownUpBarsik = ktc.grow(barsik); + System.out.println(grownUpBarsik.toString()); + } +} diff --git a/src/test/java/homework_7/KittenToCatFunctionTest.java b/src/test/java/homework_7/KittenToCatFunctionTest.java new file mode 100644 index 00000000..9c7cc7ad --- /dev/null +++ b/src/test/java/homework_7/KittenToCatFunctionTest.java @@ -0,0 +1,23 @@ +package homework_7; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class KittenToCatFunctionTest { + + private KittenToCatFunction ktc = kitten -> new Cat(kitten.getName(), kitten.getWeight() + 3, 10); + + @Test + public void interfaceTest() { + Kitten barsik = new Kitten("Barsik", 2.5, 4); + + Cat grownUpBarsik = ktc.grow(barsik); + + assertEquals(Cat.class, grownUpBarsik.getClass()); + assertEquals(barsik.getName(), grownUpBarsik.getName()); + assertEquals(barsik.getWeight() + 3, grownUpBarsik.getWeight()); + assertEquals(10, grownUpBarsik.getWhiskersLength()); + } + +} From 2297a5d07a40785d52083e45816a969e511ec984 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sun, 12 Sep 2021 20:45:23 +0300 Subject: [PATCH 44/55] README.md update --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7ce974de..ce2a70f7 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,18 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java) | The app that reads pyramid size and prints pyramid of 'x' of given size. | | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table/RandomCharsTable.java) | The app that prints a table of random chars and finds odd or even letters in it. | -| HW2 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_2) | Tests for homework 2. | +| HW2 | [Tests 2](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_2) | Tests for homework 2. | | HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_3/ImmutableCat.java) | To create an immutable class and write its requirements in comments. | | HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/custom_file_reader) | The app that reads data from file and prints it to the console. | | HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/singleton) | Singleton design pattern implementation. | | HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/custom_annotation) | Annotation. | -| HW4 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_4) | Tests for homework 4. | +| HW4 | [Tests 4](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_4) | Tests for homework 4. | | HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_5/custom_regex_mathcer) | The app that checks if input string matches pattern. | | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_5/power_of_number) | The app that calculates a number in a power using recursion. | -| HW5 | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_5) | Tests for homework 5. | +| HW5 | [Tests 5](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_5) | Tests for homework 5. | | HW6 | [MapProblemsCollisionGenerator & MapProblemMutableGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_6) | Classes that create problems in HashMap. | +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_7) | The functional interface with an abstract method that turns a Kitten to a Cat. | +| HW7 | [Tests 7](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_7) | Tests for homework 7. | [Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) From 59a2f5ea522e66e14a1af72506345f4cc9937f8b Mon Sep 17 00:00:00 2001 From: Waranko Date: Fri, 17 Sep 2021 01:06:01 +0300 Subject: [PATCH 45/55] SeaBattle done --- src/main/java/course_project/Main.java | 11 +++ .../java/course_project/enums/CellStatus.java | 10 ++ .../java/course_project/enums/Response.java | 10 ++ .../java/course_project/objects/Cell.java | 36 +++++++ .../java/course_project/objects/GameData.java | 66 +++++++++++++ .../java/course_project/objects/Move.java | 30 ++++++ .../objects/fields/ComputerField.java | 73 ++++++++++++++ .../course_project/objects/fields/Field.java | 29 ++++++ .../objects/fields/UserField.java | 65 +++++++++++++ .../course_project/services/GameService.java | 64 ++++++++++++ .../course_project/services/InputService.java | 26 +++++ .../services/MoveGenerator.java | 64 ++++++++++++ .../services/ShipLocationGenerator.java | 94 ++++++++++++++++++ .../course_project/services/UserService.java | 97 +++++++++++++++++++ 14 files changed, 675 insertions(+) create mode 100644 src/main/java/course_project/Main.java create mode 100644 src/main/java/course_project/enums/CellStatus.java create mode 100644 src/main/java/course_project/enums/Response.java create mode 100644 src/main/java/course_project/objects/Cell.java create mode 100644 src/main/java/course_project/objects/GameData.java create mode 100644 src/main/java/course_project/objects/Move.java create mode 100644 src/main/java/course_project/objects/fields/ComputerField.java create mode 100644 src/main/java/course_project/objects/fields/Field.java create mode 100644 src/main/java/course_project/objects/fields/UserField.java create mode 100644 src/main/java/course_project/services/GameService.java create mode 100644 src/main/java/course_project/services/InputService.java create mode 100644 src/main/java/course_project/services/MoveGenerator.java create mode 100644 src/main/java/course_project/services/ShipLocationGenerator.java create mode 100644 src/main/java/course_project/services/UserService.java diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..ed7ee7aa --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +import course_project.services.GameService; + +public class Main { + + public static void main(String[] args) { + new GameService().run(); + } + +} diff --git a/src/main/java/course_project/enums/CellStatus.java b/src/main/java/course_project/enums/CellStatus.java new file mode 100644 index 00000000..f7ba7d79 --- /dev/null +++ b/src/main/java/course_project/enums/CellStatus.java @@ -0,0 +1,10 @@ +package course_project.enums; + +public enum CellStatus { + + FREE, + HAS_SHIP, + VISITED, + NOT_VISITED + +} diff --git a/src/main/java/course_project/enums/Response.java b/src/main/java/course_project/enums/Response.java new file mode 100644 index 00000000..e5399a0a --- /dev/null +++ b/src/main/java/course_project/enums/Response.java @@ -0,0 +1,10 @@ +package course_project.enums; + +public enum Response { + + MISSED, + HIT, + KILLED, + VISITED + +} diff --git a/src/main/java/course_project/objects/Cell.java b/src/main/java/course_project/objects/Cell.java new file mode 100644 index 00000000..2d54d1dc --- /dev/null +++ b/src/main/java/course_project/objects/Cell.java @@ -0,0 +1,36 @@ +package course_project.objects; + +import course_project.enums.CellStatus; + +import static course_project.enums.CellStatus.FREE; +import static course_project.enums.CellStatus.HAS_SHIP; + +public class Cell { + + private final CellStatus status; + private final boolean gotShip; + + public Cell(CellStatus status, boolean gotShip) { + this.status = status; + this.gotShip = gotShip; + } + + public CellStatus getStatus() { + return status; + } + + public boolean hadShip() { + return gotShip; + } + + @Override + public String toString() { + if (status == FREE) { + return " "; + } + if (status == HAS_SHIP) { + return "X"; + } + return "."; + } +} diff --git a/src/main/java/course_project/objects/GameData.java b/src/main/java/course_project/objects/GameData.java new file mode 100644 index 00000000..079bb0e3 --- /dev/null +++ b/src/main/java/course_project/objects/GameData.java @@ -0,0 +1,66 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.Move; +import course_project.objects.fields.ComputerField; +import course_project.objects.fields.Field; +import course_project.objects.fields.UserField; +import course_project.services.ShipLocationGenerator; + +import java.util.List; + +public class GameData { + + private final ComputerField computerField; + private final UserField userField; + private int computerShips = 10; + private int userShips = 10; + + public GameData() { + computerField = new ComputerField(); + userField = new UserField(); + new ShipLocationGenerator().generateShips(computerField); + } + + public Field getComputerField() { + return computerField; + } + + public Field getUserField() { + return userField; + } + + public int getComputerShips() { + return computerShips; + } + + public int getUserShips() { + return userShips; + } + + public Response getResponseFromComputer(Move move) { + Response response = computerField.getResponse(move); + if (response == Response.KILLED) { + computerShips--; + } + return response; + } + + public void saveComputerMoveResult(Response response, Move move, List lastHit) { + if (response == Response.KILLED) { + userField.setVisitedAroundShip(lastHit); + userShips--; + } + userField.setCellStatus(move.getX(), move.getY(), CellStatus.VISITED); + } + + public boolean isUserFleetEmpty() { + return userShips == 0; + } + + public boolean isComputerFleetEmpty() { + return computerShips == 0; + } + +} diff --git a/src/main/java/course_project/objects/Move.java b/src/main/java/course_project/objects/Move.java new file mode 100644 index 00000000..7b1114a7 --- /dev/null +++ b/src/main/java/course_project/objects/Move.java @@ -0,0 +1,30 @@ +package course_project.objects; + +public class Move { + + private final int x; + private final int y; + + public Move(int x, int y) { + this.x = x; + this.y = y; + } + + public Move(String move) { + x = move.charAt(0) - 65; + y = Integer.parseInt(move.substring(1)) - 1; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + @Override + public String toString() { + return String.valueOf((char) (x + 65)) + (y + 1); + } +} diff --git a/src/main/java/course_project/objects/fields/ComputerField.java b/src/main/java/course_project/objects/fields/ComputerField.java new file mode 100644 index 00000000..94f60f95 --- /dev/null +++ b/src/main/java/course_project/objects/fields/ComputerField.java @@ -0,0 +1,73 @@ +package course_project.objects.fields; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.Cell; +import course_project.objects.Move; +import course_project.objects.fields.Field; + +import java.util.Arrays; + +public class ComputerField extends Field { + + public ComputerField() { + for (Cell[] row : table) { + Arrays.fill(row, new Cell(CellStatus.FREE, false)); + } + } + + public Response getResponse(Move move) { + if (table[move.getX()][move.getY()].getStatus() == CellStatus.FREE) { + table[move.getX()][move.getY()] = new Cell(CellStatus.VISITED, false); + return Response.MISSED; + } + if (table[move.getX()][move.getY()].getStatus() == CellStatus.VISITED) { + return Response.VISITED; + } + if (table[move.getX()][move.getY()].getStatus() == CellStatus.HAS_SHIP) { + table[move.getX()][move.getY()] = new Cell(CellStatus.VISITED, true); + int x = move.getX(); + int y = move.getY(); + if (hasShipAround(x, y)) { + return Response.HIT; + } + int prevX = -1; + int prevY = -1; + while (true) { + if (x != 0 && x - 1 != prevX && table[x - 1][y].getStatus() == CellStatus.VISITED && table[x - 1][y].hadShip()) { + prevX = x; + x--; + continue; + } + if (x + 1 < 10 && x + 1 != prevX && table[x - 1][y].getStatus() == CellStatus.VISITED && table[x + 1][y].hadShip()) { + prevX = x; + x++; + continue; + } + if (y != 0 && y - 1 != prevY && table[x][y - 1].getStatus() == CellStatus.VISITED && table[x][y - 1].hadShip()) { + prevY = y; + y--; + continue; + } + if (y + 1 < 10 && y + 1 != prevY && table[x][y + 1].getStatus() == CellStatus.VISITED && table[x][y + 1].hadShip()) { + prevY = y; + y++; + continue; + } + if (hasShipAround(x, y)) { + return Response.HIT; + } + break; + } + } + return Response.KILLED; + } + + private boolean hasShipAround(int x, int y) { + return (x != 0 && table[x - 1][y].getStatus() == CellStatus.HAS_SHIP) + || (x + 1 < table.length && table[x + 1][y].getStatus() == CellStatus.HAS_SHIP) + || (y != 0 && table[x][y - 1].getStatus() == CellStatus.HAS_SHIP) + || (y + 1 < table[0].length && table[x][y + 1].getStatus() == CellStatus.HAS_SHIP); + } + +} diff --git a/src/main/java/course_project/objects/fields/Field.java b/src/main/java/course_project/objects/fields/Field.java new file mode 100644 index 00000000..655d63d8 --- /dev/null +++ b/src/main/java/course_project/objects/fields/Field.java @@ -0,0 +1,29 @@ +package course_project.objects.fields; + +import course_project.enums.CellStatus; +import course_project.objects.Cell; + +import java.util.Arrays; + +public abstract class Field { + + protected final Cell[][] table = new Cell[10][10]; + + public CellStatus getCellStatus(int x, int y) { + return table[x][y].getStatus(); + } + + public void setCellStatus(int x, int y, CellStatus newStatus) { + if (newStatus == CellStatus.HAS_SHIP) { + table[x][y] = new Cell(newStatus, true); + } else { + table[x][y] = new Cell(newStatus, false); + } + } + + public void printField() { + for (Cell[] row : table) { + System.out.println(Arrays.toString(row)); + } + } +} diff --git a/src/main/java/course_project/objects/fields/UserField.java b/src/main/java/course_project/objects/fields/UserField.java new file mode 100644 index 00000000..635e3c95 --- /dev/null +++ b/src/main/java/course_project/objects/fields/UserField.java @@ -0,0 +1,65 @@ +package course_project.objects.fields; + +import course_project.enums.CellStatus; +import course_project.objects.Cell; +import course_project.objects.Move; +import course_project.objects.fields.Field; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class UserField extends Field { + + public UserField() { + for (Cell[] row : table) { + Arrays.fill(row, new Cell(CellStatus.NOT_VISITED, false)); + } + } + + public void setVisitedAroundShip(List list) { + boolean isSameX = false; + if (list.size() == 1 || list.get(0).getX() == list.get(1).getX()) { + isSameX = true; + } + if (isSameX) { + Comparator byY = Comparator.comparing(Move::getY); + list.sort(byY); + int x = list.get(0).getX(); + int y1 = list.get(0).getY(); + int y2 = list.get(list.size() - 1).getY(); + for (int y = y1 - 1; y <= y2 + 1; y++) { + if (!(0 <= y && y < 10)) { + continue; + } + setCellStatus(x, y, CellStatus.VISITED); + if (x - 1 >= 0) { + setCellStatus(x - 1, y, CellStatus.VISITED); + } + if (x + 1 < 10) { + setCellStatus(x + 1, y, CellStatus.VISITED); + } + } + } else { + Comparator byX = Comparator.comparing(Move::getX); + list.sort(byX); + int y = list.get(0).getY(); + int x1 = list.get(0).getX(); + int x2 = list.get(list.size() - 1).getX(); + for (int x = x1 - 1; x <= x2 + 1; x++) { + if (!(0 <= x && x < 10)) { + continue; + } + setCellStatus(x, y, CellStatus.VISITED); + if (y - 1 >= 0) { + setCellStatus(x, y - 1, CellStatus.VISITED); + } + if (y + 1 < 10) { + setCellStatus(x, y + 1, CellStatus.VISITED); + } + } + } + } + +} diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java new file mode 100644 index 00000000..77bd5f52 --- /dev/null +++ b/src/main/java/course_project/services/GameService.java @@ -0,0 +1,64 @@ +package course_project.services; + +import course_project.enums.Response; +import course_project.objects.GameData; +import course_project.objects.Move; + +import java.util.ArrayList; +import java.util.List; + +public class GameService { + + public void run() { + UserService userService = new UserService(); + userService.printWelcomeMessage(); + GameData data = new GameData(); + processMoves(userService, data); + } + + private void processMoves(UserService userService, GameData data) { + boolean gotWinner = false; + List lastHit = new ArrayList<>(); + while (!gotWinner) { + Response response; + do { + response = processUserMove(userService, data); + userService.printComputerResponse(response); + if (response == Response.KILLED) { + if (data.isComputerFleetEmpty()) { + userService.printUserWinMessageAndExit(); + gotWinner = true; + break; + } + } + } while (response == Response.HIT || response == Response.KILLED || response == Response.VISITED); + if (gotWinner) break; + do { + Move nextMove = MoveGenerator.generate(data.getUserField(), lastHit); + response = processComputerMove(userService, nextMove); + if (response == Response.HIT || response == Response.KILLED) { + lastHit.add(nextMove); + } + data.saveComputerMoveResult(response, nextMove, lastHit); + if (response == Response.KILLED) { + lastHit.clear(); + if (data.isUserFleetEmpty()) { + userService.printComputerWinMessageAndExit(); + data.getComputerField().printField(); + gotWinner = true; + break; + } + } + } while (response == Response.HIT || response == Response.KILLED); + } + } + + private Response processComputerMove(UserService userService, Move move) { + return userService.completeComputerMove(move); + } + + private Response processUserMove(UserService userService, GameData gameData) { + return gameData.getResponseFromComputer(userService.getMove()); + } + +} diff --git a/src/main/java/course_project/services/InputService.java b/src/main/java/course_project/services/InputService.java new file mode 100644 index 00000000..db0fca29 --- /dev/null +++ b/src/main/java/course_project/services/InputService.java @@ -0,0 +1,26 @@ +package course_project.services; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class InputService { + + BufferedReader br; + + public InputService() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + public String getInput() { + try { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + public void closeBuffer() throws IOException { + br.close(); + } +} diff --git a/src/main/java/course_project/services/MoveGenerator.java b/src/main/java/course_project/services/MoveGenerator.java new file mode 100644 index 00000000..0b55f136 --- /dev/null +++ b/src/main/java/course_project/services/MoveGenerator.java @@ -0,0 +1,64 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.fields.Field; +import course_project.objects.Move; + +import java.util.Comparator; +import java.util.List; + +import static java.lang.Math.random; + +public class MoveGenerator { + + public static Move generate(Field userField) { + int x = (int) (random() * 10); + int y = (int) (random() * 10); + while (userField.getCellStatus(x, y) != CellStatus.NOT_VISITED) { + x = (int) (random() * 10); + y = (int) (random() * 10); + } + return new Move(x, y); + } + + public static Move generate(Field userField, List lastHit) { + if (lastHit.size() == 0) { + return generate(userField); + } + int x = lastHit.get(0).getX(); + int y = lastHit.get(0).getY(); + + if (lastHit.size() == 1) { + if (x != 0 && userField.getCellStatus(x - 1, y) == CellStatus.NOT_VISITED) { + return new Move(x - 1, y); + } + if (x + 1 < 10 && userField.getCellStatus(x + 1, y) == CellStatus.NOT_VISITED) { + return new Move(x + 1, y); + } + if (y != 0 && userField.getCellStatus(x, y - 1) == CellStatus.NOT_VISITED) { + return new Move(x, y - 1); + } + return new Move(x, y + 1); + } + + if (x == lastHit.get(1).getX()) { + Comparator byY = Comparator.comparing(Move::getY); + lastHit.sort(byY); + y = Math.min(y, lastHit.get(lastHit.size() - 1).getY()); + if (y != 0 && userField.getCellStatus(x, y - 1) == CellStatus.NOT_VISITED) { + return new Move(x, y - 1); + } + y = Math.max(y, lastHit.get(lastHit.size() - 1).getY()); + return new Move(x, y + 1); + } + Comparator byX = Comparator.comparing(Move::getX); + lastHit.sort(byX); + x = Math.min(x, lastHit.get(lastHit.size() - 1).getX()); + if (x != 0 && userField.getCellStatus(x - 1, y) == CellStatus.NOT_VISITED) { + return new Move(x - 1, y); + } + x = Math.max(y, lastHit.get(lastHit.size() - 1).getX()); + return new Move(x + 1, y); + } + +} diff --git a/src/main/java/course_project/services/ShipLocationGenerator.java b/src/main/java/course_project/services/ShipLocationGenerator.java new file mode 100644 index 00000000..01eda89f --- /dev/null +++ b/src/main/java/course_project/services/ShipLocationGenerator.java @@ -0,0 +1,94 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.fields.Field; + +import static java.lang.Math.random; + +public class ShipLocationGenerator { + + public void generateShips(Field field) { + placeShips(field, 1, 3); + placeShips(field, 2, 2); + placeShips(field, 3, 1); + placeShips(field, 4, 0); + } + + private void placeShips(Field field, int amount, int coordDiff) { + for (int i = 0; i < amount; i++) { + boolean foundPlace = false; + while (!foundPlace) { + int x = (int) (random() * 10); + int y = (int) (random() * 10); + if (isValidPlace(field, x, x, y - coordDiff, y)) { + fillShip(field, x, x, y - coordDiff, y); + foundPlace = true; + } else if (isValidPlace(field, x, x + coordDiff, y, y)) { + fillShip(field, x, x + coordDiff, y, y); + foundPlace = true; + } else if (isValidPlace(field, x - coordDiff, x, y, y)) { + fillShip(field, x - coordDiff, x, y, y); + foundPlace = true; + } else if (isValidPlace(field, x, x, y, y + coordDiff)) { + fillShip(field, x, x, y, y + coordDiff); + foundPlace = true; + } + } + } + } + + private boolean isValidPlace(Field field, int x1, int x2, int y1, int y2) { + if (isNotInRange0to9(x1) || isNotInRange0to9(x2) || isNotInRange0to9(y1) || isNotInRange0to9(y2)) { + return false; + } + if (x2 == x1) { + for (int y = y1 - 1; y <= y2 + 1; y++) { + if (isNotInRange0to9(y)) { + continue; + } + if (isNotFreeCell(field, x1, y)) { + return false; + } + if ((!isNotInRange0to9(x1 - 1) && isNotFreeCell(field, x1 - 1, y)) || + (!isNotInRange0to9(x1 + 1) && isNotFreeCell(field, x1 + 1, y))) { + return false; + } + } + } else { + for (int x = x1 - 1; x <= x2 + 1; x++) { + if (isNotInRange0to9(x)) { + continue; + } + if (isNotFreeCell(field, x, y1)) { + return false; + } + if ((!isNotInRange0to9(y1 - 1) && isNotFreeCell(field, x, y1 - 1)) || + (!isNotInRange0to9(y2 + 1) && isNotFreeCell(field, x, y1 + 1))) { + return false; + } + } + } + return true; + } + + private void fillShip(Field field, int x1, int x2, int y1, int y2) { + if (x1 == x2) { + for (int i = y1; i <= y2; i++) { + field.setCellStatus(x1, i, CellStatus.HAS_SHIP); + } + } else { + for (int i = x1; i <= x2; i++) { + field.setCellStatus(i, y1, CellStatus.HAS_SHIP); + } + } + } + + private boolean isNotInRange0to9(int x) { + return !(0 <= x && x <= 9); + } + + private boolean isNotFreeCell(Field field, int x, int y) { + return field.getCellStatus(x, y) != CellStatus.FREE; + } + +} diff --git a/src/main/java/course_project/services/UserService.java b/src/main/java/course_project/services/UserService.java new file mode 100644 index 00000000..0eefef8b --- /dev/null +++ b/src/main/java/course_project/services/UserService.java @@ -0,0 +1,97 @@ +package course_project.services; + +import course_project.objects.Move; +import course_project.enums.Response; + +import java.io.IOException; + +public class UserService { + + private final InputService inputService; + + public UserService() { + inputService = new InputService(); + } + + public Move getMove() { + printMoveMessage(); + String input = inputService.getInput(); + while (!isValidMove(input)) { + System.out.println("Wrong input format. Try again:"); + input = inputService.getInput(); + } + return new Move(input); + } + + public Response completeComputerMove(Move move) { + printMove(move); + printResponseMessage(); + String input = inputService.getInput(); + while (!isValidMoveResponse(input)) { + System.out.println("Wrong input format. Try again:"); + input = inputService.getInput(); + } + return Response.values()[Integer.parseInt(input)]; + } + + public boolean isValidMoveResponse(String input) { + if (input != null) { + return input.matches("[0-2]"); + } + return false; + } + + public boolean isValidMove(String input) { + if (input != null) { + return input.matches("[A-J](10|[1-9])"); + } + return false; + } + + public void printComputerResponse(Response response) { + if (response == Response.VISITED) { + printVisitedAlreadyMessage(); + } else { + System.out.println(response); + } + } + + public void printMove(Move move) { + System.out.println("Computer move: " + move); + } + + public void printWelcomeMessage() { + System.out.println("Welcome to Sea Battle! You do the first move!"); + } + + public void printMoveMessage() { + System.out.println("Make your move (e. g. D4): "); + } + + public void printResponseMessage() { + System.out.println("0 - missed, 1 - hit, 2 - killed.\nEnter a response:"); + } + + public void printVisitedAlreadyMessage() { + System.out.println("You have checked this cell already! Try to make a move again."); + } + + public void printUserWinMessageAndExit() { + System.out.println("You won! Congratulations!!!"); + try { + inputService.closeBuffer(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void printComputerWinMessageAndExit() { + System.out.println("Computer won!"); + try { + inputService.closeBuffer(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} From b4d6100ed84d2401ab1c2131705dfe6fc429b960 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 18 Sep 2021 14:39:54 +0300 Subject: [PATCH 46/55] SeaBattle style fix --- build.gradle | 2 ++ src/main/java/course_project/objects/GameData.java | 7 +++---- .../java/course_project/services/GameService.java | 2 +- .../services/ShipLocationGenerator.java | 11 +++++++---- .../java/course_project/services/UserService.java | 14 +++++++------- 5 files changed, 20 insertions(+), 16 deletions(-) diff --git a/build.gradle b/build.gradle index 820ef2b2..405f66d0 100644 --- a/build.gradle +++ b/build.gradle @@ -20,6 +20,8 @@ dependencies { testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' testCompile("org.junit.jupiter:junit-jupiter-params:5.7.0") + + testImplementation "org.mockito:mockito-core:3.+" } test { diff --git a/src/main/java/course_project/objects/GameData.java b/src/main/java/course_project/objects/GameData.java index 079bb0e3..ff205824 100644 --- a/src/main/java/course_project/objects/GameData.java +++ b/src/main/java/course_project/objects/GameData.java @@ -17,13 +17,12 @@ public class GameData { private int computerShips = 10; private int userShips = 10; - public GameData() { - computerField = new ComputerField(); + public GameData(ShipLocationGenerator generator) { + computerField = generator.generateShips(); userField = new UserField(); - new ShipLocationGenerator().generateShips(computerField); } - public Field getComputerField() { + public ComputerField getComputerField() { return computerField; } diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java index 77bd5f52..a0102c84 100644 --- a/src/main/java/course_project/services/GameService.java +++ b/src/main/java/course_project/services/GameService.java @@ -12,7 +12,7 @@ public class GameService { public void run() { UserService userService = new UserService(); userService.printWelcomeMessage(); - GameData data = new GameData(); + GameData data = new GameData(new ShipLocationGenerator()); processMoves(userService, data); } diff --git a/src/main/java/course_project/services/ShipLocationGenerator.java b/src/main/java/course_project/services/ShipLocationGenerator.java index 01eda89f..a7e0cd30 100644 --- a/src/main/java/course_project/services/ShipLocationGenerator.java +++ b/src/main/java/course_project/services/ShipLocationGenerator.java @@ -1,20 +1,23 @@ package course_project.services; import course_project.enums.CellStatus; +import course_project.objects.fields.ComputerField; import course_project.objects.fields.Field; import static java.lang.Math.random; public class ShipLocationGenerator { - public void generateShips(Field field) { + public ComputerField generateShips() { + ComputerField field = new ComputerField(); placeShips(field, 1, 3); placeShips(field, 2, 2); placeShips(field, 3, 1); placeShips(field, 4, 0); + return field; } - private void placeShips(Field field, int amount, int coordDiff) { + private void placeShips(ComputerField field, int amount, int coordDiff) { for (int i = 0; i < amount; i++) { boolean foundPlace = false; while (!foundPlace) { @@ -37,7 +40,7 @@ private void placeShips(Field field, int amount, int coordDiff) { } } - private boolean isValidPlace(Field field, int x1, int x2, int y1, int y2) { + private boolean isValidPlace(ComputerField field, int x1, int x2, int y1, int y2) { if (isNotInRange0to9(x1) || isNotInRange0to9(x2) || isNotInRange0to9(y1) || isNotInRange0to9(y2)) { return false; } @@ -71,7 +74,7 @@ private boolean isValidPlace(Field field, int x1, int x2, int y1, int y2) { return true; } - private void fillShip(Field field, int x1, int x2, int y1, int y2) { + private void fillShip(ComputerField field, int x1, int x2, int y1, int y2) { if (x1 == x2) { for (int i = y1; i <= y2; i++) { field.setCellStatus(x1, i, CellStatus.HAS_SHIP); diff --git a/src/main/java/course_project/services/UserService.java b/src/main/java/course_project/services/UserService.java index 0eefef8b..7d729282 100644 --- a/src/main/java/course_project/services/UserService.java +++ b/src/main/java/course_project/services/UserService.java @@ -34,14 +34,14 @@ public Response completeComputerMove(Move move) { return Response.values()[Integer.parseInt(input)]; } - public boolean isValidMoveResponse(String input) { + private boolean isValidMoveResponse(String input) { if (input != null) { return input.matches("[0-2]"); } return false; } - public boolean isValidMove(String input) { + private boolean isValidMove(String input) { if (input != null) { return input.matches("[A-J](10|[1-9])"); } @@ -78,15 +78,15 @@ public void printVisitedAlreadyMessage() { public void printUserWinMessageAndExit() { System.out.println("You won! Congratulations!!!"); - try { - inputService.closeBuffer(); - } catch (IOException e) { - e.printStackTrace(); - } + closeBuffer(); } public void printComputerWinMessageAndExit() { System.out.println("Computer won!"); + closeBuffer(); + } + + public void closeBuffer() { try { inputService.closeBuffer(); } catch (IOException e) { From 965218d89b251521cde9179c169da73838939792 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 18 Sep 2021 14:40:22 +0300 Subject: [PATCH 47/55] SeaBattle Tests done --- .../objects/ComputerFieldTest.java | 43 ++++++++++++++++++ .../course_project/objects/GameDataTest.java | 39 ++++++++++++++++ .../java/course_project/objects/MoveTest.java | 24 ++++++++++ .../course_project/objects/UserFieldTest.java | 42 ++++++++++++++++++ .../services/GameServiceTest.java | 6 +++ .../services/MoveGeneratorTest.java | 44 +++++++++++++++++++ .../services/ShipLocationGeneratorTest.java | 44 +++++++++++++++++++ 7 files changed, 242 insertions(+) create mode 100644 src/test/java/course_project/objects/ComputerFieldTest.java create mode 100644 src/test/java/course_project/objects/GameDataTest.java create mode 100644 src/test/java/course_project/objects/MoveTest.java create mode 100644 src/test/java/course_project/objects/UserFieldTest.java create mode 100644 src/test/java/course_project/services/GameServiceTest.java create mode 100644 src/test/java/course_project/services/MoveGeneratorTest.java create mode 100644 src/test/java/course_project/services/ShipLocationGeneratorTest.java diff --git a/src/test/java/course_project/objects/ComputerFieldTest.java b/src/test/java/course_project/objects/ComputerFieldTest.java new file mode 100644 index 00000000..a136ea94 --- /dev/null +++ b/src/test/java/course_project/objects/ComputerFieldTest.java @@ -0,0 +1,43 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.fields.ComputerField; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ComputerFieldTest { + + @Test + void initTest() { + ComputerField computerField = new ComputerField(); + + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + assertEquals(CellStatus.FREE, computerField.getCellStatus(i, j)); + } + } + } + + @Test + void getResponseTest() { + ComputerField computerField = new ComputerField(); + + assertEquals(Response.MISSED, computerField.getResponse(new Move(1, 5))); + assertEquals(Response.VISITED, computerField.getResponse(new Move(1, 5))); + + computerField.setCellStatus(6, 2, CellStatus.VISITED); + assertEquals(Response.VISITED, computerField.getResponse(new Move(6, 2))); + + computerField.setCellStatus(3, 7, CellStatus.HAS_SHIP); + assertEquals(Response.KILLED, computerField.getResponse(new Move(3, 7))); + + computerField.setCellStatus(9, 8, CellStatus.HAS_SHIP); + computerField.setCellStatus(9, 7, CellStatus.HAS_SHIP); + computerField.setCellStatus(9, 6, CellStatus.HAS_SHIP); + assertEquals(Response.HIT, computerField.getResponse(new Move(9, 7))); + assertEquals(Response.HIT, computerField.getResponse(new Move(9, 6))); + assertEquals(Response.KILLED, computerField.getResponse(new Move(9, 8))); + } +} diff --git a/src/test/java/course_project/objects/GameDataTest.java b/src/test/java/course_project/objects/GameDataTest.java new file mode 100644 index 00000000..9aa4618f --- /dev/null +++ b/src/test/java/course_project/objects/GameDataTest.java @@ -0,0 +1,39 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.fields.ComputerField; +import course_project.services.ShipLocationGenerator; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class GameDataTest { + + @Test + void getResponseFromComputerTest() { + ComputerField computerField = new ComputerField(); + computerField.setCellStatus(4, 4, CellStatus.HAS_SHIP); + ShipLocationGenerator generator = Mockito.mock(ShipLocationGenerator.class); + Mockito.when(generator.generateShips()).thenReturn(computerField); + GameData gameData = new GameData(generator); + + assertEquals(Response.KILLED, gameData.getResponseFromComputer(new Move(4, 4))); + assertEquals(9, gameData.getComputerShips()); + } + + @Test + void saveComputerMoveResult() { + GameData gameData = new GameData(new ShipLocationGenerator()); + + List moves = new ArrayList<>(); + moves.add(new Move(1, 1)); + gameData.saveComputerMoveResult(Response.KILLED, moves.get(0), moves); + + assertEquals(9, gameData.getUserShips()); + } +} diff --git a/src/test/java/course_project/objects/MoveTest.java b/src/test/java/course_project/objects/MoveTest.java new file mode 100644 index 00000000..f1431185 --- /dev/null +++ b/src/test/java/course_project/objects/MoveTest.java @@ -0,0 +1,24 @@ +package course_project.objects; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MoveTest { + + @Test + void initMoveTest() { + Move move = new Move(0, 2); + + assertEquals(0, move.getX()); + assertEquals(2, move.getY()); + assertEquals("A3", move.toString()); + + move = new Move("B10"); + + assertEquals(1, move.getX()); + assertEquals(9, move.getY()); + assertEquals("B10", move.toString()); + } + +} diff --git a/src/test/java/course_project/objects/UserFieldTest.java b/src/test/java/course_project/objects/UserFieldTest.java new file mode 100644 index 00000000..e2142b7f --- /dev/null +++ b/src/test/java/course_project/objects/UserFieldTest.java @@ -0,0 +1,42 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.objects.fields.UserField; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UserFieldTest { + + @Test + void initTest() { + UserField userField = new UserField(); + + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + assertEquals(CellStatus.NOT_VISITED, userField.getCellStatus(i, j)); + } + } + } + + @Test + void setVisitedAroundShipTest() { + UserField userField = new UserField(); + + List moves = new ArrayList<>(); + moves.add(new Move(1, 2)); + moves.add(new Move(1, 3)); + moves.add(new Move(1, 4)); + userField.setVisitedAroundShip(moves); + + for (int i = 1; i < 6; i++) { + assertEquals(CellStatus.VISITED, userField.getCellStatus(1, i)); + assertEquals(CellStatus.VISITED, userField.getCellStatus(0, i)); + assertEquals(CellStatus.VISITED, userField.getCellStatus(2, i)); + } + } + +} diff --git a/src/test/java/course_project/services/GameServiceTest.java b/src/test/java/course_project/services/GameServiceTest.java new file mode 100644 index 00000000..d3063675 --- /dev/null +++ b/src/test/java/course_project/services/GameServiceTest.java @@ -0,0 +1,6 @@ +package course_project.services; + +public class GameServiceTest { + + +} diff --git a/src/test/java/course_project/services/MoveGeneratorTest.java b/src/test/java/course_project/services/MoveGeneratorTest.java new file mode 100644 index 00000000..2a9b15e0 --- /dev/null +++ b/src/test/java/course_project/services/MoveGeneratorTest.java @@ -0,0 +1,44 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.Move; +import course_project.objects.fields.UserField; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class MoveGeneratorTest { + + @Test + void generateTest() { + Move move = MoveGenerator.generate(new UserField()); + + assertTrue(0 <= move.getX() && move.getX() < 10); + assertTrue(0 <= move.getY() && move.getY() < 10); + } + + @Test + void generateWithLastHitTest() { + UserField userField = new UserField(); + userField.setCellStatus(3, 3, CellStatus.VISITED); + userField.setCellStatus(2, 3, CellStatus.VISITED); + List lastHit = new ArrayList<>(); + lastHit.add(new Move(3, 3)); + Move move = MoveGenerator.generate(userField, lastHit); + + assertEquals(4, move.getX()); + assertEquals(3, move.getY()); + + userField.setCellStatus(3, 4, CellStatus.VISITED); + lastHit.add(new Move(3, 4)); + move = MoveGenerator.generate(userField, lastHit); + + assertEquals(3, move.getX()); + assertEquals(2, move.getY()); + } + +} diff --git a/src/test/java/course_project/services/ShipLocationGeneratorTest.java b/src/test/java/course_project/services/ShipLocationGeneratorTest.java new file mode 100644 index 00000000..9aa00191 --- /dev/null +++ b/src/test/java/course_project/services/ShipLocationGeneratorTest.java @@ -0,0 +1,44 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.fields.ComputerField; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ShipLocationGeneratorTest { + + @Test + void generateShipsTest() { + ComputerField computerField = new ShipLocationGenerator().generateShips(); + + int shipCellCount = 0; + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (computerField.getCellStatus(i, j) == CellStatus.HAS_SHIP) { + shipCellCount++; + assertTrue(has0to2shipCellAround(computerField, i, j)); + + } + } + } + + assertEquals(20, shipCellCount); + } + + private boolean has0to2shipCellAround(ComputerField field, int x, int y) { + int hasShipCellCount = 0; + for (int i = x - 1; i <= x + 1; i++) { + for (int j = y - 1; j <= y + 1; j++) { + if (i > 9 || j > 9 || i < 0 || j < 0) { + continue; + } + if (field.getCellStatus(i, j) == CellStatus.HAS_SHIP) { + hasShipCellCount++; + } + } + } + return hasShipCellCount == 1 || hasShipCellCount == 2 || hasShipCellCount == 3; + } +} From 0db95e0ec0a06088aeb4086d7f3f52bdaa51e41e Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 18 Sep 2021 14:48:35 +0300 Subject: [PATCH 48/55] README.md update --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ce2a70f7..2aebb793 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ | HW6 | [MapProblemsCollisionGenerator & MapProblemMutableGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_6) | Classes that create problems in HashMap. | | HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_7) | The functional interface with an abstract method that turns a Kitten to a Cat. | | HW7 | [Tests 7](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_7) | Tests for homework 7. | +| Course Project | [Sea Battle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/course_project) | The app tht plays Sea Battle game with user. | +| Course Project | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/course_project) | Tests for Sea Battle. | [Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) From b1704c638792d78fd36c0877ee22d93d0f045dd4 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 18 Sep 2021 14:50:16 +0300 Subject: [PATCH 49/55] SeaBattle style fix --- src/test/java/course_project/services/GameServiceTest.java | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 src/test/java/course_project/services/GameServiceTest.java diff --git a/src/test/java/course_project/services/GameServiceTest.java b/src/test/java/course_project/services/GameServiceTest.java deleted file mode 100644 index d3063675..00000000 --- a/src/test/java/course_project/services/GameServiceTest.java +++ /dev/null @@ -1,6 +0,0 @@ -package course_project.services; - -public class GameServiceTest { - - -} From 0bdfe50edc7a6c8ae7c3677c306582e86037b239 Mon Sep 17 00:00:00 2001 From: Waranko Date: Sat, 18 Sep 2021 17:42:38 +0300 Subject: [PATCH 50/55] SeaBattle tests add --- .../course_project/services/UserService.java | 4 +- .../services/UserServiceTest.java | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 src/test/java/course_project/services/UserServiceTest.java diff --git a/src/main/java/course_project/services/UserService.java b/src/main/java/course_project/services/UserService.java index 7d729282..9dc64572 100644 --- a/src/main/java/course_project/services/UserService.java +++ b/src/main/java/course_project/services/UserService.java @@ -34,14 +34,14 @@ public Response completeComputerMove(Move move) { return Response.values()[Integer.parseInt(input)]; } - private boolean isValidMoveResponse(String input) { + public boolean isValidMoveResponse(String input) { if (input != null) { return input.matches("[0-2]"); } return false; } - private boolean isValidMove(String input) { + public boolean isValidMove(String input) { if (input != null) { return input.matches("[A-J](10|[1-9])"); } diff --git a/src/test/java/course_project/services/UserServiceTest.java b/src/test/java/course_project/services/UserServiceTest.java new file mode 100644 index 00000000..c1b78384 --- /dev/null +++ b/src/test/java/course_project/services/UserServiceTest.java @@ -0,0 +1,45 @@ +package course_project.services; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class UserServiceTest { + + @Test + void isValidMoveTest() { + UserService userService = new UserService(); + + assertTrue(userService.isValidMove("A1")); + assertTrue(userService.isValidMove("C10")); + assertTrue(userService.isValidMove("F8")); + assertTrue(userService.isValidMove("D4")); + assertTrue(userService.isValidMove("J10")); + + assertFalse(userService.isValidMove("D0")); + assertFalse(userService.isValidMove("F11")); + assertFalse(userService.isValidMove("M5")); + assertFalse(userService.isValidMove("d6")); + assertFalse(userService.isValidMove("5B")); + assertFalse(userService.isValidMove("string")); + assertFalse(userService.isValidMove("")); + assertFalse(userService.isValidMove("1 6")); + } + + @Test + void isValidMoveResponseTest() { + UserService userService = new UserService(); + + assertTrue(userService.isValidMoveResponse("0")); + assertTrue(userService.isValidMoveResponse("1")); + assertTrue(userService.isValidMoveResponse("2")); + + assertFalse(userService.isValidMoveResponse("3")); + assertFalse(userService.isValidMoveResponse("M5")); + assertFalse(userService.isValidMoveResponse("string")); + assertFalse(userService.isValidMoveResponse("MISSED")); + assertFalse(userService.isValidMoveResponse("")); + assertFalse(userService.isValidMoveResponse("1 6")); + } +} From 4ef8478c673efc38a8f78e96dd52126c2178285b Mon Sep 17 00:00:00 2001 From: Waranko Date: Tue, 21 Sep 2021 13:09:01 +0300 Subject: [PATCH 51/55] HW3 bug fix --- src/main/java/homework_3/ImmutableCat.java | 31 +++++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/main/java/homework_3/ImmutableCat.java b/src/main/java/homework_3/ImmutableCat.java index 02485e21..ad69151e 100644 --- a/src/main/java/homework_3/ImmutableCat.java +++ b/src/main/java/homework_3/ImmutableCat.java @@ -35,11 +35,34 @@ public ImmutableCat(){ yearOfBirth = 2020; } - public ImmutableCat setNewName(String name){ - return new ImmutableCat(name); + public String getName() { + return name; } - public ImmutableCat setNewData(String name, int yearOfBirth, ArrayList favouriteFood){ - return new ImmutableCat(name, yearOfBirth, favouriteFood); + public ImmutableCat setName(String name) { + return new ImmutableCat(name, this.yearOfBirth, this.favouriteFood); } + + public int getYearOfBirth() { + return yearOfBirth; + } + + public ImmutableCat setYearOfBirth(int yearOfBirth) { + return new ImmutableCat(this.name, yearOfBirth, this.favouriteFood); + } + + public ArrayList getFavouriteFood() { + return new ArrayList<>(favouriteFood); + } + + public ImmutableCat setFavouriteFood(ArrayList favouriteFood) { + return new ImmutableCat(this.name, this.yearOfBirth, favouriteFood); + } + + public ImmutableCat addFavouriteFoodItem(String favouriteFoodItem) { + ArrayList copyFF = new ArrayList<>(favouriteFood); + copyFF.add(favouriteFoodItem); + return new ImmutableCat(this.name, this.yearOfBirth, copyFF); + } + } From c5de362659660fcbea4fb183072b199bf34b001c Mon Sep 17 00:00:00 2001 From: Waranko Date: Tue, 21 Sep 2021 17:22:30 +0300 Subject: [PATCH 52/55] SeaBattle interface fix --- .../course_project/services/GameService.java | 90 +++++++++++-------- .../course_project/services/UserService.java | 58 +++++------- 2 files changed, 74 insertions(+), 74 deletions(-) diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java index a0102c84..ea37c2b8 100644 --- a/src/main/java/course_project/services/GameService.java +++ b/src/main/java/course_project/services/GameService.java @@ -9,56 +9,72 @@ public class GameService { + private final String WELCOME_MESSAGE = "Welcome to Sea Battle! You are playing with the computer now!"; + private final String USER_WIN_MESSAGE = "You won! Congratulations!!!"; + private final String COMPUTER_WIN_MESSAGE = "Computer won!"; + public void run() { UserService userService = new UserService(); - userService.printWelcomeMessage(); + System.out.println(WELCOME_MESSAGE); GameData data = new GameData(new ShipLocationGenerator()); processMoves(userService, data); } private void processMoves(UserService userService, GameData data) { - boolean gotWinner = false; List lastHit = new ArrayList<>(); - while (!gotWinner) { - Response response; - do { - response = processUserMove(userService, data); - userService.printComputerResponse(response); - if (response == Response.KILLED) { - if (data.isComputerFleetEmpty()) { - userService.printUserWinMessageAndExit(); - gotWinner = true; - break; - } - } - } while (response == Response.HIT || response == Response.KILLED || response == Response.VISITED); - if (gotWinner) break; - do { - Move nextMove = MoveGenerator.generate(data.getUserField(), lastHit); - response = processComputerMove(userService, nextMove); - if (response == Response.HIT || response == Response.KILLED) { - lastHit.add(nextMove); - } - data.saveComputerMoveResult(response, nextMove, lastHit); - if (response == Response.KILLED) { - lastHit.clear(); - if (data.isUserFleetEmpty()) { - userService.printComputerWinMessageAndExit(); - data.getComputerField().printField(); - gotWinner = true; - break; - } - } - } while (response == Response.HIT || response == Response.KILLED); + boolean isUsersTurn = true; + while (!isGameFinished(data)) { + if (isUsersTurn) { + processUserMoves(userService, data); + isUsersTurn = false; + } else { + processComputerMoves(userService, data, lastHit); + isUsersTurn = true; + } } + finishGame(data, userService); + } + + private void processUserMoves(UserService userService, GameData gameData) { + Response response; + do { + response = gameData.getResponseFromComputer(userService.getMove()); + userService.printComputerResponse(response); + if (response == Response.KILLED) { + if (isGameFinished(gameData)) return; + } + } while (response == Response.HIT || response == Response.KILLED || response == Response.VISITED); } - private Response processComputerMove(UserService userService, Move move) { - return userService.completeComputerMove(move); + private void processComputerMoves(UserService userService, GameData data, List lastHit) { + Response response; + do { + Move nextMove = MoveGenerator.generate(data.getUserField(), lastHit); + response = userService.completeComputerMove(nextMove); + if (response == Response.HIT || response == Response.KILLED) { + lastHit.add(nextMove); + } + data.saveComputerMoveResult(response, nextMove, lastHit); + if (response == Response.KILLED) { + lastHit.clear(); + if (isGameFinished(data)) return; + } + } while (response == Response.HIT || response == Response.KILLED); } - private Response processUserMove(UserService userService, GameData gameData) { - return gameData.getResponseFromComputer(userService.getMove()); + private boolean isGameFinished(GameData data) { + return data.isComputerFleetEmpty() || data.isUserFleetEmpty(); + } + + private void finishGame(GameData data, UserService userService) { + if (data.isUserFleetEmpty()) { + System.out.println(COMPUTER_WIN_MESSAGE); + data.getComputerField().printField(); + } + if (data.isComputerFleetEmpty()) { + System.out.println(USER_WIN_MESSAGE); + } + userService.closeBuffer(); } } diff --git a/src/main/java/course_project/services/UserService.java b/src/main/java/course_project/services/UserService.java index 9dc64572..63e8f1ed 100644 --- a/src/main/java/course_project/services/UserService.java +++ b/src/main/java/course_project/services/UserService.java @@ -7,6 +7,13 @@ public class UserService { + private final String MOVE_MESSAGE = "Make your move (e. g. D4): "; + private final String RESPONSE_MESSAGE = " Enter 0, you have no ship on this cell,\n" + + " Enter 1, if part of your ship is on this cell,\n" + + " Enter 2, if there is last/only not killed part os your ship.\n" + + " Enter a response (a digit from 0 to 2):"; + private final String VISITED_ALREADY_MESSAGE = "You have checked this cell already! Try to make a move again."; + private final String WRONG_MOVE_FORMAT_MESSAGE = "Wrong input format. Try again:"; private final InputService inputService; public UserService() { @@ -14,21 +21,22 @@ public UserService() { } public Move getMove() { - printMoveMessage(); + System.out.println(MOVE_MESSAGE); String input = inputService.getInput(); + input = input.toUpperCase(); while (!isValidMove(input)) { - System.out.println("Wrong input format. Try again:"); + System.out.println(WRONG_MOVE_FORMAT_MESSAGE); input = inputService.getInput(); } return new Move(input); } public Response completeComputerMove(Move move) { - printMove(move); - printResponseMessage(); + System.out.println("Computer's move: " + move); + System.out.println(RESPONSE_MESSAGE); String input = inputService.getInput(); while (!isValidMoveResponse(input)) { - System.out.println("Wrong input format. Try again:"); + System.out.println(WRONG_MOVE_FORMAT_MESSAGE); input = inputService.getInput(); } return Response.values()[Integer.parseInt(input)]; @@ -50,42 +58,18 @@ public boolean isValidMove(String input) { public void printComputerResponse(Response response) { if (response == Response.VISITED) { - printVisitedAlreadyMessage(); + System.out.println(VISITED_ALREADY_MESSAGE); } else { - System.out.println(response); + if (response == Response.MISSED) { + System.out.println("Computer has no ship there. It's computer's turn to make a move."); + } else if (response == Response.HIT) { + System.out.println("You have hit the computer's ship. It's your turn ta make a move again!"); + } else { + System.out.println("You have destroyed one of computer's ships entirely. It's your turn ta make a move again!"); + } } } - public void printMove(Move move) { - System.out.println("Computer move: " + move); - } - - public void printWelcomeMessage() { - System.out.println("Welcome to Sea Battle! You do the first move!"); - } - - public void printMoveMessage() { - System.out.println("Make your move (e. g. D4): "); - } - - public void printResponseMessage() { - System.out.println("0 - missed, 1 - hit, 2 - killed.\nEnter a response:"); - } - - public void printVisitedAlreadyMessage() { - System.out.println("You have checked this cell already! Try to make a move again."); - } - - public void printUserWinMessageAndExit() { - System.out.println("You won! Congratulations!!!"); - closeBuffer(); - } - - public void printComputerWinMessageAndExit() { - System.out.println("Computer won!"); - closeBuffer(); - } - public void closeBuffer() { try { inputService.closeBuffer(); From c3c75615926c09d66c304aac3358f42f5c47e9c4 Mon Sep 17 00:00:00 2001 From: Waranko Date: Wed, 22 Sep 2021 17:36:34 +0300 Subject: [PATCH 53/55] SeaBattle print field --- src/main/java/course_project/objects/Cell.java | 15 +++++++-------- .../objects/fields/ComputerField.java | 12 ++++++++++++ .../java/course_project/services/GameService.java | 2 +- .../java/course_project/services/UserService.java | 8 ++++---- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/main/java/course_project/objects/Cell.java b/src/main/java/course_project/objects/Cell.java index 2d54d1dc..c9599015 100644 --- a/src/main/java/course_project/objects/Cell.java +++ b/src/main/java/course_project/objects/Cell.java @@ -2,8 +2,7 @@ import course_project.enums.CellStatus; -import static course_project.enums.CellStatus.FREE; -import static course_project.enums.CellStatus.HAS_SHIP; +import static course_project.enums.CellStatus.*; public class Cell { @@ -25,12 +24,12 @@ public boolean hadShip() { @Override public String toString() { - if (status == FREE) { - return " "; + if (status == VISITED) { + if(gotShip) { + return "X"; + } + return "e"; } - if (status == HAS_SHIP) { - return "X"; - } - return "."; + return "-"; } } diff --git a/src/main/java/course_project/objects/fields/ComputerField.java b/src/main/java/course_project/objects/fields/ComputerField.java index 94f60f95..9b77bfc6 100644 --- a/src/main/java/course_project/objects/fields/ComputerField.java +++ b/src/main/java/course_project/objects/fields/ComputerField.java @@ -70,4 +70,16 @@ private boolean hasShipAround(int x, int y) { || (y + 1 < table[0].length && table[x][y + 1].getStatus() == CellStatus.HAS_SHIP); } + public void printField() { + System.out.println("Computer's field:"); + System.out.println(" 1 2 3 4 5 6 7 8 9 10"); + for (int i = 0; i < 10; i++) { + System.out.print((char) (i + 65)); + System.out.println(Arrays.toString(table[i])); + } + System.out.println("\tX - computer's ship you've destroyed."); + System.out.println("\te - empty cell you've checked."); + System.out.println("\t- - a cell you've not checked."); + } + } diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java index ea37c2b8..59b56625 100644 --- a/src/main/java/course_project/services/GameService.java +++ b/src/main/java/course_project/services/GameService.java @@ -38,6 +38,7 @@ private void processMoves(UserService userService, GameData data) { private void processUserMoves(UserService userService, GameData gameData) { Response response; do { + gameData.getComputerField().printField(); response = gameData.getResponseFromComputer(userService.getMove()); userService.printComputerResponse(response); if (response == Response.KILLED) { @@ -69,7 +70,6 @@ private boolean isGameFinished(GameData data) { private void finishGame(GameData data, UserService userService) { if (data.isUserFleetEmpty()) { System.out.println(COMPUTER_WIN_MESSAGE); - data.getComputerField().printField(); } if (data.isComputerFleetEmpty()) { System.out.println(USER_WIN_MESSAGE); diff --git a/src/main/java/course_project/services/UserService.java b/src/main/java/course_project/services/UserService.java index 63e8f1ed..c143e021 100644 --- a/src/main/java/course_project/services/UserService.java +++ b/src/main/java/course_project/services/UserService.java @@ -8,10 +8,10 @@ public class UserService { private final String MOVE_MESSAGE = "Make your move (e. g. D4): "; - private final String RESPONSE_MESSAGE = " Enter 0, you have no ship on this cell,\n" + - " Enter 1, if part of your ship is on this cell,\n" + - " Enter 2, if there is last/only not killed part os your ship.\n" + - " Enter a response (a digit from 0 to 2):"; + private final String RESPONSE_MESSAGE = "\tEnter 0, you have no ship on this cell,\n" + + "\tEnter 1, if part of your ship is on this cell,\n" + + "\tEnter 2, if there is last/only not killed part os your ship.\n" + + "\tEnter a response (a digit from 0 to 2):"; private final String VISITED_ALREADY_MESSAGE = "You have checked this cell already! Try to make a move again."; private final String WRONG_MOVE_FORMAT_MESSAGE = "Wrong input format. Try again:"; private final InputService inputService; From bd25d145d265ce5fe518ae7393cbad0c1465679f Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 23 Sep 2021 13:16:56 +0300 Subject: [PATCH 54/55] SeaBattle bug fix --- src/main/java/course_project/objects/fields/ComputerField.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/course_project/objects/fields/ComputerField.java b/src/main/java/course_project/objects/fields/ComputerField.java index 9b77bfc6..e0490f56 100644 --- a/src/main/java/course_project/objects/fields/ComputerField.java +++ b/src/main/java/course_project/objects/fields/ComputerField.java @@ -39,7 +39,7 @@ public Response getResponse(Move move) { x--; continue; } - if (x + 1 < 10 && x + 1 != prevX && table[x - 1][y].getStatus() == CellStatus.VISITED && table[x + 1][y].hadShip()) { + if (x + 1 < 10 && x + 1 != prevX && table[x + 1][y].getStatus() == CellStatus.VISITED && table[x + 1][y].hadShip()) { prevX = x; x++; continue; From 6b6e7a27073d7403e1968e3350e4ac22e20d0bcb Mon Sep 17 00:00:00 2001 From: Waranko Date: Thu, 23 Sep 2021 14:14:19 +0300 Subject: [PATCH 55/55] SeaBattle bug fix --- src/main/java/course_project/objects/Move.java | 2 +- src/main/java/course_project/services/MoveGenerator.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/course_project/objects/Move.java b/src/main/java/course_project/objects/Move.java index 7b1114a7..91c0d8a6 100644 --- a/src/main/java/course_project/objects/Move.java +++ b/src/main/java/course_project/objects/Move.java @@ -25,6 +25,6 @@ public int getY() { @Override public String toString() { - return String.valueOf((char) (x + 65)) + (y + 1); + return (char) (x + 65) + "" + (y + 1); } } diff --git a/src/main/java/course_project/services/MoveGenerator.java b/src/main/java/course_project/services/MoveGenerator.java index 0b55f136..8a20429e 100644 --- a/src/main/java/course_project/services/MoveGenerator.java +++ b/src/main/java/course_project/services/MoveGenerator.java @@ -57,7 +57,7 @@ public static Move generate(Field userField, List lastHit) { if (x != 0 && userField.getCellStatus(x - 1, y) == CellStatus.NOT_VISITED) { return new Move(x - 1, y); } - x = Math.max(y, lastHit.get(lastHit.size() - 1).getX()); + x = Math.max(x, lastHit.get(lastHit.size() - 1).getX()); return new Move(x + 1, y); }