From b0e8b31acee7857329f9b48ed08af2a75ee27d27 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Fri, 9 Jul 2021 21:51:11 +0300 Subject: [PATCH 01/63] gitignore updated --- README.md | 4 ++-- src/main/java/homework_1/CommandLineArgs.java | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 src/main/java/homework_1/CommandLineArgs.java diff --git a/README.md b/README.md index 5d686e9f..a59f7d31 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Krylosov Arkadiy* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady``/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) diff --git a/src/main/java/homework_1/CommandLineArgs.java b/src/main/java/homework_1/CommandLineArgs.java new file mode 100644 index 00000000..dd73b5f9 --- /dev/null +++ b/src/main/java/homework_1/CommandLineArgs.java @@ -0,0 +1,20 @@ +package Homework_1; + +public class CommandLineArgs { + + public static final String ANSI_RED = "\u001B[31m"; + + public static final String ANSI_RESET = "\u001B[0m"; + + public static void main(String[] args) { + for (String s : args) { + if (s.equals("error")) { + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); + break; + } else { + System.out.println(s + ": " + s.length() + " letters"); + } + } + } +} + From ecddcf09e0ffabf1ffeade3cd3772f6b19d4c73e Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Fri, 9 Jul 2021 21:53:44 +0300 Subject: [PATCH 02/63] gitignore updated --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a59f7d31..940493ad 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/tree/feature/KrylosovArkady``/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/KrylosovArkady/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 1df4806ffb0ff34c40aa87e1d2cdbfa80599bd11 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Fri, 9 Jul 2021 21:55:32 +0300 Subject: [PATCH 03/63] Delete Main.java --- src/main/java/homework_1/Main.java | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 src/main/java/homework_1/Main.java diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java deleted file mode 100644 index 07c029a2..00000000 --- a/src/main/java/homework_1/Main.java +++ /dev/null @@ -1,9 +0,0 @@ -package homework_1; - -public class Main { - - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - -} From 8a07313d8cb7c5c4e3e62211b28ab2026001b36f Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:00:48 +0300 Subject: [PATCH 04/63] homework_2 done. --- src/main/java/homework_2/trafficLight/TrafficLight.java | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 src/main/java/homework_2/trafficLight/TrafficLight.java diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java new file mode 100644 index 00000000..80692449 --- /dev/null +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -0,0 +1,4 @@ +package homework_2.trafficLight; + +public class TrafficLight { +} From 528cd6f0d5105971b4021b35572071d98f397e34 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:05:47 +0300 Subject: [PATCH 05/63] homework_2 done. --- .../pyramidPrinter/PyramidPrinter.java | 21 +++++++++++++++++++ .../randomCharsTable/RandomCharsTable.java | 4 ++++ 2 files changed, 25 insertions(+) create mode 100644 src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java create mode 100644 src/main/java/homework_2/randomCharsTable/RandomCharsTable.java diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java new file mode 100644 index 00000000..cc2006fb --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -0,0 +1,21 @@ +package homework_2.pyramidPrinter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + public static void main(String[] args) { + String output = ""; + int input; + try(BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))){ + input = Integer.parseInt(bF.readLine()); + for (int i = 0; i < input; i++) { + output += "x"; + System.out.println(output); + } + } catch (IOException e){ + System.out.println("Error occurred during input"); + } + } +} diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java new file mode 100644 index 00000000..62c32b95 --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -0,0 +1,4 @@ +package homework_2.randomCharsTable; + +public class RandomCharsTable { +} From e3775d8568f7c8228df07effe4194622a6834783 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:06:12 +0300 Subject: [PATCH 06/63] homework_2 done. --- src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java index cc2006fb..f8b234b8 100644 --- a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -8,13 +8,13 @@ public class PyramidPrinter { public static void main(String[] args) { String output = ""; int input; - try(BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))){ + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { input = Integer.parseInt(bF.readLine()); for (int i = 0; i < input; i++) { output += "x"; System.out.println(output); } - } catch (IOException e){ + } catch (IOException e) { System.out.println("Error occurred during input"); } } From 0e704daec45e53aae745e6cefa1bcddeb7f74286 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:28:39 +0300 Subject: [PATCH 07/63] homework_2 done. --- .../randomCharsTable/RandomCharsTable.java | 3 + .../homework_2/trafficLight/Strategy.java | 59 +++++++++++++++++++ .../homework_2/trafficLight/TrafficLight.java | 6 ++ 3 files changed, 68 insertions(+) create mode 100644 src/main/java/homework_2/trafficLight/Strategy.java diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java index 62c32b95..3821f5b3 100644 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -1,4 +1,7 @@ package homework_2.randomCharsTable; public class RandomCharsTable { + public static void main(String[] args) { + + } } diff --git a/src/main/java/homework_2/trafficLight/Strategy.java b/src/main/java/homework_2/trafficLight/Strategy.java new file mode 100644 index 00000000..12a9eaa3 --- /dev/null +++ b/src/main/java/homework_2/trafficLight/Strategy.java @@ -0,0 +1,59 @@ +package homework_2.trafficLight; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Strategy { + private final BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + private final String ANSI_GREED = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + private int seconds; + + private final boolean greenLight = seconds % 60 < 35; + + private final boolean yellowLight = seconds % 60 >= 35 && seconds % 60 <= 40 || seconds % 60 >= 55; + + public void choosingStrategy() throws IOException { + System.out.println(""" + Choose input format:\s + 1.HH:MM:SS format + 2.Total amount of seconds."""); + String strategy = bF.readLine(); + if (strategy.startsWith("1")) { + timeFormat(); + } else secondsFormat(); + } + + private void secondsFormat() throws IOException { + System.out.println("Enter necessary amount of seconds."); + seconds = Integer.parseInt(bF.readLine()); + if (seconds > 86399) { + System.out.println("Day is over"); + return; + } + if (greenLight) { + System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); + } else if (yellowLight) { + System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); + } + + private void timeFormat() throws IOException { + System.out.println("Enter necessary amount of seconds."); + String parsedTime = bF.readLine(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (greenLight) { + System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); + } else if (yellowLight) { + System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); + } +} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java index 80692449..2d17b3f2 100644 --- a/src/main/java/homework_2/trafficLight/TrafficLight.java +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -1,4 +1,10 @@ package homework_2.trafficLight; +import java.io.IOException; + public class TrafficLight { + public static void main(String[] args) throws IOException { + Strategy strategy = new Strategy(); + strategy.choosingStrategy(); + } } From 5aa7e969b47898bcaf4fc33b55573ac2860eaa43 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 18:20:42 +0300 Subject: [PATCH 08/63] homework_2 done. --- .../randomCharsTable/RandomCharsTable.java | 6 +- .../homework_2/randomCharsTable/Strategy.java | 82 +++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 src/main/java/homework_2/randomCharsTable/Strategy.java diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java index 3821f5b3..7b4e3c00 100644 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -1,7 +1,9 @@ package homework_2.randomCharsTable; -public class RandomCharsTable { - public static void main(String[] args) { +import java.io.IOException; +public class RandomCharsTable { + public static void main(String[] args) throws IOException { + Strategy.choosingStrategy(); } } diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java new file mode 100644 index 00000000..491800a6 --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/Strategy.java @@ -0,0 +1,82 @@ +package homework_2.randomCharsTable; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Strategy { + public static char[][] array; + + private final static BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); + + private static String inputData; + + private static String result = ""; + + private static int rows; + + private static int columns; + + public static void choosingStrategy() throws IOException { + System.out.println("Enter necessary data."); + inputData = bF.readLine(); + String strategy = inputData.trim(); + arrayInitialization(); + if (strategy.endsWith("odd")) { + odd(); + } else { + even(); + } + printingResult(); + } + + public static void arrayInitialization() { + rows = Integer.parseInt(inputData.substring(0, 1)); + columns = Integer.parseInt(inputData.substring(2, 3)); + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + " "); + } + } + System.out.println(); + } + + private static void odd() { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private static void even() { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + public static void printingResult() { + if (inputData.endsWith("even")) { + System.out.print("Even letters - "); + } else System.out.print("Odd letters - "); + + int counter = 0; + while (counter < result.length()) { + if (counter == result.length() - 1) { + System.out.print(result.charAt(counter)); + break; + } + System.out.print(result.charAt(counter) + ", "); + counter++; + } + } +} From 4d575f21034987b17793828e314957ec34876575 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 18:31:20 +0300 Subject: [PATCH 09/63] README updated --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 940493ad..41936886 100644 --- a/README.md +++ b/README.md @@ -5,5 +5,7 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/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) +| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| +| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From d41b2495d67da8ed06475a0b9aa01916dc8c1883 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Thu, 15 Jul 2021 18:34:25 +0300 Subject: [PATCH 10/63] Update Strategy.java --- src/main/java/homework_2/randomCharsTable/Strategy.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java index 491800a6..38fcfed5 100644 --- a/src/main/java/homework_2/randomCharsTable/Strategy.java +++ b/src/main/java/homework_2/randomCharsTable/Strategy.java @@ -30,7 +30,7 @@ public static void choosingStrategy() throws IOException { printingResult(); } - public static void arrayInitialization() { + private static void arrayInitialization() { rows = Integer.parseInt(inputData.substring(0, 1)); columns = Integer.parseInt(inputData.substring(2, 3)); array = new char[rows][columns]; @@ -64,7 +64,7 @@ private static void even() { } } - public static void printingResult() { + private static void printingResult() { if (inputData.endsWith("even")) { System.out.print("Even letters - "); } else System.out.print("Odd letters - "); From e2a0229b21adffd5e65c3539eccc267d9be72b19 Mon Sep 17 00:00:00 2001 From: Artem Nikolaev Date: Thu, 22 Jul 2021 00:36:11 +0500 Subject: [PATCH 11/63] Add UnitBase.java --- src/test/java/base/UnitBase.java | 73 ++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/test/java/base/UnitBase.java diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java new file mode 100644 index 00000000..97e2685b --- /dev/null +++ b/src/test/java/base/UnitBase.java @@ -0,0 +1,73 @@ +package base; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +public abstract class UnitBase { + + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } + + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } + + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } + + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } + + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } + +// @Test +// void example() { +// setInput("2"); +// +// new PyramidPrinter().run(); +// printOut(); +// removeFromOutput("Please input number"): +// +// assertEquals("x", getOutputLines()[0]); +// assertEquals("xx", getOutputLines()[1]); +// } + +} From ede0736496229c3688877a2846b82c84660dc45c Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:22:49 +0300 Subject: [PATCH 12/63] homework_2 corrected --- .../java/homework_2/pyramidPrinter/Main.java | 8 ++ .../pyramidPrinter/PyramidPrinter.java | 42 +++++-- .../homework_2/randomCharsTable/Main.java | 8 ++ .../randomCharsTable/RandomCharsTable.java | 108 +++++++++++++++- .../homework_2/randomCharsTable/Strategy.java | 82 ------------- .../java/homework_2/trafficLight/Main.java | 12 ++ .../homework_2/trafficLight/Strategy.java | 59 --------- .../homework_2/trafficLight/TrafficLight.java | 83 ++++++++++++- src/test/java/base/UnitBase.java | 73 +++++++++++ .../java/homework_2/PyramidPrinterTest.java | 57 +++++++++ .../java/homework_2/RandomCharsTableTest.java | 47 +++++++ .../java/homework_2/TrafficLightTest.java | 116 ++++++++++++++++++ 12 files changed, 539 insertions(+), 156 deletions(-) create mode 100644 src/main/java/homework_2/pyramidPrinter/Main.java create mode 100644 src/main/java/homework_2/randomCharsTable/Main.java delete mode 100644 src/main/java/homework_2/randomCharsTable/Strategy.java create mode 100644 src/main/java/homework_2/trafficLight/Main.java delete mode 100644 src/main/java/homework_2/trafficLight/Strategy.java create mode 100644 src/test/java/base/UnitBase.java create mode 100644 src/test/java/homework_2/PyramidPrinterTest.java create mode 100644 src/test/java/homework_2/RandomCharsTableTest.java create mode 100644 src/test/java/homework_2/TrafficLightTest.java diff --git a/src/main/java/homework_2/pyramidPrinter/Main.java b/src/main/java/homework_2/pyramidPrinter/Main.java new file mode 100644 index 00000000..033baa95 --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/Main.java @@ -0,0 +1,8 @@ +package homework_2.pyramidPrinter; + +public class Main { + public static void main(String[] args) { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + pyramidPrinter.run(); + } +} diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java index f8b234b8..f25ac445 100644 --- a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -5,17 +5,39 @@ import java.io.InputStreamReader; public class PyramidPrinter { - public static void main(String[] args) { - String output = ""; - int input; + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + System.out.println("Please, input a number:"); + int input = consoleReader(); + if (negativeInput(input)) { + System.out.println(ERROR); + } else if (input == 0) { + System.out.println(); + } else { + printResult(input); + } + } + + private int consoleReader() { try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - input = Integer.parseInt(bF.readLine()); - for (int i = 0; i < input; i++) { - output += "x"; - System.out.println(output); - } - } catch (IOException e) { - System.out.println("Error occurred during input"); + return Integer.parseInt(bF.readLine()); + } catch (NumberFormatException | IOException exception) { + } + return -1; + } + + private void printResult(int input) { + String output = ""; + for (int i = 0; i < input; i++) { + output += "x"; + System.out.println(output); + } + } + + private boolean negativeInput(int n) { + return n < 0; } } diff --git a/src/main/java/homework_2/randomCharsTable/Main.java b/src/main/java/homework_2/randomCharsTable/Main.java new file mode 100644 index 00000000..6641398b --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/Main.java @@ -0,0 +1,8 @@ +package homework_2.randomCharsTable; + +public class Main { + public static void main(String[] args) { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + randomCharsTable.run(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java index 7b4e3c00..cfc24e51 100644 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -1,9 +1,113 @@ package homework_2.randomCharsTable; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; public class RandomCharsTable { - public static void main(String[] args) throws IOException { - Strategy.choosingStrategy(); + + private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + private char[][] array; + + private String strategy; + + private String inputData; + + private String result; + + private int rows; + + private int columns; + + public void run() { + System.out.println("Enter data in format: width, length of matrix and strategy (even/odd)"); + inputData = readingConsole(); + parseData(inputData); + if (dataValidation(rows, columns, strategy)) { + return; + } + arrayInitialization(); + if (inputData.endsWith("odd")) { + odd(); + } else { + even(); + } + printingResult(); + } + + private void parseData(String s){ + String[] resultArray = s.split(" "); + if(resultArray.length != 3){ + System.out.println(ERROR); + return; + } + rows = Integer.parseInt(resultArray[0]); + columns = Integer.parseInt(resultArray[1]); + strategy = resultArray[2]; + } + + private void arrayInitialization() { + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + System.out.print("|"); + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + " |"); + } + System.out.println(); + } + } + + private void odd() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private void even() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + private void printingResult() { + if (strategy.equals("even")) { + System.out.print("Even letters - "); + } else System.out.print("Odd letters - "); + int counter = 0; + while (counter < result.length()) { + if (counter == result.length() - 1) { + System.out.print(result.charAt(counter)); + break; + } + System.out.print(result.charAt(counter) + ", "); + counter++; + } + } + + private String readingConsole() { + inputData = ""; + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + inputData = bF.readLine(); + } catch (IOException exc) { + System.out.println("Error occurred during input"); + } + return inputData; + } + + private boolean dataValidation(int x, int y, String str) { + return x < 1 || y < 1 || (!str.equals("odd") && !str.equals("even")); } } diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java deleted file mode 100644 index 491800a6..00000000 --- a/src/main/java/homework_2/randomCharsTable/Strategy.java +++ /dev/null @@ -1,82 +0,0 @@ -package homework_2.randomCharsTable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class Strategy { - public static char[][] array; - - private final static BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); - - private static String inputData; - - private static String result = ""; - - private static int rows; - - private static int columns; - - public static void choosingStrategy() throws IOException { - System.out.println("Enter necessary data."); - inputData = bF.readLine(); - String strategy = inputData.trim(); - arrayInitialization(); - if (strategy.endsWith("odd")) { - odd(); - } else { - even(); - } - printingResult(); - } - - public static void arrayInitialization() { - rows = Integer.parseInt(inputData.substring(0, 1)); - columns = Integer.parseInt(inputData.substring(2, 3)); - array = new char[rows][columns]; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - char letters = (char) (Math.random() * 10 + 65); - array[i][j] = letters; - System.out.print(array[i][j] + " "); - } - } - System.out.println(); - } - - private static void odd() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 1) { - result += array[i][j]; - } - } - } - } - - private static void even() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 0) { - result += array[i][j]; - } - } - } - } - - public static void printingResult() { - if (inputData.endsWith("even")) { - System.out.print("Even letters - "); - } else System.out.print("Odd letters - "); - - int counter = 0; - while (counter < result.length()) { - if (counter == result.length() - 1) { - System.out.print(result.charAt(counter)); - break; - } - System.out.print(result.charAt(counter) + ", "); - counter++; - } - } -} diff --git a/src/main/java/homework_2/trafficLight/Main.java b/src/main/java/homework_2/trafficLight/Main.java new file mode 100644 index 00000000..50bb55af --- /dev/null +++ b/src/main/java/homework_2/trafficLight/Main.java @@ -0,0 +1,12 @@ +package homework_2.trafficLight; + +public class Main { + public static void main(String[] args) { + TrafficLight trafficLight = new TrafficLight(); + if(args[0].equals("seconds")){ + trafficLight.runSecondsFormat(); + } else { + trafficLight.runTimeFormat(); + } + } +} diff --git a/src/main/java/homework_2/trafficLight/Strategy.java b/src/main/java/homework_2/trafficLight/Strategy.java deleted file mode 100644 index 12a9eaa3..00000000 --- a/src/main/java/homework_2/trafficLight/Strategy.java +++ /dev/null @@ -1,59 +0,0 @@ -package homework_2.trafficLight; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class Strategy { - private final BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); - - private final String ANSI_RESET = "\u001b[0m"; - - private final String ANSI_RED = "\u001B[31m"; - - private final String ANSI_GREED = "\u001B[32m"; - - private final String ANSI_YELLOW = "\u001B[33m"; - - private int seconds; - - private final boolean greenLight = seconds % 60 < 35; - - private final boolean yellowLight = seconds % 60 >= 35 && seconds % 60 <= 40 || seconds % 60 >= 55; - - public void choosingStrategy() throws IOException { - System.out.println(""" - Choose input format:\s - 1.HH:MM:SS format - 2.Total amount of seconds."""); - String strategy = bF.readLine(); - if (strategy.startsWith("1")) { - timeFormat(); - } else secondsFormat(); - } - - private void secondsFormat() throws IOException { - System.out.println("Enter necessary amount of seconds."); - seconds = Integer.parseInt(bF.readLine()); - if (seconds > 86399) { - System.out.println("Day is over"); - return; - } - if (greenLight) { - System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); - } else if (yellowLight) { - System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); - } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); - } - - private void timeFormat() throws IOException { - System.out.println("Enter necessary amount of seconds."); - String parsedTime = bF.readLine(); - seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); - if (greenLight) { - System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); - } else if (yellowLight) { - System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); - } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); - } -} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java index 2d17b3f2..04ca26bd 100644 --- a/src/main/java/homework_2/trafficLight/TrafficLight.java +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -1,10 +1,87 @@ package homework_2.trafficLight; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; public class TrafficLight { - public static void main(String[] args) throws IOException { - Strategy strategy = new Strategy(); - strategy.choosingStrategy(); + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + public final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + private int seconds; + + public void runSecondsFormat() { + System.out.println("Enter necessary amount of seconds."); + String input = consoleReader(); + if(!isDigit(input)) { + System.out.println(ERROR); + return; + } + seconds = Integer.parseInt(input); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + if (!dayOverCheck(seconds)) { + System.out.println("Day is over"); + return; + } + trafficLightColorDetection(seconds); + } + + public void runTimeFormat() { + System.out.println("Enter necessary time in HH:MM:SS format."); + String parsedTime = consoleReader(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + trafficLightColorDetection(seconds); + } + + private String consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return bF.readLine(); + } catch (NumberFormatException | IOException e) { + + } + return ""; + } + + private void trafficLightColorDetection(int sec) { + if (sec % 60 < 35) { + System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); + } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { + System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else { + System.out.print(ANSI_RED + "Red light" + ANSI_RESET); + } + } + + private boolean isNegative(int input) { + return input < 0; + } + + private boolean dayOverCheck(int input) { + return input < 86399; + } + + private boolean isDigit(String input) { + try{ + Integer.parseInt(input); + return true; + } catch (NumberFormatException e) { + return false; + } } } + diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java new file mode 100644 index 00000000..8b46be60 --- /dev/null +++ b/src/test/java/base/UnitBase.java @@ -0,0 +1,73 @@ +package base; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +public abstract class UnitBase { + + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } + + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } + + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } + + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } + + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } + +// @Test +// void example() { +// setInput("2"); +// +// new PyramidPrinter().run(); +// printOut(); +// removeFromOutput("Please input number"): +// +// assertEquals("x", getOutputLines()[0]); +// assertEquals("xx", getOutputLines()[1]); +// } + +} diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java new file mode 100644 index 00000000..c140c04c --- /dev/null +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -0,0 +1,57 @@ +package homework_2; + +import base.UnitBase; +import homework_2.pyramidPrinter.PyramidPrinter; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class PyramidPrinterTest extends UnitBase { + + @Test + void given5_whenRun_thenFiveLinesPrinted() { + setInput("5"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("x", getOutputLines()[0]); + Assertions.assertEquals("xx", getOutputLines()[1]); + Assertions.assertEquals("xxx", getOutputLines()[2]); + Assertions.assertEquals("xxxx", getOutputLines()[3]); + Assertions.assertEquals("xxxxx", getOutputLines()[4]); + } + + @Test + void givenZero_whenRun_thenEmpty() { + setInput("0"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("", getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_thenError() { + setInput("-1"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } + + @Test + void givenNaN_whenRun_thenError() { + setInput("text"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } +} diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java new file mode 100644 index 00000000..82876448 --- /dev/null +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -0,0 +1,47 @@ +package homework_2; + +import base.UnitBase; +import homework_2.randomCharsTable.RandomCharsTable; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class RandomCharsTableTest extends UnitBase { + + @Test + void givenTwoTwoEven_whenRun_thenMatrixAndLettersPrinted(){ + setInput("2 2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertTrue(getOutput().contains("|")); + Assertions.assertTrue(getOutput().contains(" |")); + Assertions.assertTrue(getOutput().contains("Even letters - ")); + } + + @Test + void givenTwoThreeOdd_whenRun_thenMatrixAndLettersPrinted(){ + setInput("2 3 odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertTrue(getOutput().contains("|")); + Assertions.assertTrue(getOutput().contains(" |")); + Assertions.assertTrue(getOutput().contains("Odd letters - ")); + } + + @Test + void givenNotFullParameters_whenRun_thenError(){ + setInput("2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertEquals("Passed parameters should match the format [positive integer] " + + "[positive integer] [even|odd]",getOutput()); + } +} diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java new file mode 100644 index 00000000..5a3e31d5 --- /dev/null +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -0,0 +1,116 @@ +package homework_2; + +import base.UnitBase; +import homework_2.trafficLight.TrafficLight; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class TrafficLightTest extends UnitBase { + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + private final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + @Test + void given0_whenRun_thenGreenLightPrinted(){ + setInput("0"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[32m")); + } + + @Test + void given35_whenRun_thenYellowLightPrinted(){ + setInput("35"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[33m")); + } + + @Test + void given54_whenRun_thenRedLightPrinted(){ + setInput("54"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[31m")); + } + + @Test + void given863400_whenRun_thenDayIsOverPrinted(){ + setInput("863400"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Day is over")); + } + + @Test + void givenFiveSecTimeFormat_whenRun_thenGreenLightPrinted(){ + setInput("23:25:05"); + + new TrafficLight().runTimeFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[32m")); + } + + @Test + void givenThirtyFiveSecTimeFormat_whenRun_thenYellowLightPrinted(){ + setInput("14:54:35"); + + new TrafficLight().runTimeFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[33m")); + } + + @Test + void givenFiftyFourSecTimeFormat_whenRun_thenRedLightPrinted(){ + setInput("07:56:54"); + + new TrafficLight().runTimeFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[31m")); + } + + @Test + void givenNegativeNumber_whenRun_thenError(){ + setInput("-56"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + @Test + void givenNaN_whenRun_thenError(){ + setInput("text"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } +} From 579a708f80d4b397f12aa32ac0ad22c0f996adb7 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:29:40 +0300 Subject: [PATCH 13/63] homework_2 corrected --- .../java/homework_2/pyramidPrinter/Main.java | 8 -- .../pyramidPrinter/PyramidPrinter.java | 43 ------- .../homework_2/randomCharsTable/Main.java | 8 -- .../randomCharsTable/RandomCharsTable.java | 113 ------------------ .../java/homework_2/trafficLight/Main.java | 12 -- .../homework_2/trafficLight/TrafficLight.java | 87 -------------- 6 files changed, 271 deletions(-) delete mode 100644 src/main/java/homework_2/pyramidPrinter/Main.java delete mode 100644 src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java delete mode 100644 src/main/java/homework_2/randomCharsTable/Main.java delete mode 100644 src/main/java/homework_2/randomCharsTable/RandomCharsTable.java delete mode 100644 src/main/java/homework_2/trafficLight/Main.java delete mode 100644 src/main/java/homework_2/trafficLight/TrafficLight.java diff --git a/src/main/java/homework_2/pyramidPrinter/Main.java b/src/main/java/homework_2/pyramidPrinter/Main.java deleted file mode 100644 index 033baa95..00000000 --- a/src/main/java/homework_2/pyramidPrinter/Main.java +++ /dev/null @@ -1,8 +0,0 @@ -package homework_2.pyramidPrinter; - -public class Main { - public static void main(String[] args) { - PyramidPrinter pyramidPrinter = new PyramidPrinter(); - pyramidPrinter.run(); - } -} diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java deleted file mode 100644 index f25ac445..00000000 --- a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java +++ /dev/null @@ -1,43 +0,0 @@ -package homework_2.pyramidPrinter; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class PyramidPrinter { - - private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; - - public void run() { - System.out.println("Please, input a number:"); - int input = consoleReader(); - if (negativeInput(input)) { - System.out.println(ERROR); - } else if (input == 0) { - System.out.println(); - } else { - printResult(input); - } - } - - private int consoleReader() { - try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - return Integer.parseInt(bF.readLine()); - } catch (NumberFormatException | IOException exception) { - - } - return -1; - } - - private void printResult(int input) { - String output = ""; - for (int i = 0; i < input; i++) { - output += "x"; - System.out.println(output); - } - } - - private boolean negativeInput(int n) { - return n < 0; - } -} diff --git a/src/main/java/homework_2/randomCharsTable/Main.java b/src/main/java/homework_2/randomCharsTable/Main.java deleted file mode 100644 index 6641398b..00000000 --- a/src/main/java/homework_2/randomCharsTable/Main.java +++ /dev/null @@ -1,8 +0,0 @@ -package homework_2.randomCharsTable; - -public class Main { - public static void main(String[] args) { - RandomCharsTable randomCharsTable = new RandomCharsTable(); - randomCharsTable.run(); - } -} \ No newline at end of file diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java deleted file mode 100644 index cfc24e51..00000000 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ /dev/null @@ -1,113 +0,0 @@ -package homework_2.randomCharsTable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class RandomCharsTable { - - private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; - - private char[][] array; - - private String strategy; - - private String inputData; - - private String result; - - private int rows; - - private int columns; - - public void run() { - System.out.println("Enter data in format: width, length of matrix and strategy (even/odd)"); - inputData = readingConsole(); - parseData(inputData); - if (dataValidation(rows, columns, strategy)) { - return; - } - arrayInitialization(); - if (inputData.endsWith("odd")) { - odd(); - } else { - even(); - } - printingResult(); - } - - private void parseData(String s){ - String[] resultArray = s.split(" "); - if(resultArray.length != 3){ - System.out.println(ERROR); - return; - } - rows = Integer.parseInt(resultArray[0]); - columns = Integer.parseInt(resultArray[1]); - strategy = resultArray[2]; - } - - private void arrayInitialization() { - array = new char[rows][columns]; - for (int i = 0; i < rows; i++) { - System.out.print("|"); - for (int j = 0; j < columns; j++) { - char letters = (char) (Math.random() * 10 + 65); - array[i][j] = letters; - System.out.print(array[i][j] + " |"); - } - System.out.println(); - } - } - - private void odd() { - result = ""; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 1) { - result += array[i][j]; - } - } - } - } - - private void even() { - result = ""; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 0) { - result += array[i][j]; - } - } - } - } - - private void printingResult() { - if (strategy.equals("even")) { - System.out.print("Even letters - "); - } else System.out.print("Odd letters - "); - int counter = 0; - while (counter < result.length()) { - if (counter == result.length() - 1) { - System.out.print(result.charAt(counter)); - break; - } - System.out.print(result.charAt(counter) + ", "); - counter++; - } - } - - private String readingConsole() { - inputData = ""; - try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - inputData = bF.readLine(); - } catch (IOException exc) { - System.out.println("Error occurred during input"); - } - return inputData; - } - - private boolean dataValidation(int x, int y, String str) { - return x < 1 || y < 1 || (!str.equals("odd") && !str.equals("even")); - } -} diff --git a/src/main/java/homework_2/trafficLight/Main.java b/src/main/java/homework_2/trafficLight/Main.java deleted file mode 100644 index 50bb55af..00000000 --- a/src/main/java/homework_2/trafficLight/Main.java +++ /dev/null @@ -1,12 +0,0 @@ -package homework_2.trafficLight; - -public class Main { - public static void main(String[] args) { - TrafficLight trafficLight = new TrafficLight(); - if(args[0].equals("seconds")){ - trafficLight.runSecondsFormat(); - } else { - trafficLight.runTimeFormat(); - } - } -} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java deleted file mode 100644 index 04ca26bd..00000000 --- a/src/main/java/homework_2/trafficLight/TrafficLight.java +++ /dev/null @@ -1,87 +0,0 @@ -package homework_2.trafficLight; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class TrafficLight { - - private final String ANSI_RESET = "\u001b[0m"; - - private final String ANSI_RED = "\u001B[31m"; - - public final String ANSI_GREEN = "\u001B[32m"; - - private final String ANSI_YELLOW = "\u001B[33m"; - - private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; - - private int seconds; - - public void runSecondsFormat() { - System.out.println("Enter necessary amount of seconds."); - String input = consoleReader(); - if(!isDigit(input)) { - System.out.println(ERROR); - return; - } - seconds = Integer.parseInt(input); - if (isNegative(seconds)) { - System.out.println(ERROR); - return; - } - if (!dayOverCheck(seconds)) { - System.out.println("Day is over"); - return; - } - trafficLightColorDetection(seconds); - } - - public void runTimeFormat() { - System.out.println("Enter necessary time in HH:MM:SS format."); - String parsedTime = consoleReader(); - seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); - if (isNegative(seconds)) { - System.out.println(ERROR); - return; - } - trafficLightColorDetection(seconds); - } - - private String consoleReader() { - try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - return bF.readLine(); - } catch (NumberFormatException | IOException e) { - - } - return ""; - } - - private void trafficLightColorDetection(int sec) { - if (sec % 60 < 35) { - System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); - } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { - System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); - } else { - System.out.print(ANSI_RED + "Red light" + ANSI_RESET); - } - } - - private boolean isNegative(int input) { - return input < 0; - } - - private boolean dayOverCheck(int input) { - return input < 86399; - } - - private boolean isDigit(String input) { - try{ - Integer.parseInt(input); - return true; - } catch (NumberFormatException e) { - return false; - } - } -} - From 385c677e9ef95ced2d3616b4187d434e402981a1 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:30:59 +0300 Subject: [PATCH 14/63] homework_2 corrected --- .../java/homework_2/pyramidPrinter/Main.java | 8 ++ .../pyramidPrinter/PyramidPrinter.java | 43 +++++++ .../homework_2/randomCharsTable/Main.java | 8 ++ .../randomCharsTable/RandomCharsTable.java | 113 ++++++++++++++++++ .../java/homework_2/trafficLight/Main.java | 12 ++ .../homework_2/trafficLight/TrafficLight.java | 87 ++++++++++++++ 6 files changed, 271 insertions(+) create mode 100644 src/main/java/homework_2/pyramidPrinter/Main.java create mode 100644 src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java create mode 100644 src/main/java/homework_2/randomCharsTable/Main.java create mode 100644 src/main/java/homework_2/randomCharsTable/RandomCharsTable.java create mode 100644 src/main/java/homework_2/trafficLight/Main.java create mode 100644 src/main/java/homework_2/trafficLight/TrafficLight.java diff --git a/src/main/java/homework_2/pyramidPrinter/Main.java b/src/main/java/homework_2/pyramidPrinter/Main.java new file mode 100644 index 00000000..033baa95 --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/Main.java @@ -0,0 +1,8 @@ +package homework_2.pyramidPrinter; + +public class Main { + public static void main(String[] args) { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + pyramidPrinter.run(); + } +} diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java new file mode 100644 index 00000000..f25ac445 --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -0,0 +1,43 @@ +package homework_2.pyramidPrinter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + System.out.println("Please, input a number:"); + int input = consoleReader(); + if (negativeInput(input)) { + System.out.println(ERROR); + } else if (input == 0) { + System.out.println(); + } else { + printResult(input); + } + } + + private int consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return Integer.parseInt(bF.readLine()); + } catch (NumberFormatException | IOException exception) { + + } + return -1; + } + + private void printResult(int input) { + String output = ""; + for (int i = 0; i < input; i++) { + output += "x"; + System.out.println(output); + } + } + + private boolean negativeInput(int n) { + return n < 0; + } +} diff --git a/src/main/java/homework_2/randomCharsTable/Main.java b/src/main/java/homework_2/randomCharsTable/Main.java new file mode 100644 index 00000000..6641398b --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/Main.java @@ -0,0 +1,8 @@ +package homework_2.randomCharsTable; + +public class Main { + public static void main(String[] args) { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + randomCharsTable.run(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java new file mode 100644 index 00000000..cfc24e51 --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -0,0 +1,113 @@ +package homework_2.randomCharsTable; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + + private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + private char[][] array; + + private String strategy; + + private String inputData; + + private String result; + + private int rows; + + private int columns; + + public void run() { + System.out.println("Enter data in format: width, length of matrix and strategy (even/odd)"); + inputData = readingConsole(); + parseData(inputData); + if (dataValidation(rows, columns, strategy)) { + return; + } + arrayInitialization(); + if (inputData.endsWith("odd")) { + odd(); + } else { + even(); + } + printingResult(); + } + + private void parseData(String s){ + String[] resultArray = s.split(" "); + if(resultArray.length != 3){ + System.out.println(ERROR); + return; + } + rows = Integer.parseInt(resultArray[0]); + columns = Integer.parseInt(resultArray[1]); + strategy = resultArray[2]; + } + + private void arrayInitialization() { + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + System.out.print("|"); + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + " |"); + } + System.out.println(); + } + } + + private void odd() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private void even() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + private void printingResult() { + if (strategy.equals("even")) { + System.out.print("Even letters - "); + } else System.out.print("Odd letters - "); + int counter = 0; + while (counter < result.length()) { + if (counter == result.length() - 1) { + System.out.print(result.charAt(counter)); + break; + } + System.out.print(result.charAt(counter) + ", "); + counter++; + } + } + + private String readingConsole() { + inputData = ""; + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + inputData = bF.readLine(); + } catch (IOException exc) { + System.out.println("Error occurred during input"); + } + return inputData; + } + + private boolean dataValidation(int x, int y, String str) { + return x < 1 || y < 1 || (!str.equals("odd") && !str.equals("even")); + } +} diff --git a/src/main/java/homework_2/trafficLight/Main.java b/src/main/java/homework_2/trafficLight/Main.java new file mode 100644 index 00000000..50bb55af --- /dev/null +++ b/src/main/java/homework_2/trafficLight/Main.java @@ -0,0 +1,12 @@ +package homework_2.trafficLight; + +public class Main { + public static void main(String[] args) { + TrafficLight trafficLight = new TrafficLight(); + if(args[0].equals("seconds")){ + trafficLight.runSecondsFormat(); + } else { + trafficLight.runTimeFormat(); + } + } +} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java new file mode 100644 index 00000000..04ca26bd --- /dev/null +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -0,0 +1,87 @@ +package homework_2.trafficLight; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + public final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + private int seconds; + + public void runSecondsFormat() { + System.out.println("Enter necessary amount of seconds."); + String input = consoleReader(); + if(!isDigit(input)) { + System.out.println(ERROR); + return; + } + seconds = Integer.parseInt(input); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + if (!dayOverCheck(seconds)) { + System.out.println("Day is over"); + return; + } + trafficLightColorDetection(seconds); + } + + public void runTimeFormat() { + System.out.println("Enter necessary time in HH:MM:SS format."); + String parsedTime = consoleReader(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + trafficLightColorDetection(seconds); + } + + private String consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return bF.readLine(); + } catch (NumberFormatException | IOException e) { + + } + return ""; + } + + private void trafficLightColorDetection(int sec) { + if (sec % 60 < 35) { + System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); + } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { + System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else { + System.out.print(ANSI_RED + "Red light" + ANSI_RESET); + } + } + + private boolean isNegative(int input) { + return input < 0; + } + + private boolean dayOverCheck(int input) { + return input < 86399; + } + + private boolean isDigit(String input) { + try{ + Integer.parseInt(input); + return true; + } catch (NumberFormatException e) { + return false; + } + } +} + From 7f07dad77c4aaf2acfa24541288609662e5cd30d Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:34:24 +0300 Subject: [PATCH 15/63] Delete Strategy.java --- .../homework_2/randomCharsTable/Strategy.java | 82 ------------------- 1 file changed, 82 deletions(-) delete mode 100644 src/main/java/homework_2/randomCharsTable/Strategy.java diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java deleted file mode 100644 index 38fcfed5..00000000 --- a/src/main/java/homework_2/randomCharsTable/Strategy.java +++ /dev/null @@ -1,82 +0,0 @@ -package homework_2.randomCharsTable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class Strategy { - public static char[][] array; - - private final static BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); - - private static String inputData; - - private static String result = ""; - - private static int rows; - - private static int columns; - - public static void choosingStrategy() throws IOException { - System.out.println("Enter necessary data."); - inputData = bF.readLine(); - String strategy = inputData.trim(); - arrayInitialization(); - if (strategy.endsWith("odd")) { - odd(); - } else { - even(); - } - printingResult(); - } - - private static void arrayInitialization() { - rows = Integer.parseInt(inputData.substring(0, 1)); - columns = Integer.parseInt(inputData.substring(2, 3)); - array = new char[rows][columns]; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - char letters = (char) (Math.random() * 10 + 65); - array[i][j] = letters; - System.out.print(array[i][j] + " "); - } - } - System.out.println(); - } - - private static void odd() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 1) { - result += array[i][j]; - } - } - } - } - - private static void even() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 0) { - result += array[i][j]; - } - } - } - } - - private static void printingResult() { - if (inputData.endsWith("even")) { - System.out.print("Even letters - "); - } else System.out.print("Odd letters - "); - - int counter = 0; - while (counter < result.length()) { - if (counter == result.length() - 1) { - System.out.print(result.charAt(counter)); - break; - } - System.out.print(result.charAt(counter) + ", "); - counter++; - } - } -} From 1a6933dcc5bc964bb1b7e0cfa45c589031ac8df5 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:36:48 +0300 Subject: [PATCH 16/63] README updated --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 41936886..9950634a 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,4 @@ | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) From 4f3efcd555c12ebdcb9c94240289a8fec95caef8 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:37:25 +0300 Subject: [PATCH 17/63] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 41936886..7eaee314 100644 --- a/README.md +++ b/README.md @@ -8,4 +8,5 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +[Link to markdown guide](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 835d06c228fd4571283784821831177e2d7ef882 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:37:58 +0300 Subject: [PATCH 18/63] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7eaee314..a155cfd0 100644 --- a/README.md +++ b/README.md @@ -8,5 +8,5 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| -[Link to markdown guide](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) +[Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 42abc6594c8e8a992b931e5b3dda98ae9c6485f4 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:42:09 +0300 Subject: [PATCH 19/63] README updated --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 52a7cc2f..a155cfd0 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,3 @@ | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) -[Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) From a9b9d092b6df0deaae41faf8232696167db0e7e9 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:56:04 +0300 Subject: [PATCH 20/63] package naming corrected --- src/main/java/homework_3/ImmutableClass.java | 49 ++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/homework_3/ImmutableClass.java diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..d7f77ee9 --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,49 @@ +package homework_3; + +import java.util.List; + +final class ImmutableClass { + + private final int firstInt; + + private final String firstString; + + private final int[] firstIntArray; + + private final String[] firstStringArray; + + private final List firstCollection; + + + ImmutableClass(int firstInt, String firstString, int[] firstIntArray, String[] firstStringArray, List firstCollection) { + this.firstInt = firstInt; + this.firstString = firstString; + this.firstIntArray = firstIntArray; + this.firstStringArray = firstStringArray; + this.firstCollection = firstCollection; + } + + public int getFirstInt() { + return firstInt; + } + + public String getFirstString() { + return firstString; + } + + public int[] getFirstIntArray() { + return firstIntArray; + } + + public String[] getFirstStringArray() { + return firstStringArray; + } + + public List getFirstCollection() { + return firstCollection; + } + + public ImmutableClass getNewImmutableClass(int x, String y, int[] xy, String[] yx, List list) { + return new ImmutableClass(x,y,xy,yx,list); + } +} From 4019fa671700d4fd5da7bacffc2f66ce48478ec1 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:58:11 +0300 Subject: [PATCH 21/63] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a155cfd0..8b8e2b0a 100644 --- a/README.md +++ b/README.md @@ -8,5 +8,7 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +| HW3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| + [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From ad9cbb36836a64522d35213745fb564e8f060c33 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:58:28 +0300 Subject: [PATCH 22/63] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8b8e2b0a..46736de7 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| -| HW3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| +| HW3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From c88d8789dfd83515f33c2653429c70f15b4645b2 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 05:05:32 +0300 Subject: [PATCH 23/63] UnitBase merged --- src/test/java/base/UnitBase.java | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 8b46be60..5cdc43ee 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -10,6 +10,54 @@ public abstract class UnitBase { + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } + + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } + + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } + + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } + + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); protected final PrintStream originalOut = System.out; protected final InputStream originalIn = System.in; @@ -58,6 +106,7 @@ protected void printOut() { System.setOut(new PrintStream(mockedOut)); } + // @Test // void example() { // setInput("2"); From 3fcf714269a2bd25450318499a04baaabf31721f Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 05:06:36 +0300 Subject: [PATCH 24/63] Delete UnitBase.java --- src/test/java/base/UnitBase.java | 122 ------------------------------- 1 file changed, 122 deletions(-) delete mode 100644 src/test/java/base/UnitBase.java diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java deleted file mode 100644 index 5cdc43ee..00000000 --- a/src/test/java/base/UnitBase.java +++ /dev/null @@ -1,122 +0,0 @@ -package base; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -public abstract class UnitBase { - - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; - - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } - - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } - - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } - - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } - - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } - - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } - - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; - - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } - - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } - - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } - - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } - - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } - - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } - - -// @Test -// void example() { -// setInput("2"); -// -// new PyramidPrinter().run(); -// printOut(); -// removeFromOutput("Please input number"): -// -// assertEquals("x", getOutputLines()[0]); -// assertEquals("xx", getOutputLines()[1]); -// } - -} From 988376a58d5ecfb19afc1fc38635de9b694ec0aa Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Fri, 9 Jul 2021 21:51:11 +0300 Subject: [PATCH 25/63] gitignore updated --- README.md | 4 ++-- src/main/java/homework_1/CommandLineArgs.java | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 src/main/java/homework_1/CommandLineArgs.java diff --git a/README.md b/README.md index 5d686e9f..a59f7d31 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Krylosov Arkadiy* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady``/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) diff --git a/src/main/java/homework_1/CommandLineArgs.java b/src/main/java/homework_1/CommandLineArgs.java new file mode 100644 index 00000000..dd73b5f9 --- /dev/null +++ b/src/main/java/homework_1/CommandLineArgs.java @@ -0,0 +1,20 @@ +package Homework_1; + +public class CommandLineArgs { + + public static final String ANSI_RED = "\u001B[31m"; + + public static final String ANSI_RESET = "\u001B[0m"; + + public static void main(String[] args) { + for (String s : args) { + if (s.equals("error")) { + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); + break; + } else { + System.out.println(s + ": " + s.length() + " letters"); + } + } + } +} + From 0f600b5765cc755dcf2ca5bb00e4810c1bdda3b6 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Fri, 9 Jul 2021 21:53:44 +0300 Subject: [PATCH 26/63] gitignore updated --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a59f7d31..940493ad 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/tree/feature/KrylosovArkady``/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/KrylosovArkady/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 3e1d9950b6af2e0da9cb440abdaa38775b5cd3c4 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Fri, 9 Jul 2021 21:55:32 +0300 Subject: [PATCH 27/63] Delete Main.java --- src/main/java/homework_1/Main.java | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 src/main/java/homework_1/Main.java diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java deleted file mode 100644 index 07c029a2..00000000 --- a/src/main/java/homework_1/Main.java +++ /dev/null @@ -1,9 +0,0 @@ -package homework_1; - -public class Main { - - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - -} From 231c3e95e02460fc65b974989fd5dba8bd5d4574 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:00:48 +0300 Subject: [PATCH 28/63] homework_2 done. --- src/main/java/homework_2/trafficLight/TrafficLight.java | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 src/main/java/homework_2/trafficLight/TrafficLight.java diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java new file mode 100644 index 00000000..80692449 --- /dev/null +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -0,0 +1,4 @@ +package homework_2.trafficLight; + +public class TrafficLight { +} From 30b783ec75565273035fbd530e721a3474fd5564 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:05:47 +0300 Subject: [PATCH 29/63] homework_2 done. --- .../pyramidPrinter/PyramidPrinter.java | 21 +++++++++++++++++++ .../randomCharsTable/RandomCharsTable.java | 4 ++++ 2 files changed, 25 insertions(+) create mode 100644 src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java create mode 100644 src/main/java/homework_2/randomCharsTable/RandomCharsTable.java diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java new file mode 100644 index 00000000..cc2006fb --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -0,0 +1,21 @@ +package homework_2.pyramidPrinter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + public static void main(String[] args) { + String output = ""; + int input; + try(BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))){ + input = Integer.parseInt(bF.readLine()); + for (int i = 0; i < input; i++) { + output += "x"; + System.out.println(output); + } + } catch (IOException e){ + System.out.println("Error occurred during input"); + } + } +} diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java new file mode 100644 index 00000000..62c32b95 --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -0,0 +1,4 @@ +package homework_2.randomCharsTable; + +public class RandomCharsTable { +} From 6bba87887b73e611d3baa8401f42b9188c6fc717 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:06:12 +0300 Subject: [PATCH 30/63] homework_2 done. --- src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java index cc2006fb..f8b234b8 100644 --- a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -8,13 +8,13 @@ public class PyramidPrinter { public static void main(String[] args) { String output = ""; int input; - try(BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))){ + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { input = Integer.parseInt(bF.readLine()); for (int i = 0; i < input; i++) { output += "x"; System.out.println(output); } - } catch (IOException e){ + } catch (IOException e) { System.out.println("Error occurred during input"); } } From ea7c10a2d896233864c6d1cd25cf106021da39c1 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 17:28:39 +0300 Subject: [PATCH 31/63] homework_2 done. --- .../randomCharsTable/RandomCharsTable.java | 3 + .../homework_2/trafficLight/Strategy.java | 59 +++++++++++++++++++ .../homework_2/trafficLight/TrafficLight.java | 6 ++ 3 files changed, 68 insertions(+) create mode 100644 src/main/java/homework_2/trafficLight/Strategy.java diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java index 62c32b95..3821f5b3 100644 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -1,4 +1,7 @@ package homework_2.randomCharsTable; public class RandomCharsTable { + public static void main(String[] args) { + + } } diff --git a/src/main/java/homework_2/trafficLight/Strategy.java b/src/main/java/homework_2/trafficLight/Strategy.java new file mode 100644 index 00000000..12a9eaa3 --- /dev/null +++ b/src/main/java/homework_2/trafficLight/Strategy.java @@ -0,0 +1,59 @@ +package homework_2.trafficLight; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Strategy { + private final BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + private final String ANSI_GREED = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + private int seconds; + + private final boolean greenLight = seconds % 60 < 35; + + private final boolean yellowLight = seconds % 60 >= 35 && seconds % 60 <= 40 || seconds % 60 >= 55; + + public void choosingStrategy() throws IOException { + System.out.println(""" + Choose input format:\s + 1.HH:MM:SS format + 2.Total amount of seconds."""); + String strategy = bF.readLine(); + if (strategy.startsWith("1")) { + timeFormat(); + } else secondsFormat(); + } + + private void secondsFormat() throws IOException { + System.out.println("Enter necessary amount of seconds."); + seconds = Integer.parseInt(bF.readLine()); + if (seconds > 86399) { + System.out.println("Day is over"); + return; + } + if (greenLight) { + System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); + } else if (yellowLight) { + System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); + } + + private void timeFormat() throws IOException { + System.out.println("Enter necessary amount of seconds."); + String parsedTime = bF.readLine(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (greenLight) { + System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); + } else if (yellowLight) { + System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); + } +} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java index 80692449..2d17b3f2 100644 --- a/src/main/java/homework_2/trafficLight/TrafficLight.java +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -1,4 +1,10 @@ package homework_2.trafficLight; +import java.io.IOException; + public class TrafficLight { + public static void main(String[] args) throws IOException { + Strategy strategy = new Strategy(); + strategy.choosingStrategy(); + } } From 566d965915186b4b980ce32c952b47d9fa9d480e Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 18:20:42 +0300 Subject: [PATCH 32/63] homework_2 done. --- .../randomCharsTable/RandomCharsTable.java | 6 +- .../homework_2/randomCharsTable/Strategy.java | 82 +++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 src/main/java/homework_2/randomCharsTable/Strategy.java diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java index 3821f5b3..7b4e3c00 100644 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -1,7 +1,9 @@ package homework_2.randomCharsTable; -public class RandomCharsTable { - public static void main(String[] args) { +import java.io.IOException; +public class RandomCharsTable { + public static void main(String[] args) throws IOException { + Strategy.choosingStrategy(); } } diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java new file mode 100644 index 00000000..491800a6 --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/Strategy.java @@ -0,0 +1,82 @@ +package homework_2.randomCharsTable; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Strategy { + public static char[][] array; + + private final static BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); + + private static String inputData; + + private static String result = ""; + + private static int rows; + + private static int columns; + + public static void choosingStrategy() throws IOException { + System.out.println("Enter necessary data."); + inputData = bF.readLine(); + String strategy = inputData.trim(); + arrayInitialization(); + if (strategy.endsWith("odd")) { + odd(); + } else { + even(); + } + printingResult(); + } + + public static void arrayInitialization() { + rows = Integer.parseInt(inputData.substring(0, 1)); + columns = Integer.parseInt(inputData.substring(2, 3)); + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + " "); + } + } + System.out.println(); + } + + private static void odd() { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private static void even() { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + public static void printingResult() { + if (inputData.endsWith("even")) { + System.out.print("Even letters - "); + } else System.out.print("Odd letters - "); + + int counter = 0; + while (counter < result.length()) { + if (counter == result.length() - 1) { + System.out.print(result.charAt(counter)); + break; + } + System.out.print(result.charAt(counter) + ", "); + counter++; + } + } +} From 5d27087a312324b71db332646e0a5f1cbae087a8 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 15 Jul 2021 18:31:20 +0300 Subject: [PATCH 33/63] README updated --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 940493ad..41936886 100644 --- a/README.md +++ b/README.md @@ -5,5 +5,7 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/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) +| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| +| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From eb00857fd1a9349b9b36c94f170fa0d2297262e1 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:22:49 +0300 Subject: [PATCH 34/63] homework_2 corrected --- .../java/homework_2/pyramidPrinter/Main.java | 8 ++ .../pyramidPrinter/PyramidPrinter.java | 42 +++++-- .../homework_2/randomCharsTable/Main.java | 8 ++ .../randomCharsTable/RandomCharsTable.java | 108 +++++++++++++++- .../homework_2/randomCharsTable/Strategy.java | 82 ------------- .../java/homework_2/trafficLight/Main.java | 12 ++ .../homework_2/trafficLight/Strategy.java | 59 --------- .../homework_2/trafficLight/TrafficLight.java | 83 ++++++++++++- src/test/java/base/UnitBase.java | 78 ++++++------ .../java/homework_2/PyramidPrinterTest.java | 57 +++++++++ .../java/homework_2/RandomCharsTableTest.java | 47 +++++++ .../java/homework_2/TrafficLightTest.java | 116 ++++++++++++++++++ 12 files changed, 505 insertions(+), 195 deletions(-) create mode 100644 src/main/java/homework_2/pyramidPrinter/Main.java create mode 100644 src/main/java/homework_2/randomCharsTable/Main.java delete mode 100644 src/main/java/homework_2/randomCharsTable/Strategy.java create mode 100644 src/main/java/homework_2/trafficLight/Main.java delete mode 100644 src/main/java/homework_2/trafficLight/Strategy.java create mode 100644 src/test/java/homework_2/PyramidPrinterTest.java create mode 100644 src/test/java/homework_2/RandomCharsTableTest.java create mode 100644 src/test/java/homework_2/TrafficLightTest.java diff --git a/src/main/java/homework_2/pyramidPrinter/Main.java b/src/main/java/homework_2/pyramidPrinter/Main.java new file mode 100644 index 00000000..033baa95 --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/Main.java @@ -0,0 +1,8 @@ +package homework_2.pyramidPrinter; + +public class Main { + public static void main(String[] args) { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + pyramidPrinter.run(); + } +} diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java index f8b234b8..f25ac445 100644 --- a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -5,17 +5,39 @@ import java.io.InputStreamReader; public class PyramidPrinter { - public static void main(String[] args) { - String output = ""; - int input; + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + System.out.println("Please, input a number:"); + int input = consoleReader(); + if (negativeInput(input)) { + System.out.println(ERROR); + } else if (input == 0) { + System.out.println(); + } else { + printResult(input); + } + } + + private int consoleReader() { try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - input = Integer.parseInt(bF.readLine()); - for (int i = 0; i < input; i++) { - output += "x"; - System.out.println(output); - } - } catch (IOException e) { - System.out.println("Error occurred during input"); + return Integer.parseInt(bF.readLine()); + } catch (NumberFormatException | IOException exception) { + } + return -1; + } + + private void printResult(int input) { + String output = ""; + for (int i = 0; i < input; i++) { + output += "x"; + System.out.println(output); + } + } + + private boolean negativeInput(int n) { + return n < 0; } } diff --git a/src/main/java/homework_2/randomCharsTable/Main.java b/src/main/java/homework_2/randomCharsTable/Main.java new file mode 100644 index 00000000..6641398b --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/Main.java @@ -0,0 +1,8 @@ +package homework_2.randomCharsTable; + +public class Main { + public static void main(String[] args) { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + randomCharsTable.run(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java index 7b4e3c00..cfc24e51 100644 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -1,9 +1,113 @@ package homework_2.randomCharsTable; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; public class RandomCharsTable { - public static void main(String[] args) throws IOException { - Strategy.choosingStrategy(); + + private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + private char[][] array; + + private String strategy; + + private String inputData; + + private String result; + + private int rows; + + private int columns; + + public void run() { + System.out.println("Enter data in format: width, length of matrix and strategy (even/odd)"); + inputData = readingConsole(); + parseData(inputData); + if (dataValidation(rows, columns, strategy)) { + return; + } + arrayInitialization(); + if (inputData.endsWith("odd")) { + odd(); + } else { + even(); + } + printingResult(); + } + + private void parseData(String s){ + String[] resultArray = s.split(" "); + if(resultArray.length != 3){ + System.out.println(ERROR); + return; + } + rows = Integer.parseInt(resultArray[0]); + columns = Integer.parseInt(resultArray[1]); + strategy = resultArray[2]; + } + + private void arrayInitialization() { + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + System.out.print("|"); + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + " |"); + } + System.out.println(); + } + } + + private void odd() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private void even() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + private void printingResult() { + if (strategy.equals("even")) { + System.out.print("Even letters - "); + } else System.out.print("Odd letters - "); + int counter = 0; + while (counter < result.length()) { + if (counter == result.length() - 1) { + System.out.print(result.charAt(counter)); + break; + } + System.out.print(result.charAt(counter) + ", "); + counter++; + } + } + + private String readingConsole() { + inputData = ""; + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + inputData = bF.readLine(); + } catch (IOException exc) { + System.out.println("Error occurred during input"); + } + return inputData; + } + + private boolean dataValidation(int x, int y, String str) { + return x < 1 || y < 1 || (!str.equals("odd") && !str.equals("even")); } } diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java deleted file mode 100644 index 491800a6..00000000 --- a/src/main/java/homework_2/randomCharsTable/Strategy.java +++ /dev/null @@ -1,82 +0,0 @@ -package homework_2.randomCharsTable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class Strategy { - public static char[][] array; - - private final static BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); - - private static String inputData; - - private static String result = ""; - - private static int rows; - - private static int columns; - - public static void choosingStrategy() throws IOException { - System.out.println("Enter necessary data."); - inputData = bF.readLine(); - String strategy = inputData.trim(); - arrayInitialization(); - if (strategy.endsWith("odd")) { - odd(); - } else { - even(); - } - printingResult(); - } - - public static void arrayInitialization() { - rows = Integer.parseInt(inputData.substring(0, 1)); - columns = Integer.parseInt(inputData.substring(2, 3)); - array = new char[rows][columns]; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - char letters = (char) (Math.random() * 10 + 65); - array[i][j] = letters; - System.out.print(array[i][j] + " "); - } - } - System.out.println(); - } - - private static void odd() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 1) { - result += array[i][j]; - } - } - } - } - - private static void even() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 0) { - result += array[i][j]; - } - } - } - } - - public static void printingResult() { - if (inputData.endsWith("even")) { - System.out.print("Even letters - "); - } else System.out.print("Odd letters - "); - - int counter = 0; - while (counter < result.length()) { - if (counter == result.length() - 1) { - System.out.print(result.charAt(counter)); - break; - } - System.out.print(result.charAt(counter) + ", "); - counter++; - } - } -} diff --git a/src/main/java/homework_2/trafficLight/Main.java b/src/main/java/homework_2/trafficLight/Main.java new file mode 100644 index 00000000..50bb55af --- /dev/null +++ b/src/main/java/homework_2/trafficLight/Main.java @@ -0,0 +1,12 @@ +package homework_2.trafficLight; + +public class Main { + public static void main(String[] args) { + TrafficLight trafficLight = new TrafficLight(); + if(args[0].equals("seconds")){ + trafficLight.runSecondsFormat(); + } else { + trafficLight.runTimeFormat(); + } + } +} diff --git a/src/main/java/homework_2/trafficLight/Strategy.java b/src/main/java/homework_2/trafficLight/Strategy.java deleted file mode 100644 index 12a9eaa3..00000000 --- a/src/main/java/homework_2/trafficLight/Strategy.java +++ /dev/null @@ -1,59 +0,0 @@ -package homework_2.trafficLight; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class Strategy { - private final BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); - - private final String ANSI_RESET = "\u001b[0m"; - - private final String ANSI_RED = "\u001B[31m"; - - private final String ANSI_GREED = "\u001B[32m"; - - private final String ANSI_YELLOW = "\u001B[33m"; - - private int seconds; - - private final boolean greenLight = seconds % 60 < 35; - - private final boolean yellowLight = seconds % 60 >= 35 && seconds % 60 <= 40 || seconds % 60 >= 55; - - public void choosingStrategy() throws IOException { - System.out.println(""" - Choose input format:\s - 1.HH:MM:SS format - 2.Total amount of seconds."""); - String strategy = bF.readLine(); - if (strategy.startsWith("1")) { - timeFormat(); - } else secondsFormat(); - } - - private void secondsFormat() throws IOException { - System.out.println("Enter necessary amount of seconds."); - seconds = Integer.parseInt(bF.readLine()); - if (seconds > 86399) { - System.out.println("Day is over"); - return; - } - if (greenLight) { - System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); - } else if (yellowLight) { - System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); - } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); - } - - private void timeFormat() throws IOException { - System.out.println("Enter necessary amount of seconds."); - String parsedTime = bF.readLine(); - seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); - if (greenLight) { - System.out.println(ANSI_GREED + "Green light" + ANSI_RESET); - } else if (yellowLight) { - System.out.println(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); - } else System.out.println(ANSI_RED + "Red light" + ANSI_RESET); - } -} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java index 2d17b3f2..04ca26bd 100644 --- a/src/main/java/homework_2/trafficLight/TrafficLight.java +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -1,10 +1,87 @@ package homework_2.trafficLight; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; public class TrafficLight { - public static void main(String[] args) throws IOException { - Strategy strategy = new Strategy(); - strategy.choosingStrategy(); + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + public final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + private int seconds; + + public void runSecondsFormat() { + System.out.println("Enter necessary amount of seconds."); + String input = consoleReader(); + if(!isDigit(input)) { + System.out.println(ERROR); + return; + } + seconds = Integer.parseInt(input); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + if (!dayOverCheck(seconds)) { + System.out.println("Day is over"); + return; + } + trafficLightColorDetection(seconds); + } + + public void runTimeFormat() { + System.out.println("Enter necessary time in HH:MM:SS format."); + String parsedTime = consoleReader(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + trafficLightColorDetection(seconds); + } + + private String consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return bF.readLine(); + } catch (NumberFormatException | IOException e) { + + } + return ""; + } + + private void trafficLightColorDetection(int sec) { + if (sec % 60 < 35) { + System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); + } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { + System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else { + System.out.print(ANSI_RED + "Red light" + ANSI_RESET); + } + } + + private boolean isNegative(int input) { + return input < 0; + } + + private boolean dayOverCheck(int input) { + return input < 86399; + } + + private boolean isDigit(String input) { + try{ + Integer.parseInt(input); + return true; + } catch (NumberFormatException e) { + return false; + } } } + diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 97e2685b..8b46be60 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -10,53 +10,53 @@ public abstract class UnitBase { - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } } - } - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } // @Test // void example() { diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java new file mode 100644 index 00000000..c140c04c --- /dev/null +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -0,0 +1,57 @@ +package homework_2; + +import base.UnitBase; +import homework_2.pyramidPrinter.PyramidPrinter; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class PyramidPrinterTest extends UnitBase { + + @Test + void given5_whenRun_thenFiveLinesPrinted() { + setInput("5"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("x", getOutputLines()[0]); + Assertions.assertEquals("xx", getOutputLines()[1]); + Assertions.assertEquals("xxx", getOutputLines()[2]); + Assertions.assertEquals("xxxx", getOutputLines()[3]); + Assertions.assertEquals("xxxxx", getOutputLines()[4]); + } + + @Test + void givenZero_whenRun_thenEmpty() { + setInput("0"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("", getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_thenError() { + setInput("-1"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } + + @Test + void givenNaN_whenRun_thenError() { + setInput("text"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } +} diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java new file mode 100644 index 00000000..82876448 --- /dev/null +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -0,0 +1,47 @@ +package homework_2; + +import base.UnitBase; +import homework_2.randomCharsTable.RandomCharsTable; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class RandomCharsTableTest extends UnitBase { + + @Test + void givenTwoTwoEven_whenRun_thenMatrixAndLettersPrinted(){ + setInput("2 2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertTrue(getOutput().contains("|")); + Assertions.assertTrue(getOutput().contains(" |")); + Assertions.assertTrue(getOutput().contains("Even letters - ")); + } + + @Test + void givenTwoThreeOdd_whenRun_thenMatrixAndLettersPrinted(){ + setInput("2 3 odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertTrue(getOutput().contains("|")); + Assertions.assertTrue(getOutput().contains(" |")); + Assertions.assertTrue(getOutput().contains("Odd letters - ")); + } + + @Test + void givenNotFullParameters_whenRun_thenError(){ + setInput("2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertEquals("Passed parameters should match the format [positive integer] " + + "[positive integer] [even|odd]",getOutput()); + } +} diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java new file mode 100644 index 00000000..5a3e31d5 --- /dev/null +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -0,0 +1,116 @@ +package homework_2; + +import base.UnitBase; +import homework_2.trafficLight.TrafficLight; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class TrafficLightTest extends UnitBase { + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + private final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + @Test + void given0_whenRun_thenGreenLightPrinted(){ + setInput("0"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[32m")); + } + + @Test + void given35_whenRun_thenYellowLightPrinted(){ + setInput("35"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[33m")); + } + + @Test + void given54_whenRun_thenRedLightPrinted(){ + setInput("54"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[31m")); + } + + @Test + void given863400_whenRun_thenDayIsOverPrinted(){ + setInput("863400"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Day is over")); + } + + @Test + void givenFiveSecTimeFormat_whenRun_thenGreenLightPrinted(){ + setInput("23:25:05"); + + new TrafficLight().runTimeFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[32m")); + } + + @Test + void givenThirtyFiveSecTimeFormat_whenRun_thenYellowLightPrinted(){ + setInput("14:54:35"); + + new TrafficLight().runTimeFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[33m")); + } + + @Test + void givenFiftyFourSecTimeFormat_whenRun_thenRedLightPrinted(){ + setInput("07:56:54"); + + new TrafficLight().runTimeFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[31m")); + } + + @Test + void givenNegativeNumber_whenRun_thenError(){ + setInput("-56"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + @Test + void givenNaN_whenRun_thenError(){ + setInput("text"); + + new TrafficLight().runSecondsFormat(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } +} From 88d84b06b540d183a461dd9ea20dfc9e68443d75 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:29:40 +0300 Subject: [PATCH 35/63] homework_2 corrected --- .../java/homework_2/pyramidPrinter/Main.java | 8 -- .../pyramidPrinter/PyramidPrinter.java | 43 ------- .../homework_2/randomCharsTable/Main.java | 8 -- .../randomCharsTable/RandomCharsTable.java | 113 ------------------ .../java/homework_2/trafficLight/Main.java | 12 -- .../homework_2/trafficLight/TrafficLight.java | 87 -------------- 6 files changed, 271 deletions(-) delete mode 100644 src/main/java/homework_2/pyramidPrinter/Main.java delete mode 100644 src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java delete mode 100644 src/main/java/homework_2/randomCharsTable/Main.java delete mode 100644 src/main/java/homework_2/randomCharsTable/RandomCharsTable.java delete mode 100644 src/main/java/homework_2/trafficLight/Main.java delete mode 100644 src/main/java/homework_2/trafficLight/TrafficLight.java diff --git a/src/main/java/homework_2/pyramidPrinter/Main.java b/src/main/java/homework_2/pyramidPrinter/Main.java deleted file mode 100644 index 033baa95..00000000 --- a/src/main/java/homework_2/pyramidPrinter/Main.java +++ /dev/null @@ -1,8 +0,0 @@ -package homework_2.pyramidPrinter; - -public class Main { - public static void main(String[] args) { - PyramidPrinter pyramidPrinter = new PyramidPrinter(); - pyramidPrinter.run(); - } -} diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java deleted file mode 100644 index f25ac445..00000000 --- a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java +++ /dev/null @@ -1,43 +0,0 @@ -package homework_2.pyramidPrinter; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class PyramidPrinter { - - private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; - - public void run() { - System.out.println("Please, input a number:"); - int input = consoleReader(); - if (negativeInput(input)) { - System.out.println(ERROR); - } else if (input == 0) { - System.out.println(); - } else { - printResult(input); - } - } - - private int consoleReader() { - try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - return Integer.parseInt(bF.readLine()); - } catch (NumberFormatException | IOException exception) { - - } - return -1; - } - - private void printResult(int input) { - String output = ""; - for (int i = 0; i < input; i++) { - output += "x"; - System.out.println(output); - } - } - - private boolean negativeInput(int n) { - return n < 0; - } -} diff --git a/src/main/java/homework_2/randomCharsTable/Main.java b/src/main/java/homework_2/randomCharsTable/Main.java deleted file mode 100644 index 6641398b..00000000 --- a/src/main/java/homework_2/randomCharsTable/Main.java +++ /dev/null @@ -1,8 +0,0 @@ -package homework_2.randomCharsTable; - -public class Main { - public static void main(String[] args) { - RandomCharsTable randomCharsTable = new RandomCharsTable(); - randomCharsTable.run(); - } -} \ No newline at end of file diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java deleted file mode 100644 index cfc24e51..00000000 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ /dev/null @@ -1,113 +0,0 @@ -package homework_2.randomCharsTable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class RandomCharsTable { - - private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; - - private char[][] array; - - private String strategy; - - private String inputData; - - private String result; - - private int rows; - - private int columns; - - public void run() { - System.out.println("Enter data in format: width, length of matrix and strategy (even/odd)"); - inputData = readingConsole(); - parseData(inputData); - if (dataValidation(rows, columns, strategy)) { - return; - } - arrayInitialization(); - if (inputData.endsWith("odd")) { - odd(); - } else { - even(); - } - printingResult(); - } - - private void parseData(String s){ - String[] resultArray = s.split(" "); - if(resultArray.length != 3){ - System.out.println(ERROR); - return; - } - rows = Integer.parseInt(resultArray[0]); - columns = Integer.parseInt(resultArray[1]); - strategy = resultArray[2]; - } - - private void arrayInitialization() { - array = new char[rows][columns]; - for (int i = 0; i < rows; i++) { - System.out.print("|"); - for (int j = 0; j < columns; j++) { - char letters = (char) (Math.random() * 10 + 65); - array[i][j] = letters; - System.out.print(array[i][j] + " |"); - } - System.out.println(); - } - } - - private void odd() { - result = ""; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 1) { - result += array[i][j]; - } - } - } - } - - private void even() { - result = ""; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 0) { - result += array[i][j]; - } - } - } - } - - private void printingResult() { - if (strategy.equals("even")) { - System.out.print("Even letters - "); - } else System.out.print("Odd letters - "); - int counter = 0; - while (counter < result.length()) { - if (counter == result.length() - 1) { - System.out.print(result.charAt(counter)); - break; - } - System.out.print(result.charAt(counter) + ", "); - counter++; - } - } - - private String readingConsole() { - inputData = ""; - try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - inputData = bF.readLine(); - } catch (IOException exc) { - System.out.println("Error occurred during input"); - } - return inputData; - } - - private boolean dataValidation(int x, int y, String str) { - return x < 1 || y < 1 || (!str.equals("odd") && !str.equals("even")); - } -} diff --git a/src/main/java/homework_2/trafficLight/Main.java b/src/main/java/homework_2/trafficLight/Main.java deleted file mode 100644 index 50bb55af..00000000 --- a/src/main/java/homework_2/trafficLight/Main.java +++ /dev/null @@ -1,12 +0,0 @@ -package homework_2.trafficLight; - -public class Main { - public static void main(String[] args) { - TrafficLight trafficLight = new TrafficLight(); - if(args[0].equals("seconds")){ - trafficLight.runSecondsFormat(); - } else { - trafficLight.runTimeFormat(); - } - } -} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java deleted file mode 100644 index 04ca26bd..00000000 --- a/src/main/java/homework_2/trafficLight/TrafficLight.java +++ /dev/null @@ -1,87 +0,0 @@ -package homework_2.trafficLight; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class TrafficLight { - - private final String ANSI_RESET = "\u001b[0m"; - - private final String ANSI_RED = "\u001B[31m"; - - public final String ANSI_GREEN = "\u001B[32m"; - - private final String ANSI_YELLOW = "\u001B[33m"; - - private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; - - private int seconds; - - public void runSecondsFormat() { - System.out.println("Enter necessary amount of seconds."); - String input = consoleReader(); - if(!isDigit(input)) { - System.out.println(ERROR); - return; - } - seconds = Integer.parseInt(input); - if (isNegative(seconds)) { - System.out.println(ERROR); - return; - } - if (!dayOverCheck(seconds)) { - System.out.println("Day is over"); - return; - } - trafficLightColorDetection(seconds); - } - - public void runTimeFormat() { - System.out.println("Enter necessary time in HH:MM:SS format."); - String parsedTime = consoleReader(); - seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); - if (isNegative(seconds)) { - System.out.println(ERROR); - return; - } - trafficLightColorDetection(seconds); - } - - private String consoleReader() { - try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { - return bF.readLine(); - } catch (NumberFormatException | IOException e) { - - } - return ""; - } - - private void trafficLightColorDetection(int sec) { - if (sec % 60 < 35) { - System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); - } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { - System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); - } else { - System.out.print(ANSI_RED + "Red light" + ANSI_RESET); - } - } - - private boolean isNegative(int input) { - return input < 0; - } - - private boolean dayOverCheck(int input) { - return input < 86399; - } - - private boolean isDigit(String input) { - try{ - Integer.parseInt(input); - return true; - } catch (NumberFormatException e) { - return false; - } - } -} - From 4926d1ee21e599b5e72e928ebd5ccaa12460fd91 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:30:59 +0300 Subject: [PATCH 36/63] homework_2 corrected --- .../java/homework_2/pyramidPrinter/Main.java | 8 ++ .../pyramidPrinter/PyramidPrinter.java | 43 +++++++ .../homework_2/randomCharsTable/Main.java | 8 ++ .../randomCharsTable/RandomCharsTable.java | 113 ++++++++++++++++++ .../java/homework_2/trafficLight/Main.java | 12 ++ .../homework_2/trafficLight/TrafficLight.java | 87 ++++++++++++++ 6 files changed, 271 insertions(+) create mode 100644 src/main/java/homework_2/pyramidPrinter/Main.java create mode 100644 src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java create mode 100644 src/main/java/homework_2/randomCharsTable/Main.java create mode 100644 src/main/java/homework_2/randomCharsTable/RandomCharsTable.java create mode 100644 src/main/java/homework_2/trafficLight/Main.java create mode 100644 src/main/java/homework_2/trafficLight/TrafficLight.java diff --git a/src/main/java/homework_2/pyramidPrinter/Main.java b/src/main/java/homework_2/pyramidPrinter/Main.java new file mode 100644 index 00000000..033baa95 --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/Main.java @@ -0,0 +1,8 @@ +package homework_2.pyramidPrinter; + +public class Main { + public static void main(String[] args) { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + pyramidPrinter.run(); + } +} diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java new file mode 100644 index 00000000..f25ac445 --- /dev/null +++ b/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java @@ -0,0 +1,43 @@ +package homework_2.pyramidPrinter; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + System.out.println("Please, input a number:"); + int input = consoleReader(); + if (negativeInput(input)) { + System.out.println(ERROR); + } else if (input == 0) { + System.out.println(); + } else { + printResult(input); + } + } + + private int consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return Integer.parseInt(bF.readLine()); + } catch (NumberFormatException | IOException exception) { + + } + return -1; + } + + private void printResult(int input) { + String output = ""; + for (int i = 0; i < input; i++) { + output += "x"; + System.out.println(output); + } + } + + private boolean negativeInput(int n) { + return n < 0; + } +} diff --git a/src/main/java/homework_2/randomCharsTable/Main.java b/src/main/java/homework_2/randomCharsTable/Main.java new file mode 100644 index 00000000..6641398b --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/Main.java @@ -0,0 +1,8 @@ +package homework_2.randomCharsTable; + +public class Main { + public static void main(String[] args) { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + randomCharsTable.run(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java new file mode 100644 index 00000000..cfc24e51 --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java @@ -0,0 +1,113 @@ +package homework_2.randomCharsTable; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + + private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + private char[][] array; + + private String strategy; + + private String inputData; + + private String result; + + private int rows; + + private int columns; + + public void run() { + System.out.println("Enter data in format: width, length of matrix and strategy (even/odd)"); + inputData = readingConsole(); + parseData(inputData); + if (dataValidation(rows, columns, strategy)) { + return; + } + arrayInitialization(); + if (inputData.endsWith("odd")) { + odd(); + } else { + even(); + } + printingResult(); + } + + private void parseData(String s){ + String[] resultArray = s.split(" "); + if(resultArray.length != 3){ + System.out.println(ERROR); + return; + } + rows = Integer.parseInt(resultArray[0]); + columns = Integer.parseInt(resultArray[1]); + strategy = resultArray[2]; + } + + private void arrayInitialization() { + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + System.out.print("|"); + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + " |"); + } + System.out.println(); + } + } + + private void odd() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private void even() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + private void printingResult() { + if (strategy.equals("even")) { + System.out.print("Even letters - "); + } else System.out.print("Odd letters - "); + int counter = 0; + while (counter < result.length()) { + if (counter == result.length() - 1) { + System.out.print(result.charAt(counter)); + break; + } + System.out.print(result.charAt(counter) + ", "); + counter++; + } + } + + private String readingConsole() { + inputData = ""; + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + inputData = bF.readLine(); + } catch (IOException exc) { + System.out.println("Error occurred during input"); + } + return inputData; + } + + private boolean dataValidation(int x, int y, String str) { + return x < 1 || y < 1 || (!str.equals("odd") && !str.equals("even")); + } +} diff --git a/src/main/java/homework_2/trafficLight/Main.java b/src/main/java/homework_2/trafficLight/Main.java new file mode 100644 index 00000000..50bb55af --- /dev/null +++ b/src/main/java/homework_2/trafficLight/Main.java @@ -0,0 +1,12 @@ +package homework_2.trafficLight; + +public class Main { + public static void main(String[] args) { + TrafficLight trafficLight = new TrafficLight(); + if(args[0].equals("seconds")){ + trafficLight.runSecondsFormat(); + } else { + trafficLight.runTimeFormat(); + } + } +} diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/trafficLight/TrafficLight.java new file mode 100644 index 00000000..04ca26bd --- /dev/null +++ b/src/main/java/homework_2/trafficLight/TrafficLight.java @@ -0,0 +1,87 @@ +package homework_2.trafficLight; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + public final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + private int seconds; + + public void runSecondsFormat() { + System.out.println("Enter necessary amount of seconds."); + String input = consoleReader(); + if(!isDigit(input)) { + System.out.println(ERROR); + return; + } + seconds = Integer.parseInt(input); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + if (!dayOverCheck(seconds)) { + System.out.println("Day is over"); + return; + } + trafficLightColorDetection(seconds); + } + + public void runTimeFormat() { + System.out.println("Enter necessary time in HH:MM:SS format."); + String parsedTime = consoleReader(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + trafficLightColorDetection(seconds); + } + + private String consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return bF.readLine(); + } catch (NumberFormatException | IOException e) { + + } + return ""; + } + + private void trafficLightColorDetection(int sec) { + if (sec % 60 < 35) { + System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); + } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { + System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else { + System.out.print(ANSI_RED + "Red light" + ANSI_RESET); + } + } + + private boolean isNegative(int input) { + return input < 0; + } + + private boolean dayOverCheck(int input) { + return input < 86399; + } + + private boolean isDigit(String input) { + try{ + Integer.parseInt(input); + return true; + } catch (NumberFormatException e) { + return false; + } + } +} + From cb73022ab62ac713eb14a36bf39a2df2c9523fb2 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Thu, 15 Jul 2021 18:34:25 +0300 Subject: [PATCH 37/63] Update Strategy.java --- .../homework_2/randomCharsTable/Strategy.java | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/main/java/homework_2/randomCharsTable/Strategy.java diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java new file mode 100644 index 00000000..38fcfed5 --- /dev/null +++ b/src/main/java/homework_2/randomCharsTable/Strategy.java @@ -0,0 +1,82 @@ +package homework_2.randomCharsTable; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Strategy { + public static char[][] array; + + private final static BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); + + private static String inputData; + + private static String result = ""; + + private static int rows; + + private static int columns; + + public static void choosingStrategy() throws IOException { + System.out.println("Enter necessary data."); + inputData = bF.readLine(); + String strategy = inputData.trim(); + arrayInitialization(); + if (strategy.endsWith("odd")) { + odd(); + } else { + even(); + } + printingResult(); + } + + private static void arrayInitialization() { + rows = Integer.parseInt(inputData.substring(0, 1)); + columns = Integer.parseInt(inputData.substring(2, 3)); + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + " "); + } + } + System.out.println(); + } + + private static void odd() { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private static void even() { + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + private static void printingResult() { + if (inputData.endsWith("even")) { + System.out.print("Even letters - "); + } else System.out.print("Odd letters - "); + + int counter = 0; + while (counter < result.length()) { + if (counter == result.length() - 1) { + System.out.print(result.charAt(counter)); + break; + } + System.out.print(result.charAt(counter) + ", "); + counter++; + } + } +} From bda343235aa7d703869439e87a6bbda0558d69d2 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:36:48 +0300 Subject: [PATCH 38/63] README updated --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 41936886..9950634a 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,4 @@ | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) From 5d6eafc8a3c77abbdb38ee5e89e2fd99c9634bb8 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:34:24 +0300 Subject: [PATCH 39/63] Delete Strategy.java --- .../homework_2/randomCharsTable/Strategy.java | 82 ------------------- 1 file changed, 82 deletions(-) delete mode 100644 src/main/java/homework_2/randomCharsTable/Strategy.java diff --git a/src/main/java/homework_2/randomCharsTable/Strategy.java b/src/main/java/homework_2/randomCharsTable/Strategy.java deleted file mode 100644 index 38fcfed5..00000000 --- a/src/main/java/homework_2/randomCharsTable/Strategy.java +++ /dev/null @@ -1,82 +0,0 @@ -package homework_2.randomCharsTable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class Strategy { - public static char[][] array; - - private final static BufferedReader bF = new BufferedReader(new InputStreamReader(System.in)); - - private static String inputData; - - private static String result = ""; - - private static int rows; - - private static int columns; - - public static void choosingStrategy() throws IOException { - System.out.println("Enter necessary data."); - inputData = bF.readLine(); - String strategy = inputData.trim(); - arrayInitialization(); - if (strategy.endsWith("odd")) { - odd(); - } else { - even(); - } - printingResult(); - } - - private static void arrayInitialization() { - rows = Integer.parseInt(inputData.substring(0, 1)); - columns = Integer.parseInt(inputData.substring(2, 3)); - array = new char[rows][columns]; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - char letters = (char) (Math.random() * 10 + 65); - array[i][j] = letters; - System.out.print(array[i][j] + " "); - } - } - System.out.println(); - } - - private static void odd() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 1) { - result += array[i][j]; - } - } - } - } - - private static void even() { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if ((array[i][j] % 2) == 0) { - result += array[i][j]; - } - } - } - } - - private static void printingResult() { - if (inputData.endsWith("even")) { - System.out.print("Even letters - "); - } else System.out.print("Odd letters - "); - - int counter = 0; - while (counter < result.length()) { - if (counter == result.length() - 1) { - System.out.print(result.charAt(counter)); - break; - } - System.out.print(result.charAt(counter) + ", "); - counter++; - } - } -} From 2aed539d916dac1983b44f12afc80d77906fb237 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:37:25 +0300 Subject: [PATCH 40/63] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9950634a..43a02594 100644 --- a/README.md +++ b/README.md @@ -8,5 +8,6 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +[Link to markdown guide](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) From d84e24c61d7c03cafc7af2e8f5d922cfd1b5e92c Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:37:58 +0300 Subject: [PATCH 41/63] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 43a02594..52a7cc2f 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,6 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| -[Link to markdown guide](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) +[Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) From b9dac9f88c87f62485f6c5818045131dd48a576c Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:42:09 +0300 Subject: [PATCH 42/63] README updated --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 52a7cc2f..a155cfd0 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,3 @@ | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) -[Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) From 68fac5308cb493425401a1d7861b414f20ea2811 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 04:56:04 +0300 Subject: [PATCH 43/63] package naming corrected --- src/main/java/homework_3/ImmutableClass.java | 49 ++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/homework_3/ImmutableClass.java diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..d7f77ee9 --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,49 @@ +package homework_3; + +import java.util.List; + +final class ImmutableClass { + + private final int firstInt; + + private final String firstString; + + private final int[] firstIntArray; + + private final String[] firstStringArray; + + private final List firstCollection; + + + ImmutableClass(int firstInt, String firstString, int[] firstIntArray, String[] firstStringArray, List firstCollection) { + this.firstInt = firstInt; + this.firstString = firstString; + this.firstIntArray = firstIntArray; + this.firstStringArray = firstStringArray; + this.firstCollection = firstCollection; + } + + public int getFirstInt() { + return firstInt; + } + + public String getFirstString() { + return firstString; + } + + public int[] getFirstIntArray() { + return firstIntArray; + } + + public String[] getFirstStringArray() { + return firstStringArray; + } + + public List getFirstCollection() { + return firstCollection; + } + + public ImmutableClass getNewImmutableClass(int x, String y, int[] xy, String[] yx, List list) { + return new ImmutableClass(x,y,xy,yx,list); + } +} From fbecf0baf31faf69b15b392211925f968d225d5a Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:58:11 +0300 Subject: [PATCH 44/63] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a155cfd0..8b8e2b0a 100644 --- a/README.md +++ b/README.md @@ -8,5 +8,7 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +| HW3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| + [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 44764f436cb201d52867520de9153210ffb924a9 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 04:58:28 +0300 Subject: [PATCH 45/63] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8b8e2b0a..46736de7 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ | HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | | HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| | HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| -| HW3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| +| HW3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 2756dea79f2ad68d4618380cfc8aed3e75b605d4 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 05:05:32 +0300 Subject: [PATCH 46/63] UnitBase merged --- src/test/java/base/UnitBase.java | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 8b46be60..5cdc43ee 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -10,6 +10,54 @@ public abstract class UnitBase { + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } + + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } + + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } + + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } + + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); protected final PrintStream originalOut = System.out; protected final InputStream originalIn = System.in; @@ -58,6 +106,7 @@ protected void printOut() { System.setOut(new PrintStream(mockedOut)); } + // @Test // void example() { // setInput("2"); From f9a8a46a079333a5e004ec8b2f81ec451509fba8 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 05:06:36 +0300 Subject: [PATCH 47/63] Delete UnitBase.java --- src/test/java/base/UnitBase.java | 122 ------------------------------- 1 file changed, 122 deletions(-) delete mode 100644 src/test/java/base/UnitBase.java diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java deleted file mode 100644 index 5cdc43ee..00000000 --- a/src/test/java/base/UnitBase.java +++ /dev/null @@ -1,122 +0,0 @@ -package base; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -public abstract class UnitBase { - - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; - - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } - - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } - - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } - - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } - - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } - - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } - - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; - - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } - - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } - - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } - - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } - - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } - - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } - - -// @Test -// void example() { -// setInput("2"); -// -// new PyramidPrinter().run(); -// printOut(); -// removeFromOutput("Please input number"): -// -// assertEquals("x", getOutputLines()[0]); -// assertEquals("xx", getOutputLines()[1]); -// } - -} From 0e076f43c6aa1e0b6ae8f384a15d1702c4e9e9b7 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 05:12:54 +0300 Subject: [PATCH 48/63] UnitBase merged --- src/test/java/base/UnitBase.java | 74 ++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/test/java/base/UnitBase.java diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java new file mode 100644 index 00000000..28eac5f4 --- /dev/null +++ b/src/test/java/base/UnitBase.java @@ -0,0 +1,74 @@ +package base; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +public abstract class UnitBase { + + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } + + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } + + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } + + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } + + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } + +// @Test +// void example() { +// setInput("2"); +// +// new PyramidPrinter().run(); +// printOut(); +// removeFromOutput("Please input number"): +// +// assertEquals("x", getOutputLines()[0]); +// assertEquals("xx", getOutputLines()[1]); +// test +// } + +} From dcb4e0a1c69980b59035ea0ae772af1428df507d Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Sun, 25 Jul 2021 05:18:01 +0300 Subject: [PATCH 49/63] UnitBase merged --- src/test/java/base/UnitBase.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 28eac5f4..ab25ff58 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -69,6 +69,7 @@ protected void printOut() { // assertEquals("x", getOutputLines()[0]); // assertEquals("xx", getOutputLines()[1]); // test +// one more test // } } From a54053f7c3ff482efe4998918c06b9fcc39916b5 Mon Sep 17 00:00:00 2001 From: Arkadiy Date: Sun, 25 Jul 2021 05:18:52 +0300 Subject: [PATCH 50/63] Update UnitBase.java --- src/test/java/base/UnitBase.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index ab25ff58..97e2685b 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -68,8 +68,6 @@ protected void printOut() { // // assertEquals("x", getOutputLines()[0]); // assertEquals("xx", getOutputLines()[1]); -// test -// one more test // } } From 3d8a1fa6d449e96a12bbacb26e7de153b76f0cdf Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Mon, 26 Jul 2021 15:36:58 +0300 Subject: [PATCH 51/63] homework_2 correction --- .../Main.java | 2 +- .../PyramidPrinter.java | 2 +- .../Main.java | 2 +- .../RandomCharsTable.java | 3 ++- .../{trafficLight => traffic_light}/Main.java | 7 ++--- .../TrafficLight.java | 27 +++++++------------ .../traffic_light/TrafficLightExtraMod.java | 15 +++++++++++ .../java/homework_2/PyramidPrinterTest.java | 2 +- .../java/homework_2/RandomCharsTableTest.java | 14 +++++++++- .../java/homework_2/TrafficLightTest.java | 21 ++++++++------- 10 files changed, 58 insertions(+), 37 deletions(-) rename src/main/java/homework_2/{pyramidPrinter => pyramid_printer}/Main.java (82%) rename src/main/java/homework_2/{pyramidPrinter => pyramid_printer}/PyramidPrinter.java (96%) rename src/main/java/homework_2/{randomCharsTable => random_chars_table}/Main.java (81%) rename src/main/java/homework_2/{randomCharsTable => random_chars_table}/RandomCharsTable.java (97%) rename src/main/java/homework_2/{trafficLight => traffic_light}/Main.java (51%) rename src/main/java/homework_2/{trafficLight => traffic_light}/TrafficLight.java (69%) create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java diff --git a/src/main/java/homework_2/pyramidPrinter/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java similarity index 82% rename from src/main/java/homework_2/pyramidPrinter/Main.java rename to src/main/java/homework_2/pyramid_printer/Main.java index 033baa95..e00ce234 100644 --- a/src/main/java/homework_2/pyramidPrinter/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -1,4 +1,4 @@ -package homework_2.pyramidPrinter; +package homework_2.pyramid_printer; public class Main { public static void main(String[] args) { diff --git a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java similarity index 96% rename from src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java rename to src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index f25ac445..4b40818d 100644 --- a/src/main/java/homework_2/pyramidPrinter/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -1,4 +1,4 @@ -package homework_2.pyramidPrinter; +package homework_2.pyramid_printer; import java.io.BufferedReader; import java.io.IOException; diff --git a/src/main/java/homework_2/randomCharsTable/Main.java b/src/main/java/homework_2/random_chars_table/Main.java similarity index 81% rename from src/main/java/homework_2/randomCharsTable/Main.java rename to src/main/java/homework_2/random_chars_table/Main.java index 6641398b..901735a8 100644 --- a/src/main/java/homework_2/randomCharsTable/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -1,4 +1,4 @@ -package homework_2.randomCharsTable; +package homework_2.random_chars_table; public class Main { public static void main(String[] args) { diff --git a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java similarity index 97% rename from src/main/java/homework_2/randomCharsTable/RandomCharsTable.java rename to src/main/java/homework_2/random_chars_table/RandomCharsTable.java index cfc24e51..1add8e47 100644 --- a/src/main/java/homework_2/randomCharsTable/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,4 +1,4 @@ -package homework_2.randomCharsTable; +package homework_2.random_chars_table; import java.io.BufferedReader; import java.io.IOException; @@ -25,6 +25,7 @@ public void run() { inputData = readingConsole(); parseData(inputData); if (dataValidation(rows, columns, strategy)) { + System.out.println(ERROR); return; } arrayInitialization(); diff --git a/src/main/java/homework_2/trafficLight/Main.java b/src/main/java/homework_2/traffic_light/Main.java similarity index 51% rename from src/main/java/homework_2/trafficLight/Main.java rename to src/main/java/homework_2/traffic_light/Main.java index 50bb55af..a9d70a3f 100644 --- a/src/main/java/homework_2/trafficLight/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -1,12 +1,13 @@ -package homework_2.trafficLight; +package homework_2.traffic_light; public class Main { public static void main(String[] args) { TrafficLight trafficLight = new TrafficLight(); + TrafficLightExtraMod trafficLightExtraMod = new TrafficLightExtraMod(); if(args[0].equals("seconds")){ - trafficLight.runSecondsFormat(); + trafficLight.run(); } else { - trafficLight.runTimeFormat(); + trafficLightExtraMod.run(); } } } diff --git a/src/main/java/homework_2/trafficLight/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java similarity index 69% rename from src/main/java/homework_2/trafficLight/TrafficLight.java rename to src/main/java/homework_2/traffic_light/TrafficLight.java index 04ca26bd..53617416 100644 --- a/src/main/java/homework_2/trafficLight/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,4 +1,4 @@ -package homework_2.trafficLight; +package homework_2.traffic_light; import java.io.BufferedReader; import java.io.IOException; @@ -14,11 +14,11 @@ public class TrafficLight { private final String ANSI_YELLOW = "\u001B[33m"; - private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + protected final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; - private int seconds; + protected int seconds; - public void runSecondsFormat() { + public void run() { System.out.println("Enter necessary amount of seconds."); String input = consoleReader(); if(!isDigit(input)) { @@ -37,18 +37,9 @@ public void runSecondsFormat() { trafficLightColorDetection(seconds); } - public void runTimeFormat() { - System.out.println("Enter necessary time in HH:MM:SS format."); - String parsedTime = consoleReader(); - seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); - if (isNegative(seconds)) { - System.out.println(ERROR); - return; - } - trafficLightColorDetection(seconds); - } - private String consoleReader() { + + protected String consoleReader() { try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { return bF.readLine(); } catch (NumberFormatException | IOException e) { @@ -57,7 +48,7 @@ private String consoleReader() { return ""; } - private void trafficLightColorDetection(int sec) { + protected void trafficLightColorDetection(int sec) { if (sec % 60 < 35) { System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { @@ -67,12 +58,12 @@ private void trafficLightColorDetection(int sec) { } } - private boolean isNegative(int input) { + protected boolean isNegative(int input) { return input < 0; } private boolean dayOverCheck(int input) { - return input < 86399; + return input <= 86399; } private boolean isDigit(String input) { diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java new file mode 100644 index 00000000..bbf5157e --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java @@ -0,0 +1,15 @@ +package homework_2.traffic_light; + +public class TrafficLightExtraMod extends TrafficLight{ + + public void run() { + System.out.println("Enter necessary time in HH:MM:SS format."); + String parsedTime = consoleReader(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (isNegative(seconds)) { + System.out.println(ERROR); + return; + } + trafficLightColorDetection(seconds); + } +} diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java index c140c04c..803dfc82 100644 --- a/src/test/java/homework_2/PyramidPrinterTest.java +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -1,7 +1,7 @@ package homework_2; import base.UnitBase; -import homework_2.pyramidPrinter.PyramidPrinter; +import homework_2.pyramid_printer.PyramidPrinter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java index 82876448..1ca209f0 100644 --- a/src/test/java/homework_2/RandomCharsTableTest.java +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -1,7 +1,7 @@ package homework_2; import base.UnitBase; -import homework_2.randomCharsTable.RandomCharsTable; +import homework_2.random_chars_table.RandomCharsTable; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -44,4 +44,16 @@ void givenNotFullParameters_whenRun_thenError(){ Assertions.assertEquals("Passed parameters should match the format [positive integer] " + "[positive integer] [even|odd]",getOutput()); } + + @Test + void givenZeroAndNegativeParameters_whenRun_thenError(){ + setInput("0 -2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertEquals("Passed parameters should match the format [positive integer] " + + "[positive integer] [even|odd]",getOutput()); + } } diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java index 5a3e31d5..c754063c 100644 --- a/src/test/java/homework_2/TrafficLightTest.java +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -1,7 +1,8 @@ package homework_2; import base.UnitBase; -import homework_2.trafficLight.TrafficLight; +import homework_2.traffic_light.TrafficLight; +import homework_2.traffic_light.TrafficLightExtraMod; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -19,7 +20,7 @@ public class TrafficLightTest extends UnitBase { void given0_whenRun_thenGreenLightPrinted(){ setInput("0"); - new TrafficLight().runSecondsFormat(); + new TrafficLight().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -30,7 +31,7 @@ void given0_whenRun_thenGreenLightPrinted(){ void given35_whenRun_thenYellowLightPrinted(){ setInput("35"); - new TrafficLight().runSecondsFormat(); + new TrafficLight().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -41,7 +42,7 @@ void given35_whenRun_thenYellowLightPrinted(){ void given54_whenRun_thenRedLightPrinted(){ setInput("54"); - new TrafficLight().runSecondsFormat(); + new TrafficLight().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -52,7 +53,7 @@ void given54_whenRun_thenRedLightPrinted(){ void given863400_whenRun_thenDayIsOverPrinted(){ setInput("863400"); - new TrafficLight().runSecondsFormat(); + new TrafficLight().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -63,7 +64,7 @@ void given863400_whenRun_thenDayIsOverPrinted(){ void givenFiveSecTimeFormat_whenRun_thenGreenLightPrinted(){ setInput("23:25:05"); - new TrafficLight().runTimeFormat(); + new TrafficLightExtraMod().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -74,7 +75,7 @@ void givenFiveSecTimeFormat_whenRun_thenGreenLightPrinted(){ void givenThirtyFiveSecTimeFormat_whenRun_thenYellowLightPrinted(){ setInput("14:54:35"); - new TrafficLight().runTimeFormat(); + new TrafficLightExtraMod().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -85,7 +86,7 @@ void givenThirtyFiveSecTimeFormat_whenRun_thenYellowLightPrinted(){ void givenFiftyFourSecTimeFormat_whenRun_thenRedLightPrinted(){ setInput("07:56:54"); - new TrafficLight().runTimeFormat(); + new TrafficLightExtraMod().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -96,7 +97,7 @@ void givenFiftyFourSecTimeFormat_whenRun_thenRedLightPrinted(){ void givenNegativeNumber_whenRun_thenError(){ setInput("-56"); - new TrafficLight().runSecondsFormat(); + new TrafficLight().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); @@ -107,7 +108,7 @@ void givenNegativeNumber_whenRun_thenError(){ void givenNaN_whenRun_thenError(){ setInput("text"); - new TrafficLight().runSecondsFormat(); + new TrafficLight().run(); printOut(); removeFromOutput("Enter necessary amount of seconds"); From d4ef7cb9c7d69efcc58a2a8d362bf6657230222c Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Mon, 26 Jul 2021 17:11:09 +0300 Subject: [PATCH 52/63] homework_2 correction --- src/test/java/homework_2/RandomCharsTableTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java index 1ca209f0..846d04c1 100644 --- a/src/test/java/homework_2/RandomCharsTableTest.java +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -42,7 +42,9 @@ void givenNotFullParameters_whenRun_thenError(){ removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); Assertions.assertEquals("Passed parameters should match the format [positive integer] " + - "[positive integer] [even|odd]",getOutput()); + "[positive integer] [even|odd]",getOutputLines()[0]); + Assertions.assertEquals("Passed parameters should match the format [positive integer] " + + "[positive integer] [even|odd]",getOutputLines()[1]); } @Test From fb46f539794f059f198048e51ed1bc553f4eecc4 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 5 Aug 2021 22:36:38 +0300 Subject: [PATCH 53/63] homework_3 correction --- src/main/java/homework_3/ImmutableClass.java | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java index d7f77ee9..fd9a7ffa 100644 --- a/src/main/java/homework_3/ImmutableClass.java +++ b/src/main/java/homework_3/ImmutableClass.java @@ -1,7 +1,16 @@ package homework_3; +import java.util.ArrayList; import java.util.List; +/* +The class must be declared as final. +Data members in the class must be declared as private & final. +A parameterized constructor should initialize all the fields. +Deep Copy of objects should be performed in the getter methods. +No setters. + */ + final class ImmutableClass { private final int firstInt; @@ -23,6 +32,22 @@ final class ImmutableClass { this.firstCollection = firstCollection; } + public ImmutableClass() { + this.firstInt = 1; + this.firstString = "Default"; + this.firstIntArray = new int[1]; + this.firstStringArray = new String[1]; + this.firstCollection = new ArrayList<>(); + } + + public ImmutableClass(int firstInt, String firstString) { + this.firstInt = firstInt; + this.firstString = firstString; + this.firstIntArray = new int[1]; + this.firstStringArray = new String[1]; + this.firstCollection = new ArrayList<>(); + } + public int getFirstInt() { return firstInt; } From 478cf573216bd0ef5910f7c8318ff912e8ebe211 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 5 Aug 2021 23:14:29 +0300 Subject: [PATCH 54/63] homework_4 realization --- .../custom_annotation/MyAnnotation.java | 17 ++++++++++++++ .../custom_file_reader/CustomFileReader.java | 23 +++++++++++++++++++ .../homework_4/custom_file_reader/Main.java | 9 ++++++++ .../java/homework_4/singleton/Singleton.java | 16 +++++++++++++ src/main/resources/testCustomFileReader.txt | 1 + 5 files changed, 66 insertions(+) create mode 100644 src/main/java/homework_4/custom_annotation/MyAnnotation.java create mode 100644 src/main/java/homework_4/custom_file_reader/CustomFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/Main.java create mode 100644 src/main/java/homework_4/singleton/Singleton.java create mode 100644 src/main/resources/testCustomFileReader.txt diff --git a/src/main/java/homework_4/custom_annotation/MyAnnotation.java b/src/main/java/homework_4/custom_annotation/MyAnnotation.java new file mode 100644 index 00000000..b3d1405f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/MyAnnotation.java @@ -0,0 +1,17 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +//Аннотация необходимая, которая позволяет включать отмеченные поля в сгенерированный JSON + +public class MyAnnotation { + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface JsonElement { + public String key() default ""; + } +} 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..eae6c6f3 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,23 @@ +package homework_4.custom_file_reader; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class CustomFileReader { + + private final String fileName = "C:\\Users\\Аркадий\\IdeaProjects\\Java_Core_June_2021\\src\\main\\resources\\testCustomFileReader.txt"; + + public void run() { + + } + + private void bufferedReader() { + try (BufferedReader bf = new BufferedReader(new FileReader(fileName))) { + + + } catch (IOException exception) { + System.out.println("Input error occurred"); + } + } +} 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..4d99e3a2 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,9 @@ +package homework_4.custom_file_reader; + +public class Main { + + public static void main(String[] args) { + CustomFileReader customFileReader = new CustomFileReader(); + customFileReader.run(); + } +} 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..f3b8dd2e --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,16 @@ +package homework_4.singleton; + +public class Singleton { + private static Singleton INSTANCE; + + public static Singleton getInstance() { + if (INSTANCE == null) { + INSTANCE = new Singleton(); + } + return INSTANCE; + } + + private Singleton() { + + } +} diff --git a/src/main/resources/testCustomFileReader.txt b/src/main/resources/testCustomFileReader.txt new file mode 100644 index 00000000..08e00ed2 --- /dev/null +++ b/src/main/resources/testCustomFileReader.txt @@ -0,0 +1 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \ No newline at end of file From 239bf04676d47501074acc8bb44e40c598dca5b7 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Fri, 6 Aug 2021 01:04:43 +0300 Subject: [PATCH 55/63] homework_4 realization --- .../custom_file_reader/CustomFileReader.java | 53 ++++++++++++++----- .../homework_4/custom_file_reader/Main.java | 4 +- .../testCustomFileReader.txt | 4 ++ src/main/resources/testCustomFileReader.txt | 1 - 4 files changed, 48 insertions(+), 14 deletions(-) create mode 100644 src/main/resources/custom_file_reader/testCustomFileReader.txt delete mode 100644 src/main/resources/testCustomFileReader.txt diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index eae6c6f3..b1ebab76 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -1,23 +1,52 @@ package homework_4.custom_file_reader; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; public class CustomFileReader { - private final String fileName = "C:\\Users\\Аркадий\\IdeaProjects\\Java_Core_June_2021\\src\\main\\resources\\testCustomFileReader.txt"; - - public void run() { - + private static final String PATH_TO_FILE = "\\src\\main\\resources\\custom_file_reader\\"; + + public void run1(String filename) { + List data = new ArrayList<>(); + try (BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(getPath(filename))))){ + String line; + while ((line = bf.readLine()) != null) { + data.add(line); + } + } catch (IOException exception){ + System.out.println("Error occurred"); + } + System.out.println(String.join("", data).replaceAll("[,.]", "")); } - private void bufferedReader() { - try (BufferedReader bf = new BufferedReader(new FileReader(fileName))) { - + public void run2(String filename) { + try{ + Files.lines(Path.of(getPath(filename))).map(x->x.replaceAll("[,.]","")).forEach(System.out::println); + } catch (IOException exception){ + System.out.println("Error occurred"); + } + } - } catch (IOException exception) { - System.out.println("Input error occurred"); + public void run3(String filename){ + try { + Scanner scanner = new Scanner(new FileReader(getPath(filename))); + List data = new ArrayList<>(); + while(scanner.hasNextLine()){ + data.add(scanner.nextLine()); + } + System.out.println(String.join("", data).replaceAll("[,.]", "")); + } catch (FileNotFoundException e) { + e.printStackTrace(); } } + + private static String getPath(String fileName){ + return Paths.get("").toAbsolutePath() + PATH_TO_FILE + fileName; + } } diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java index 4d99e3a2..dbabf5e4 100644 --- a/src/main/java/homework_4/custom_file_reader/Main.java +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -4,6 +4,8 @@ public class Main { public static void main(String[] args) { CustomFileReader customFileReader = new CustomFileReader(); - customFileReader.run(); + customFileReader.run1(args[0]); + customFileReader.run2(args[0]); + customFileReader.run3(args[0]); } } diff --git a/src/main/resources/custom_file_reader/testCustomFileReader.txt b/src/main/resources/custom_file_reader/testCustomFileReader.txt new file mode 100644 index 00000000..b96edced --- /dev/null +++ b/src/main/resources/custom_file_reader/testCustomFileReader.txt @@ -0,0 +1,4 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna + aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. + Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. + Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \ No newline at end of file diff --git a/src/main/resources/testCustomFileReader.txt b/src/main/resources/testCustomFileReader.txt deleted file mode 100644 index 08e00ed2..00000000 --- a/src/main/resources/testCustomFileReader.txt +++ /dev/null @@ -1 +0,0 @@ -Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \ No newline at end of file From 55c43a8a03539041ae322e0c2aabc0f8e5de3bb6 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Fri, 6 Aug 2021 02:05:57 +0300 Subject: [PATCH 56/63] homework_4 tests realization --- .../custom_file_reader/CustomFileReader.java | 13 +++- ...tomFileReader.txt => CustomFileReader.txt} | 0 .../custom_file_reader/testCustom.txt | 1 + .../CustomFileReaderTest.java | 70 +++++++++++++++++++ .../homework_4/singleton/SingletonTest.java | 17 +++++ 5 files changed, 100 insertions(+), 1 deletion(-) rename src/main/resources/custom_file_reader/{testCustomFileReader.txt => CustomFileReader.txt} (100%) create mode 100644 src/main/resources/custom_file_reader/testCustom.txt create mode 100644 src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java create mode 100644 src/test/java/homework_4/singleton/SingletonTest.java diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index b1ebab76..0ef01321 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -13,6 +13,7 @@ public class CustomFileReader { private static final String PATH_TO_FILE = "\\src\\main\\resources\\custom_file_reader\\"; public void run1(String filename) { + isCorrectFilename(filename); List data = new ArrayList<>(); try (BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(getPath(filename))))){ String line; @@ -26,6 +27,7 @@ public void run1(String filename) { } public void run2(String filename) { + isCorrectFilename(filename); try{ Files.lines(Path.of(getPath(filename))).map(x->x.replaceAll("[,.]","")).forEach(System.out::println); } catch (IOException exception){ @@ -34,6 +36,7 @@ public void run2(String filename) { } public void run3(String filename){ + isCorrectFilename(filename); try { Scanner scanner = new Scanner(new FileReader(getPath(filename))); List data = new ArrayList<>(); @@ -46,7 +49,15 @@ public void run3(String filename){ } } - private static String getPath(String fileName){ + private String getPath(String fileName){ return Paths.get("").toAbsolutePath() + PATH_TO_FILE + fileName; } + + private boolean isCorrectFilename(String filename) { + if (!(filename.endsWith(".txt"))) { + throw new IllegalArgumentException(); + } else { + return filename.endsWith(".txt"); + } + } } diff --git a/src/main/resources/custom_file_reader/testCustomFileReader.txt b/src/main/resources/custom_file_reader/CustomFileReader.txt similarity index 100% rename from src/main/resources/custom_file_reader/testCustomFileReader.txt rename to src/main/resources/custom_file_reader/CustomFileReader.txt diff --git a/src/main/resources/custom_file_reader/testCustom.txt b/src/main/resources/custom_file_reader/testCustom.txt new file mode 100644 index 00000000..69b5c67d --- /dev/null +++ b/src/main/resources/custom_file_reader/testCustom.txt @@ -0,0 +1 @@ +Linkin park, Halestorm... The ,,,...Pretty Reckless,,... Disturbed \ No newline at end of file diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..7f654fce --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,70 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBase { + + private final String FILENAME = "testCustom.txt"; + + @Test + void givenFileName_whenRun_thenFileContentPrintOutFirstMode() { + new CustomFileReader().run1(FILENAME); + printOut(); + + assertEquals("Linkin park Halestorm The Pretty Reckless Disturbed", getOutputLines()[0]); + assertNotEquals("TestTestTest", getOutputLines()[0]); + } + + @Test + void givenIncorrectFileName_whenRun_thenExceptionThrownFirstMode(){ + String filenameIncorrect = "testCustom"; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run1(filenameIncorrect)); + } + + @Test + void givenFileName_whenRun_thenFileContentPrintOutSecondMode() { + new CustomFileReader().run2(FILENAME); + printOut(); + + assertEquals("Linkin park Halestorm The Pretty Reckless Disturbed", getOutputLines()[0]); + assertNotEquals("TestTestTest", getOutputLines()[0]); + } + + @Test + void givenIncorrectFileName_whenRun_thenExceptionThrownSecondMode(){ + String filenameIncorrect = "testCustom"; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run2(filenameIncorrect)); + } + + @Test + void givenFileName_whenRun_thenFileContentPrintOutThirdMode() { + new CustomFileReader().run3(FILENAME); + printOut(); + + assertEquals("Linkin park Halestorm The Pretty Reckless Disturbed", getOutputLines()[0]); + assertNotEquals("TestTestTest", getOutputLines()[0]); + } + + @Test + void givenIncorrectFileName_whenRun_thenExceptionThrownThirdMode(){ + String filenameIncorrect = "testCustom"; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run3(filenameIncorrect)); + } + + @Test + void givenEmptyFileName_whenRun_thenExceptionThrown(){ + String emptyName = " "; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run3(emptyName)); + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run2(emptyName)); + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run1(emptyName)); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..c6ff7569 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,17 @@ +package homework_4.singleton; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class SingletonTest extends UnitBase { + + @Test + void givenSingleton_whenRun_thenSimpleClassNameReturned() { + Singleton singleton = Singleton.getInstance(); + System.out.println(singleton.getClass().getSimpleName()); + + assertEquals("Singleton", getOutputLines()[0]); + } +} \ No newline at end of file From ab773e185a18b97a8f3f0f14a3660d285cef419e Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Fri, 6 Aug 2021 02:11:36 +0300 Subject: [PATCH 57/63] README updated --- README.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 46736de7..a797b8c6 100644 --- a/README.md +++ b/README.md @@ -5,10 +5,13 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/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/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | -| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| -| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| -| HW3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| +| HW2.1 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | +| HW2.2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| +| HW2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +| HW3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| +| HW4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_file_reader) |The app that reads file 3 different ways and print the result into console | +| HW4.2 | [My annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_annotation) | My custom annotation that allows to put annotated fields into JSON file| +| HW4.3 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/singleton) |Example of singleton design pattern | [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 7f594b29abf1481d689e7374ae93d147673101dc Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 12 Aug 2021 00:01:23 +0300 Subject: [PATCH 58/63] homework_2,4 fixed. --- README.md | 6 +-- src/main/java/homework_1/CommandLineArgs.java | 6 +-- .../pyramid_printer/PyramidPrinter.java | 11 +---- .../random_chars_table/RandomCharsTable.java | 42 ++++++++----------- .../traffic_light/TrafficLight.java | 14 ++----- .../traffic_light/TrafficLightExtraMod.java | 2 +- .../custom_file_reader/CustomFileReader.java | 3 +- src/main/java/homework_4/singleton/Main.java | 10 +++++ .../java/homework_4/singleton/Singleton.java | 2 +- .../java/homework_2/RandomCharsTableTest.java | 6 +-- .../homework_4/singleton/SingletonTest.java | 3 +- 11 files changed, 45 insertions(+), 60 deletions(-) create mode 100644 src/main/java/homework_4/singleton/Main.java diff --git a/README.md b/README.md index a797b8c6..5aa86626 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | -| HW2.1 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/trafficLight) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | -| HW2.2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramidPrinter) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| -| HW2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/randomCharsTable) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +| HW2.1 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/traffic_light) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | +| HW2.2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramid_printer) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| +| HW2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/random_chars_table) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| | HW3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| | HW4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_file_reader) |The app that reads file 3 different ways and print the result into console | | HW4.2 | [My annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_annotation) | My custom annotation that allows to put annotated fields into JSON file| diff --git a/src/main/java/homework_1/CommandLineArgs.java b/src/main/java/homework_1/CommandLineArgs.java index dd73b5f9..95b74935 100644 --- a/src/main/java/homework_1/CommandLineArgs.java +++ b/src/main/java/homework_1/CommandLineArgs.java @@ -1,10 +1,10 @@ -package Homework_1; +package homework_1; public class CommandLineArgs { - public static final String ANSI_RED = "\u001B[31m"; + private static final String ANSI_RED = "\u001B[31m"; - public static final String ANSI_RESET = "\u001B[0m"; + private static final String ANSI_RESET = "\u001B[0m"; public static void main(String[] args) { for (String s : args) { diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 4b40818d..f03e5959 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -11,10 +11,8 @@ public class PyramidPrinter { public void run() { System.out.println("Please, input a number:"); int input = consoleReader(); - if (negativeInput(input)) { + if (input<0) { System.out.println(ERROR); - } else if (input == 0) { - System.out.println(); } else { printResult(input); } @@ -24,9 +22,8 @@ private int consoleReader() { try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { return Integer.parseInt(bF.readLine()); } catch (NumberFormatException | IOException exception) { - + return -1; } - return -1; } private void printResult(int input) { @@ -36,8 +33,4 @@ private void printResult(int input) { System.out.println(output); } } - - private boolean negativeInput(int n) { - return n < 0; - } } 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 1add8e47..f159cce4 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -5,19 +5,12 @@ import java.io.InputStreamReader; public class RandomCharsTable { - private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; - private char[][] array; - private String strategy; - private String inputData; - private String result; - private int rows; - private int columns; public void run() { @@ -26,21 +19,20 @@ public void run() { parseData(inputData); if (dataValidation(rows, columns, strategy)) { System.out.println(ERROR); - return; - } - arrayInitialization(); - if (inputData.endsWith("odd")) { - odd(); } else { - even(); + arrayInitialization(); + if (strategy.equals("odd")) { + oddStrategy(); + } else { + evenStrategy(); + } + printingResult(); } - printingResult(); } private void parseData(String s){ String[] resultArray = s.split(" "); if(resultArray.length != 3){ - System.out.println(ERROR); return; } rows = Integer.parseInt(resultArray[0]); @@ -55,13 +47,13 @@ private void arrayInitialization() { for (int j = 0; j < columns; j++) { char letters = (char) (Math.random() * 10 + 65); array[i][j] = letters; - System.out.print(array[i][j] + " |"); + System.out.print(array[i][j] + "|"); } System.out.println(); } } - private void odd() { + private void oddStrategy() { result = ""; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { @@ -72,7 +64,7 @@ private void odd() { } } - private void even() { + private void evenStrategy() { result = ""; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { @@ -86,15 +78,15 @@ private void even() { private void printingResult() { if (strategy.equals("even")) { System.out.print("Even letters - "); - } else System.out.print("Odd letters - "); - int counter = 0; - while (counter < result.length()) { - if (counter == result.length() - 1) { - System.out.print(result.charAt(counter)); + } else { + System.out.print("Odd letters - "); + } + for(int i = 0; i< result.length();i++){ + if (i == result.length() - 1) { + System.out.print(result.charAt(i)); break; } - System.out.print(result.charAt(counter) + ", "); - counter++; + System.out.print(result.charAt(i) + ", "); } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 53617416..aaaefb6d 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -26,11 +26,11 @@ public void run() { return; } seconds = Integer.parseInt(input); - if (isNegative(seconds)) { + if (seconds < 0) { System.out.println(ERROR); return; } - if (!dayOverCheck(seconds)) { + if (seconds > 86399) { System.out.println("Day is over"); return; } @@ -51,21 +51,13 @@ protected String consoleReader() { protected void trafficLightColorDetection(int sec) { if (sec % 60 < 35) { System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); - } else if (sec % 60 >= 35 && sec % 60 < 40 || sec % 60 >= 55) { + } else if (sec % 60 < 40 || sec % 60 >= 55) { System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); } else { System.out.print(ANSI_RED + "Red light" + ANSI_RESET); } } - protected boolean isNegative(int input) { - return input < 0; - } - - private boolean dayOverCheck(int input) { - return input <= 86399; - } - private boolean isDigit(String input) { try{ Integer.parseInt(input); diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java index bbf5157e..3f6f7419 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java @@ -6,7 +6,7 @@ public void run() { System.out.println("Enter necessary time in HH:MM:SS format."); String parsedTime = consoleReader(); seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); - if (isNegative(seconds)) { + if (seconds < 0) { System.out.println(ERROR); return; } diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index 0ef01321..c6c9dbf2 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -2,7 +2,6 @@ import java.io.*; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @@ -29,7 +28,7 @@ public void run1(String filename) { public void run2(String filename) { isCorrectFilename(filename); try{ - Files.lines(Path.of(getPath(filename))).map(x->x.replaceAll("[,.]","")).forEach(System.out::println); + Files.lines(Paths.get(getPath(filename))).map(x->x.replaceAll("[,.]","")).forEach(System.out::println); } catch (IOException exception){ System.out.println("Error occurred"); } 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..f4908e77 --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,10 @@ +package homework_4.singleton; + +public class Main { + public static void main(String[] args) { + Singleton firstInstance = Singleton.getInstance(); + System.out.println(firstInstance.getClass().getSimpleName()); + Singleton secondInstance = Singleton.getInstance(); + System.out.println(firstInstance == secondInstance); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java index f3b8dd2e..43b87374 100644 --- a/src/main/java/homework_4/singleton/Singleton.java +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -11,6 +11,6 @@ public static Singleton getInstance() { } private Singleton() { - + System.out.println("Singleton created"); } } diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java index 846d04c1..cf7d0a1a 100644 --- a/src/test/java/homework_2/RandomCharsTableTest.java +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -16,7 +16,7 @@ void givenTwoTwoEven_whenRun_thenMatrixAndLettersPrinted(){ removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); Assertions.assertTrue(getOutput().contains("|")); - Assertions.assertTrue(getOutput().contains(" |")); + Assertions.assertFalse(getOutput().contains(" |")); Assertions.assertTrue(getOutput().contains("Even letters - ")); } @@ -29,7 +29,7 @@ void givenTwoThreeOdd_whenRun_thenMatrixAndLettersPrinted(){ removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); Assertions.assertTrue(getOutput().contains("|")); - Assertions.assertTrue(getOutput().contains(" |")); + Assertions.assertFalse(getOutput().contains(" |")); Assertions.assertTrue(getOutput().contains("Odd letters - ")); } @@ -43,8 +43,6 @@ void givenNotFullParameters_whenRun_thenError(){ Assertions.assertEquals("Passed parameters should match the format [positive integer] " + "[positive integer] [even|odd]",getOutputLines()[0]); - Assertions.assertEquals("Passed parameters should match the format [positive integer] " + - "[positive integer] [even|odd]",getOutputLines()[1]); } @Test diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java index c6ff7569..197e49ca 100644 --- a/src/test/java/homework_4/singleton/SingletonTest.java +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -12,6 +12,7 @@ void givenSingleton_whenRun_thenSimpleClassNameReturned() { Singleton singleton = Singleton.getInstance(); System.out.println(singleton.getClass().getSimpleName()); - assertEquals("Singleton", getOutputLines()[0]); + assertEquals("Singleton created", getOutputLines()[0]); + assertEquals("Singleton", getOutputLines()[1]); } } \ No newline at end of file From 2cf9724ebdc7f1205dfd427feef816165390bb24 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Wed, 8 Sep 2021 01:03:29 +0300 Subject: [PATCH 59/63] homework 5 done. --- README.md | 3 +- .../CustomRegexMatcher.java | 18 ++++++ .../homework_5/custom_regex_matcher/Main.java | 8 +++ .../java/homework_5/power_of_number/Main.java | 8 +++ .../power_of_number/PowerOfNumber.java | 43 +++++++++++++ .../CustomRegexMatcherTest.java | 40 +++++++++++++ .../power_of_number/PowerOfNumberTest.java | 60 +++++++++++++++++++ 7 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java create mode 100644 src/main/java/homework_5/custom_regex_matcher/Main.java create mode 100644 src/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/custom_regex_matcher/CustomRegexMatcherTest.java create mode 100644 src/test/java/homework_5/power_of_number/PowerOfNumberTest.java diff --git a/README.md b/README.md index 5aa86626..45a54f41 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ | HW4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_file_reader) |The app that reads file 3 different ways and print the result into console | | HW4.2 | [My annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_annotation) | My custom annotation that allows to put annotated fields into JSON file| | HW4.3 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/singleton) |Example of singleton design pattern | - +| HW5.1 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_5/power_of_number) |The app that raises to the power of input using recursion | +| HW5.2 | [Custom regex matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_5/custom_regex_matcher) |The app that simulate password regex matcher | [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..7eb837b0 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,18 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + private final Scanner sc = new Scanner(System.in); + + public void run() { + String input = sc.nextLine(); + System.out.println(matcher(input)); + } + + private boolean matcher(String s) { + String passwordRegex = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; + return Pattern.matches(passwordRegex, s); + } +} 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..0f412d29 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,8 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); + customRegexMatcher.run(); + } +} 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..18d1c211 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,8 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + PowerOfNumber powerOfNumber = new PowerOfNumber(); + powerOfNumber.run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..8b601b70 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,43 @@ +package homework_5.power_of_number; + +import java.util.Arrays; +import java.util.Scanner; + +public class PowerOfNumber { + private final Scanner sc = new Scanner(System.in); + private final String ERROR = "Only 2 non-negative integers are allowed"; + + public void run() { + String input = sc.nextLine(); + Integer[] inputData = parseData(input); + int value = inputData[0]; + int powValue = inputData[2]; + int result = pow(value, powValue); + if(result == -1){ + System.out.println(ERROR); + } else { + System.out.println(result); + } + } + + private int pow(int value, int powValue) { + if (powValue == 0) { + return 1; + } else if (powValue == 1) { + return value; + } else if (value < 0 || powValue < 0) { + return -1; + } else { + return value * pow(value, powValue - 1); + } + } + + private Integer[] parseData(String s) { + Character[] array = s.chars().mapToObj(c -> (char) c).toArray(Character[]::new); + if (array.length != 3 || (!Character.isDigit(array[0])) || (!Character.isDigit(array[2]))) { + return new Integer[]{-1, 0, -1}; + } else { + return Arrays.stream(array).map(Character::getNumericValue).toArray(Integer[]::new); + } + } +} diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..ca8b2775 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,40 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomRegexMatcherTest extends UnitBase { + + @Test + void givenMatchingString_whenRun_thenTrueReturned() { + setInput("KissKiss#1"); + + new CustomRegexMatcher().run(); + printOut(); + + Assertions.assertEquals("true", getOutput()); + } + + @Test + void givenTooShortString_whenRun_thenFalseReturned() { + setInput("test"); + + new CustomRegexMatcher().run(); + printOut(); + + Assertions.assertEquals("false",getOutput()); + } + + @Test + void givenNotMatchingString_whenRun_thenFalseReturned() { + setInput("test1test1"); + + new CustomRegexMatcher().run(); + printOut(); + + Assertions.assertEquals("false", getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..1bbbbec4 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,60 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + + @Test + void givenValidInput_whenRun_thenResultPrinted() { + setInput("2 2"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("4", getOutput()); + } + + @Test + void givenNegativeNumbers_whenRun_thenError() { + setInput("-1 -1"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } + + @Test + void givenNotFullInput_whenRun_thenError(){ + setInput("1 "); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } + + @Test + void givenString_whenRun_thenError(){ + setInput("t t"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } + + @Test + void givenMoreParameters_whenRun_thenError(){ + setInput("1 2 3"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } +} \ No newline at end of file From ab37ecc7de2e0e04aabd1c1a3cc5de800c3cd67b Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Wed, 8 Sep 2021 01:40:39 +0300 Subject: [PATCH 60/63] homework 6 done. --- README.md | 1 + .../map_problems_generator/Main.java | 32 ++++++++++++++ .../MapProblemsCollisionGenerator.java | 37 ++++++++++++++++ .../MapProblemsMutableGenerator.java | 42 +++++++++++++++++++ 4 files changed, 112 insertions(+) create mode 100644 src/main/java/homework_6/map_problems_generator/Main.java create mode 100644 src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java create mode 100644 src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java diff --git a/README.md b/README.md index 45a54f41..3b6085f1 100644 --- a/README.md +++ b/README.md @@ -14,5 +14,6 @@ | HW4.3 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/singleton) |Example of singleton design pattern | | HW5.1 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_5/power_of_number) |The app that raises to the power of input using recursion | | HW5.2 | [Custom regex matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_5/custom_regex_matcher) |The app that simulate password regex matcher | +| HW6 | [Map problems generator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_6/map_problems_generator) |Example of problems that may occur if contract of equals & hashCode are not followed and if mutable class if used as a key | [Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java new file mode 100644 index 00000000..4d3d0ab8 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,32 @@ +package homework_6.map_problems_generator; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + public static void main(String[] args) { + Map collisionGenerator = new HashMap<>(); + MapProblemsCollisionGenerator firstCollisionKey = new MapProblemsCollisionGenerator(1, "firstValue"); + MapProblemsCollisionGenerator secondCollisionKey = new MapProblemsCollisionGenerator(1, "secondValue"); + MapProblemsCollisionGenerator thirdCollisionKey = new MapProblemsCollisionGenerator(2, "thirdValue"); + + collisionGenerator.put(firstCollisionKey, "firstV"); + collisionGenerator.put(secondCollisionKey, "secondV"); + collisionGenerator.put(thirdCollisionKey, "thirdV"); + + System.out.println(collisionGenerator.get(firstCollisionKey) + " is not firstV"); + System.out.println(collisionGenerator.get(secondCollisionKey) + " is not secondV"); + System.out.println(collisionGenerator.get(thirdCollisionKey) + " is not thirdV"); + + Map mutableGenerator = new HashMap<>(); + MapProblemsMutableGenerator firstMutableKey = new MapProblemsMutableGenerator(1, "firstValue"); + MapProblemsMutableGenerator secondMutableKey = new MapProblemsMutableGenerator(2, "thirdValue"); + + mutableGenerator.put(firstMutableKey, "firstV"); + mutableGenerator.put(secondMutableKey, "thirdV"); + + System.out.println("Before changing " + mutableGenerator.get(firstMutableKey)); + firstMutableKey.setKey(2); + System.out.println("After changing " + mutableGenerator.get(firstMutableKey)); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..dee8c8db --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java @@ -0,0 +1,37 @@ +package homework_6.map_problems_generator; + +public class MapProblemsCollisionGenerator { + private int key; + private String value; + + public MapProblemsCollisionGenerator(int key, String value) { + this.key = key; + this.value = value; + } + + public int getKey() { + return key; + } + + public void setKey(int key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + return true; + } + + @Override + public int hashCode() { + return key; + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..48b1ba77 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -0,0 +1,42 @@ +package homework_6.map_problems_generator; + +import java.util.Objects; + +public class MapProblemsMutableGenerator { + private int key; + private String value; + + public MapProblemsMutableGenerator(int key, String value) { + this.key = key; + this.value = value; + } + + public int getKey() { + return key; + } + + public void setKey(int key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + if(this == o) return true; + if(o == null ||getClass() != o.getClass()) return false; + MapProblemsMutableGenerator another = (MapProblemsMutableGenerator) o; + return key == another.key && Objects.equals(value, another.value); + } + + @Override + public int hashCode() { + return Objects.hash(key, key); + } +} From 18ae0d6449531d338f197fa75d64ca611a775312 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Wed, 22 Sep 2021 21:30:48 +0300 Subject: [PATCH 61/63] homework 7 and course project done. --- src/main/java/course_project/Main.java | 11 + .../custom_exceptions/CoordinatesNumber.java | 8 + .../custom_exceptions/InvalidShip.java | 8 + .../custom_exceptions/PlaceNotFree.java | 8 + .../course_project/model/Battlefield.java | 19 + .../course_project/model/Designation.java | 30 ++ .../java/course_project/model/Player.java | 56 +++ .../service/BattleFieldService.java | 339 ++++++++++++++++++ .../course_project/service/PlayerService.java | 89 +++++ .../java/course_project/service/Runner.java | 60 ++++ .../kitten_to_cat_function/Cat.java | 35 ++ .../kitten_to_cat_function/Kitten.java | 25 ++ .../KittenToCatFunction.java | 6 + .../kitten_to_cat_function/Main.java | 15 + 14 files changed, 709 insertions(+) create mode 100644 src/main/java/course_project/Main.java create mode 100644 src/main/java/course_project/custom_exceptions/CoordinatesNumber.java create mode 100644 src/main/java/course_project/custom_exceptions/InvalidShip.java create mode 100644 src/main/java/course_project/custom_exceptions/PlaceNotFree.java create mode 100644 src/main/java/course_project/model/Battlefield.java create mode 100644 src/main/java/course_project/model/Designation.java create mode 100644 src/main/java/course_project/model/Player.java create mode 100644 src/main/java/course_project/service/BattleFieldService.java create mode 100644 src/main/java/course_project/service/PlayerService.java create mode 100644 src/main/java/course_project/service/Runner.java create mode 100644 src/main/java/homework_7/kitten_to_cat_function/Cat.java create mode 100644 src/main/java/homework_7/kitten_to_cat_function/Kitten.java create mode 100644 src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java create mode 100644 src/main/java/homework_7/kitten_to_cat_function/Main.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..71a2a19d --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +import course_project.service.Runner; + +public class Main { + public static void main(String[] args) { + Runner runner = new Runner(); + runner.run(); + } + +} diff --git a/src/main/java/course_project/custom_exceptions/CoordinatesNumber.java b/src/main/java/course_project/custom_exceptions/CoordinatesNumber.java new file mode 100644 index 00000000..a539ca28 --- /dev/null +++ b/src/main/java/course_project/custom_exceptions/CoordinatesNumber.java @@ -0,0 +1,8 @@ +package course_project.custom_exceptions; + +public class CoordinatesNumber extends Exception{ + + public CoordinatesNumber() { + super("Number of coordinates don't fit ship length"); + } +} diff --git a/src/main/java/course_project/custom_exceptions/InvalidShip.java b/src/main/java/course_project/custom_exceptions/InvalidShip.java new file mode 100644 index 00000000..639b30cd --- /dev/null +++ b/src/main/java/course_project/custom_exceptions/InvalidShip.java @@ -0,0 +1,8 @@ +package course_project.custom_exceptions; + +public class InvalidShip extends Exception { + + public InvalidShip() { + super("Invalid place for ship! It should be horizontal, vertical and solid structure"); + } +} diff --git a/src/main/java/course_project/custom_exceptions/PlaceNotFree.java b/src/main/java/course_project/custom_exceptions/PlaceNotFree.java new file mode 100644 index 00000000..c5f8c4d2 --- /dev/null +++ b/src/main/java/course_project/custom_exceptions/PlaceNotFree.java @@ -0,0 +1,8 @@ +package course_project.custom_exceptions; + +public class PlaceNotFree extends Exception { + + public PlaceNotFree() { + super("Invalid place for ship: this place is already occupied by another ship or another ship is too close"); + } +} diff --git a/src/main/java/course_project/model/Battlefield.java b/src/main/java/course_project/model/Battlefield.java new file mode 100644 index 00000000..b7071cd9 --- /dev/null +++ b/src/main/java/course_project/model/Battlefield.java @@ -0,0 +1,19 @@ +package course_project.model; + +import java.util.Arrays; + +public class Battlefield { + private Designation[][] grid; + + public Battlefield() { + grid = new Designation[11][11]; + for (Designation[] cell : grid) { + Arrays.fill(cell, Designation.EMPTY); + } + } + + public Designation[][] getGrid() { + return grid; + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/model/Designation.java b/src/main/java/course_project/model/Designation.java new file mode 100644 index 00000000..ed096458 --- /dev/null +++ b/src/main/java/course_project/model/Designation.java @@ -0,0 +1,30 @@ +package course_project.model; + +public enum Designation { + SHIP("⬜", 0), + FOUR_DECKER("", 4), + THREE_DECKER("", 3), + TWO_DECKER("", 2), + ONE_DECKER("",1), + HIT("x", 0), + EMPTY("~", 0), + MISS("◾", 0), + GAP("🟦", 0); + + private String sign; + private int length; + + Designation(String sign, int length) { + this.sign = sign; + this.length = length; + } + + @Override + public String toString() { + return sign; + } + + public int getLength() { + return length; + } +} diff --git a/src/main/java/course_project/model/Player.java b/src/main/java/course_project/model/Player.java new file mode 100644 index 00000000..732ca311 --- /dev/null +++ b/src/main/java/course_project/model/Player.java @@ -0,0 +1,56 @@ +package course_project.model; + +import java.io.IOException; +import java.util.Scanner; + +public class Player { + + private Battlefield myField; + private Battlefield enemyField; + private String name; + private int shipsAmount; + + public Player() { + myField = new Battlefield(); + enemyField = new Battlefield(); + shipsAmount = 10; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + + + public Designation[][] getGrid() { + return myField.getGrid(); + } + + public Battlefield getField() { + return this.myField; + } + + public Battlefield getEnemyField() { + return this.enemyField; + } + + public void setMyField(Battlefield myField) { + this.myField = myField; + } + + public void setEnemyField(Battlefield enemyField) { + this.enemyField = enemyField; + } + + public int getShipsAmount() { + return shipsAmount; + } + + public void setShipsAmount(int shipsAmount) { + this.shipsAmount = shipsAmount; + } +} diff --git a/src/main/java/course_project/service/BattleFieldService.java b/src/main/java/course_project/service/BattleFieldService.java new file mode 100644 index 00000000..3cc9f6f3 --- /dev/null +++ b/src/main/java/course_project/service/BattleFieldService.java @@ -0,0 +1,339 @@ +package course_project.service; + +import course_project.custom_exceptions.CoordinatesNumber; +import course_project.custom_exceptions.InvalidShip; +import course_project.custom_exceptions.PlaceNotFree; +import course_project.model.Battlefield; +import course_project.model.Designation; +import course_project.model.Player; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; + +public class BattleFieldService { + + private final Battlefield battlefield; + + public BattleFieldService(Battlefield battlefield) { + this.battlefield = battlefield; + } + + public void print(Battlefield battlefield) { + Designation[][] grid = battlefield.getGrid(); + for (int i = 1; i < grid.length; i++) { + if (i == 1) { + System.out.print(" \t"); + for (int j = 1; j < 11; j++) { + System.out.print((char) ('A' + (j - 1)) + "\t"); + } + System.out.println(); + } + System.out.print(i + "\t"); + for (int j = 1; j < grid[i].length; j++) { + System.out.print((j == grid[i].length - 1) ? (grid[i][j] + "\n") : grid[i][j] + "\t"); + } + } + } + + public void arrangement(Player player, Scanner readIt) { + + System.out.println(player.getName() + ", your field is below\n"); + print(player.getField()); + + while (true) { + try { + System.out.println(player.getName() + ", enter coordinates of four-decker (format: A1;A2;A3;A4)"); + putShip(player, readIt.nextLine(), Designation.FOUR_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip exc) { + System.out.println(exc.getMessage()); + } + } + + for (int i = 0; i < 2; i++) { + while (true) { + try { + System.out.println("Enter coordinates of three-decker (format: A1;A2;A3)"); + putShip(player, readIt.nextLine(), Designation.THREE_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + } + } + + for (int i = 0; i < 3; i++) { + while (true) { + try { + System.out.println("Enter coordinates of two-decker (format: A1;A2)"); + putShip(player, readIt.nextLine(), Designation.TWO_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + } + } + + for (int i = 0; i < 4; i++) { + while (true) { + try { + System.out.println("Enter coordinates of one-decker (format: A1)"); + putShip(player, readIt.nextLine(), Designation.ONE_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + } + } + System.out.println("Fields with all ships: "); + print(player.getField()); + System.out.println("Enter any to skip your field"); + readIt.nextLine(); + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n"); + } + + public boolean isDead(Battlefield battlefield, int x, int y) { + for (int i = 1; i <= 3; i++) { + if (x - i >= 0 && battlefield.getGrid()[x - i][y] == Designation.SHIP) { + return false; + } else if (x - i >= 0 && battlefield.getGrid()[x - i][y] != Designation.HIT) { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (x + i <= 9 && battlefield.getGrid()[x + i][y] == Designation.SHIP) { + return false; + } else if (x + i <= 9 && battlefield.getGrid()[x + i][y] != Designation.HIT) { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y - i >= 0 && battlefield.getGrid()[x][y - i] == Designation.SHIP) { + return false; + } else if (y - i >= 0 && battlefield.getGrid()[x][y - i] != Designation.HIT) { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y + i <= 9 && battlefield.getGrid()[x][y + i] == Designation.SHIP) { + return false; + } else if (y + i <= 9 && battlefield.getGrid()[x][y + i] != Designation.HIT) { + break; + } + } + return true; + } + + public void surroundDeadShip(Battlefield battlefield, int x, int y) { + List deadShipCoords = new ArrayList<>(); + deadShipCoords.add(new int[]{x, y}); + + for (int i = 1; i <= 3; i++) { + if (x - i >= 0 && battlefield.getGrid()[x - i][y] == Designation.HIT) { + deadShipCoords.add(new int[]{x - i, y}); + } else { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (x + i <= 9 && battlefield.getGrid()[x + i][y] == Designation.HIT) { + deadShipCoords.add(new int[]{x + i, y}); + } else { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y - i >= 0 && battlefield.getGrid()[x][y - i] == Designation.HIT) { + deadShipCoords.add(new int[]{x, y - i}); + } else { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y + i <= 9 && battlefield.getGrid()[x][y + i] == Designation.HIT) { + deadShipCoords.add(new int[]{x, y + i}); + } else { + break; + } + } + + for (int[] coord : deadShipCoords) { + int a = coord[0]; + int b = coord[1]; + + if (a - 1 >= 0 && battlefield.getGrid()[a - 1][b] != Designation.HIT) { + battlefield.getGrid()[a - 1][b] = Designation.MISS; + } + if (a - 1 >= 0 && b + 1 <= 9 && battlefield.getGrid()[a - 1][b + 1] != Designation.SHIP) { + battlefield.getGrid()[a - 1][b + 1] = Designation.MISS; + } + if (b + 1 <= 9 && battlefield.getGrid()[a][b + 1] != Designation.HIT) { + battlefield.getGrid()[a][b + 1] = Designation.MISS; + } + if (a + 1 <= 9 && b + 1 <= 9 && battlefield.getGrid()[a + 1][b + 1] != Designation.HIT) { + battlefield.getGrid()[a + 1][b + 1] = Designation.MISS; + } + if (a + 1 <= 9 && battlefield.getGrid()[a + 1][b] != Designation.HIT) { + battlefield.getGrid()[a + 1][b] = Designation.MISS; + } + if (a + 1 <= 9 && b - 1 >= 0 && battlefield.getGrid()[a + 1][b - 1] != Designation.HIT) { + battlefield.getGrid()[a + 1][b - 1] = Designation.MISS; + } + if (b - 1 >= 0 && battlefield.getGrid()[a][b - 1] != Designation.HIT) { + battlefield.getGrid()[a][b - 1] = Designation.MISS; + } + if (a - 1 >= 0 && b - 1 >= 0 && battlefield.getGrid()[a - 1][b - 1] != Designation.HIT) { + battlefield.getGrid()[a - 1][b - 1] = Designation.MISS; + } + } + } + + private void putShip(Player player, String strCoords, Designation ship) throws CoordinatesNumber, IOException, InvalidShip, PlaceNotFree { + + String[] shipCoordsArray = strCoords.split(";"); + + if (shipCoordsArray.length != ship.getLength()) { + throw new CoordinatesNumber(); + } + + int[][] digitalCoords = new int[shipCoordsArray.length][2]; + + for (int i = 0; i < shipCoordsArray.length; i++) { + if (Character.isDigit(shipCoordsArray[i].charAt(0)) || !Character.isDigit(shipCoordsArray[i].charAt(1))) { + System.out.println("Invalid input format! X should be letter A-J and Y - numbers 0 - 9"); + throw new IOException(); + } + + digitalCoords[i][0] = Character.getNumericValue(shipCoordsArray[i].charAt(1)); + digitalCoords[i][1] = shipCoordsArray[i].charAt(0) - 64; + } + + if (!isValid(digitalCoords)) { + throw new InvalidShip(); + } + if (!isFree(digitalCoords, player.getField().getGrid())) { + throw new PlaceNotFree(); + } + + for (int[] digitalCoord : digitalCoords) { + + player.getField().getGrid()[digitalCoord[0]][digitalCoord[1]] = Designation.SHIP; + } + + for (int[] digitalCoord : digitalCoords) { + int x = digitalCoord[0]; + int y = digitalCoord[1]; + + if (x - 1 >= 0 && player.getField().getGrid()[x - 1][y] != Designation.SHIP) { + player.getField().getGrid()[x - 1][y] = Designation.GAP; + } + if (x - 1 >= 0 && y + 1 <= 9 && player.getField().getGrid()[x - 1][y + 1] != Designation.SHIP) { + player.getField().getGrid()[x - 1][y + 1] = Designation.GAP; + } + if (y + 1 <= 9 && player.getField().getGrid()[x][y + 1] != Designation.SHIP) { + player.getField().getGrid()[x][y + 1] = Designation.GAP; + } + if (x + 1 <= 9 && y + 1 <= 9 && player.getField().getGrid()[x + 1][y + 1] != Designation.SHIP) { + player.getField().getGrid()[x + 1][y + 1] = Designation.GAP; + } + if (x + 1 <= 9 && player.getField().getGrid()[x + 1][y] != Designation.SHIP) { + player.getField().getGrid()[x + 1][y] = Designation.GAP; + } + if (x + 1 <= 9 && y - 1 >= 0 && player.getField().getGrid()[x + 1][y - 1] != Designation.SHIP) { + player.getField().getGrid()[x + 1][y - 1] = Designation.GAP; + } + if (y - 1 >= 0 && player.getField().getGrid()[x][y - 1] != Designation.SHIP) { + player.getField().getGrid()[x][y - 1] = Designation.GAP; + } + if (x - 1 >= 0 && y - 1 >= 0 && player.getField().getGrid()[x - 1][y - 1] != Designation.SHIP) { + player.getField().getGrid()[x - 1][y - 1] = Designation.GAP; + } + } + } + + private boolean isValid(int[][] coords) { + if (coords.length == 1) { + return true; + } + + int x = coords[0][0]; + int y = coords[0][1]; + boolean isCorrect = true; + + for (int i = 1; i < coords.length; i++) { + if (coords[i][0] == x) { + + for (int j = 0; j < coords.length; j++) { + if (i == j) { + continue; + } + + if (coords[i][1] == coords[j][1] || coords[i][1] == y) { + isCorrect = false; + break; + } + } + + int[] isAdjacent = new int[coords.length]; + + for (int j = 0; j < coords.length; j++) { + isAdjacent[j] = coords[j][1]; + } + Arrays.sort(isAdjacent); + + for (int t = 0; t < isAdjacent.length - 1; t++) { + isCorrect = isAdjacent[t + 1] == (isAdjacent[t] + 1) && isCorrect; + } + + } else if (coords[i][1] == y) { + for (int j = 0; j < coords.length; j++) { + if (i == j) { + continue; + } + + if (coords[i][0] == coords[j][0] || coords[i][0] == x) { + isCorrect = false; + break; + } + } + + int[] isAdjacent = new int[coords.length]; + for (int j = 0; j < coords.length; j++) { + isAdjacent[j] = coords[j][0]; + } + Arrays.sort(isAdjacent); + + for (int t = 0; t < isAdjacent.length - 1; t++) { + isCorrect = isAdjacent[t + 1] == (isAdjacent[t] + 1) && isCorrect; + } + + } else { + isCorrect = false; + } + } + return isCorrect; + } + + private boolean isFree(int[][] coords, Designation[][] field) { + for (int[] coord : coords) { + if (!(field[coord[0]][coord[1]] == Designation.EMPTY)) { + return false; + } + } + return true; + } + +} diff --git a/src/main/java/course_project/service/PlayerService.java b/src/main/java/course_project/service/PlayerService.java new file mode 100644 index 00000000..988f0018 --- /dev/null +++ b/src/main/java/course_project/service/PlayerService.java @@ -0,0 +1,89 @@ +package course_project.service; + +import course_project.model.Battlefield; +import course_project.model.Designation; +import course_project.model.Player; + +import java.io.IOException; +import java.util.Scanner; + +public class PlayerService { + + private final BattleFieldService battleFieldService; + private final Player player; + + public PlayerService(Player player, BattleFieldService battleFieldService) { + this.player = player; + this.battleFieldService = battleFieldService; + } + + public boolean makeShot(Player currentPlayer, Player enemy, Scanner readIt) throws IOException { + int shipAmount = enemy.getShipsAmount(); + + System.out.println("Your battlefield:"); + battleFieldService.print(currentPlayer.getField()); + System.out.println("Enemy battlefield:"); + battleFieldService.print(currentPlayer.getEnemyField()); + + System.out.println("Player " + currentPlayer.getName() + "is playing. Enter coordinates int format \"A1\""); + + while (true) { + String strCoord = readIt.nextLine(); + + if (strCoord.length() != 2 || + Character.isDigit(strCoord.charAt(0)) || !Character.isDigit(strCoord.charAt(1))) { + System.out.println("Invalid format of input! Enter coordinates in format \"A1\""); + throw new IOException(); + } + + int x = Character.getNumericValue(strCoord.charAt(1)); + int y = strCoord.charAt(0) - 64; + + if (enemy.getGrid()[x][y] == Designation.SHIP) { + + enemy.getGrid()[x][y] = Designation.HIT; + enemy.getField().getGrid()[x][y] = Designation.HIT; + + if (battleFieldService.isDead(enemy.getField(), x, y)) { + battleFieldService.surroundDeadShip(currentPlayer.getEnemyField(), x, y); + battleFieldService.surroundDeadShip(enemy.getField(), x, y); + } + + System.out.println("Your field:"); + battleFieldService.print(currentPlayer.getField()); + System.out.println("Enemy field:"); + battleFieldService.print(currentPlayer.getEnemyField()); + System.out.println("HIT!"); + + if (battleFieldService.isDead(enemy.getField(), x, y)) { + System.out.println("Ship totally destroyed!"); + enemy.setShipsAmount(shipAmount--); + } + + if (enemy.getShipsAmount() == 0) { + System.out.println("Congratulations to player " + currentPlayer + "!"); + return false; + } else { + System.out.println("Shoot one more time!"); + } + + } else if (enemy.getGrid()[x][y] == Designation.HIT) { + System.out.println("You already shoot here! Shoot one more time!"); + } else { + enemy.getGrid()[x][y] = Designation.MISS; + currentPlayer.getEnemyField().getGrid()[x][y] = Designation.MISS; + System.out.println("Your field:"); + battleFieldService.print(currentPlayer.getField()); + System.out.println("Enemy field:"); + battleFieldService.print(currentPlayer.getEnemyField()); + System.out.println("MISS!"); + break; + } + } + System.out.println(currentPlayer.getName() + ", your turn is over. Press Enter to pass the turn to another player"); + readIt.nextLine(); + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n"); + return true; + } + +} diff --git a/src/main/java/course_project/service/Runner.java b/src/main/java/course_project/service/Runner.java new file mode 100644 index 00000000..85a9aeba --- /dev/null +++ b/src/main/java/course_project/service/Runner.java @@ -0,0 +1,60 @@ +package course_project.service; + +import course_project.model.Battlefield; +import course_project.model.Player; + +import java.io.IOException; +import java.util.Scanner; + +public class Runner { + public void run() { + Player a, b, c; + boolean win; + Scanner readIt = new Scanner(System.in); + + Player player1 = new Player(); + Player player2 = new Player(); + Battlefield battlefieldOne = new Battlefield(); + Battlefield battlefieldTwo = new Battlefield(); + BattleFieldService playerOneBattlefieldService = new BattleFieldService(battlefieldOne); + BattleFieldService playerTwoBattlefieldService = new BattleFieldService(battlefieldTwo); + PlayerService playerServiceOne = new PlayerService(player1, playerOneBattlefieldService); + PlayerService playerServiceTwo = new PlayerService(player2, playerTwoBattlefieldService); + System.out.println("Enter name of the first player"); + player1.setName(readIt.nextLine()); + System.out.println("Enter name of the second player"); + player2.setName(readIt.nextLine()); + + playerOneBattlefieldService.arrangement(player1, readIt); + playerTwoBattlefieldService.arrangement(player2, readIt); + + int first = (int) (Math.random() * 2); + if (first == 0) { + a = player1; + b = player2; + } else { + a = player2; + b = player1; + } + System.out.println("Players have put their ships. Let the battle begin!\n Player " + a.getName() + " starts"); + + do { + while (true) { + try { + win = playerServiceOne.makeShot(a, b, readIt); + break; + } catch (IOException e) { + System.out.println(a.getName() + ", enter coordinates in format \"A1\""); + } + } + c = a; + a = b; + b = c; + } while (!win); + + System.out.println("Game is over!"); + + readIt.close(); + } +} + diff --git a/src/main/java/homework_7/kitten_to_cat_function/Cat.java b/src/main/java/homework_7/kitten_to_cat_function/Cat.java new file mode 100644 index 00000000..592ecc3f --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Cat.java @@ -0,0 +1,35 @@ +package homework_7.kitten_to_cat_function; + +public class Cat { + private String name; + private int age; + + public Cat(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/Kitten.java b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java new file mode 100644 index 00000000..3fe6e890 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java @@ -0,0 +1,25 @@ +package homework_7.kitten_to_cat_function; + +public class Kitten extends Cat { + private String parentName; + + public Kitten(String name, int age, String parentName) { + super(name, age); + this.parentName = parentName; + } + + public String getParentName() { + return parentName; + } + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + @Override + public String toString() { + return "Kitten{" + + "parentName='" + parentName + '\'' + + '}' + super.toString(); + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java new file mode 100644 index 00000000..5c7b09d5 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7.kitten_to_cat_function; + +@FunctionalInterface +public interface KittenToCatFunction { + Cat grow(Kitten kitten); +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/Main.java b/src/main/java/homework_7/kitten_to_cat_function/Main.java new file mode 100644 index 00000000..b601b818 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Main.java @@ -0,0 +1,15 @@ +package homework_7.kitten_to_cat_function; + +public class Main { + public static void main(String[] args) { + Cat cat = new Cat("Anfisa", 10); + Kitten kitten = new Kitten("Sam", 3, "test"); + + KittenToCatFunction kittenToCatFunction = newKitten -> new Cat(newKitten.getName() + "Cat", newKitten.getAge() + 10); + Cat oldKitten = kittenToCatFunction.grow(kitten); + + System.out.println(cat); + System.out.println(kitten); + System.out.println(oldKitten); + } +} From 2bd2afdea054f87aa90259d277a6b6384fc8a10d Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 23 Sep 2021 15:21:43 +0300 Subject: [PATCH 62/63] course project fixed --- .../course_project/model/Designation.java | 8 ++-- .../service/BattleFieldService.java | 38 ++++++++++++++++--- .../course_project/service/PlayerService.java | 8 ++-- .../java/course_project/service/Runner.java | 17 +++++++-- 4 files changed, 55 insertions(+), 16 deletions(-) diff --git a/src/main/java/course_project/model/Designation.java b/src/main/java/course_project/model/Designation.java index ed096458..316fa89f 100644 --- a/src/main/java/course_project/model/Designation.java +++ b/src/main/java/course_project/model/Designation.java @@ -1,15 +1,15 @@ package course_project.model; public enum Designation { - SHIP("⬜", 0), + SHIP("◾", 0), FOUR_DECKER("", 4), THREE_DECKER("", 3), TWO_DECKER("", 2), - ONE_DECKER("",1), + ONE_DECKER("", 1), HIT("x", 0), EMPTY("~", 0), - MISS("◾", 0), - GAP("🟦", 0); + MISS("*", 0), + GAP("o", 0); private String sign; private int length; diff --git a/src/main/java/course_project/service/BattleFieldService.java b/src/main/java/course_project/service/BattleFieldService.java index 3cc9f6f3..d1fdb45e 100644 --- a/src/main/java/course_project/service/BattleFieldService.java +++ b/src/main/java/course_project/service/BattleFieldService.java @@ -8,10 +8,7 @@ import course_project.model.Player; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Scanner; +import java.util.*; public class BattleFieldService { @@ -38,6 +35,37 @@ public void print(Battlefield battlefield) { } } + public void autoShipPlacement(Player player) { + String fourDecker = "A1;A2;A3;A4"; + String threeDeckerFirst = "C1;C2;C3"; + String threeDeckerSecond = "C5;C6;C7"; + String twoDeckerFirst = "E1;E2"; + String twoDeckerSecond = "E4;E5"; + String twoDeckerThird = "E7;E8"; + String oneDeckerFirst = "G1"; + String oneDeckerSecond = "G3"; + String oneDeckerThird = "G5"; + String oneDeckerFourth = "G7"; + + try { + putShip(player, fourDecker, Designation.FOUR_DECKER); + putShip(player, threeDeckerFirst, Designation.THREE_DECKER); + putShip(player, threeDeckerSecond, Designation.THREE_DECKER); + putShip(player, twoDeckerFirst, Designation.TWO_DECKER); + putShip(player, twoDeckerSecond, Designation.TWO_DECKER); + putShip(player, twoDeckerThird, Designation.TWO_DECKER); + putShip(player, oneDeckerFirst, Designation.ONE_DECKER); + putShip(player, oneDeckerSecond, Designation.ONE_DECKER); + putShip(player, oneDeckerThird, Designation.ONE_DECKER); + putShip(player, oneDeckerFourth, Designation.ONE_DECKER); + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + System.out.println("Fields with all ships: "); + print(player.getField()); + System.out.println("\n\n"); + } + public void arrangement(Player player, Scanner readIt) { System.out.println(player.getName() + ", your field is below\n"); @@ -218,7 +246,7 @@ private void putShip(Player player, String strCoords, Designation ship) throws C } digitalCoords[i][0] = Character.getNumericValue(shipCoordsArray[i].charAt(1)); - digitalCoords[i][1] = shipCoordsArray[i].charAt(0) - 64; + digitalCoords[i][1] = shipCoordsArray[i].toLowerCase().charAt(0) - 96; } if (!isValid(digitalCoords)) { diff --git a/src/main/java/course_project/service/PlayerService.java b/src/main/java/course_project/service/PlayerService.java index 988f0018..f203b0e3 100644 --- a/src/main/java/course_project/service/PlayerService.java +++ b/src/main/java/course_project/service/PlayerService.java @@ -37,7 +37,7 @@ public boolean makeShot(Player currentPlayer, Player enemy, Scanner readIt) thro } int x = Character.getNumericValue(strCoord.charAt(1)); - int y = strCoord.charAt(0) - 64; + int y = strCoord.toLowerCase().charAt(0) - 96; if (enemy.getGrid()[x][y] == Designation.SHIP) { @@ -57,10 +57,10 @@ public boolean makeShot(Player currentPlayer, Player enemy, Scanner readIt) thro if (battleFieldService.isDead(enemy.getField(), x, y)) { System.out.println("Ship totally destroyed!"); - enemy.setShipsAmount(shipAmount--); + enemy.setShipsAmount(--shipAmount); } - if (enemy.getShipsAmount() == 0) { + if (enemy.getShipsAmount() < 0) { System.out.println("Congratulations to player " + currentPlayer + "!"); return false; } else { @@ -82,7 +82,7 @@ public boolean makeShot(Player currentPlayer, Player enemy, Scanner readIt) thro } System.out.println(currentPlayer.getName() + ", your turn is over. Press Enter to pass the turn to another player"); readIt.nextLine(); - System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n"); + System.out.println("\n\n"); return true; } diff --git a/src/main/java/course_project/service/Runner.java b/src/main/java/course_project/service/Runner.java index 85a9aeba..56e4e098 100644 --- a/src/main/java/course_project/service/Runner.java +++ b/src/main/java/course_project/service/Runner.java @@ -22,11 +22,21 @@ public void run() { PlayerService playerServiceTwo = new PlayerService(player2, playerTwoBattlefieldService); System.out.println("Enter name of the first player"); player1.setName(readIt.nextLine()); + System.out.println("Choose ship placement mode: auto or manual"); + if (readIt.nextLine().equalsIgnoreCase("auto")) { + playerOneBattlefieldService.autoShipPlacement(player1); + } else { + playerOneBattlefieldService.arrangement(player1, readIt); + } + System.out.println("Enter name of the second player"); player2.setName(readIt.nextLine()); - - playerOneBattlefieldService.arrangement(player1, readIt); - playerTwoBattlefieldService.arrangement(player2, readIt); + System.out.println("Choose ship placement mode: auto or manual"); + if (readIt.nextLine().equalsIgnoreCase("auto")) { + playerTwoBattlefieldService.autoShipPlacement(player2); + } else { + playerTwoBattlefieldService.arrangement(player2, readIt); + } int first = (int) (Math.random() * 2); if (first == 0) { @@ -56,5 +66,6 @@ public void run() { readIt.close(); } + } From fe7984884ca7f1afb67291ba40081698720f1948 Mon Sep 17 00:00:00 2001 From: arkadiy krylosov Date: Thu, 23 Sep 2021 15:33:01 +0300 Subject: [PATCH 63/63] course project fixed --- .../java/course_project/service/Runner.java | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/main/java/course_project/service/Runner.java b/src/main/java/course_project/service/Runner.java index 56e4e098..f349f40e 100644 --- a/src/main/java/course_project/service/Runner.java +++ b/src/main/java/course_project/service/Runner.java @@ -10,6 +10,8 @@ public class Runner { public void run() { Player a, b, c; boolean win; + boolean enteredFirst = false; + boolean enteredSecond = false; Scanner readIt = new Scanner(System.in); Player player1 = new Player(); @@ -22,20 +24,30 @@ public void run() { PlayerService playerServiceTwo = new PlayerService(player2, playerTwoBattlefieldService); System.out.println("Enter name of the first player"); player1.setName(readIt.nextLine()); - System.out.println("Choose ship placement mode: auto or manual"); - if (readIt.nextLine().equalsIgnoreCase("auto")) { - playerOneBattlefieldService.autoShipPlacement(player1); - } else { - playerOneBattlefieldService.arrangement(player1, readIt); + while (!enteredFirst) { + System.out.println("Choose ship placement mode: auto or manual"); + String modeFirst = readIt.nextLine(); + if (modeFirst.equalsIgnoreCase("auto")) { + playerOneBattlefieldService.autoShipPlacement(player1); + enteredFirst = true; + } else if (modeFirst.equalsIgnoreCase("manual")) { + playerOneBattlefieldService.arrangement(player1, readIt); + enteredFirst = true; + } } System.out.println("Enter name of the second player"); player2.setName(readIt.nextLine()); - System.out.println("Choose ship placement mode: auto or manual"); - if (readIt.nextLine().equalsIgnoreCase("auto")) { - playerTwoBattlefieldService.autoShipPlacement(player2); - } else { - playerTwoBattlefieldService.arrangement(player2, readIt); + while (!enteredSecond) { + System.out.println("Choose ship placement mode: auto or manual"); + String modeSecond = readIt.nextLine(); + if (modeSecond.equalsIgnoreCase("auto")) { + playerTwoBattlefieldService.autoShipPlacement(player2); + enteredSecond = true; + } else if (modeSecond.equalsIgnoreCase("manual")) { + playerTwoBattlefieldService.arrangement(player2, readIt); + enteredSecond = true; + } } int first = (int) (Math.random() * 2);