From 4a301c4017461fab40ede5f11152e841da58bc35 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Mon, 5 Jul 2021 19:46:48 +0300 Subject: [PATCH 01/32] Test commit --- src/main/java/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 9f28e436..79a1fa9b 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,7 +1,7 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello, World!"); + System.out.println("Hello, Russia!"); } } From e415e2951e92f50ae7ce99ba56e5bd5b7b5717d2 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Mon, 5 Jul 2021 20:07:49 +0300 Subject: [PATCH 02/32] Test commit 2 --- .gitignore | 5 ++++- src/main/java/Main.java | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 8a0a60d2..2b1fb1b8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ # Project exclude paths /.gradle/ /build/ -/build/classes/java/main/ \ No newline at end of file +/build/classes/java/main/ +/.idea/ +/gradle/ +/.DS_Store/ \ No newline at end of file diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 79a1fa9b..cb24da2b 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,7 +1,9 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello, Russia!"); + System.out.println("Hello, World!"); + + System.out.println("Hello World2!"); } } From a10dd3a21373e0965743dd642432dfb6abb95787 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Mon, 5 Jul 2021 23:53:09 +0300 Subject: [PATCH 03/32] Home work 1 --- .gitignore | 32 +++++++++++++++++++++++++++++- src/main/java/homework_1/Main.java | 13 ++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/main/java/homework_1/Main.java diff --git a/.gitignore b/.gitignore index 2b1fb1b8..14f3f265 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,34 @@ /build/classes/java/main/ /.idea/ /gradle/ -/.DS_Store/ \ No newline at end of file +/.DS_Store/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +#Ignore files +out +target +*.iml +.idea \ No newline at end of file diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java new file mode 100644 index 00000000..56de3156 --- /dev/null +++ b/src/main/java/homework_1/Main.java @@ -0,0 +1,13 @@ +package homework_1; + +public class Main { + public static void main(String[] args) { + for (String s : args) { + if(s.equals("ошибка")){ + System.err.println("Тревога!"); + break; + } + System.out.println(s + ": " + s.length()); + } + } +} From bfb5444d875e2a9e164854aa742db3764bbe57bb Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Wed, 7 Jul 2021 23:43:34 +0300 Subject: [PATCH 04/32] Added README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5d686e9f..b16e66b1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Asadulaev Gamzat* | 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/GamzatAsadulaev/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 ba3855b28d49fb90b32d0163834e8a860c7b37f2 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Thu, 15 Jul 2021 23:50:05 +0300 Subject: [PATCH 05/32] Homework 2 --- .../homework_2/homework2_1/TrafficLight.java | 74 ++++++++++++ .../homework2_2/PyramidPrinter.java | 28 +++++ .../homework2_3/RandomCharsTable.java | 110 ++++++++++++++++++ 3 files changed, 212 insertions(+) create mode 100644 src/main/java/homework_2/homework2_1/TrafficLight.java create mode 100644 src/main/java/homework_2/homework2_2/PyramidPrinter.java create mode 100644 src/main/java/homework_2/homework2_3/RandomCharsTable.java diff --git a/src/main/java/homework_2/homework2_1/TrafficLight.java b/src/main/java/homework_2/homework2_1/TrafficLight.java new file mode 100644 index 00000000..56339dd6 --- /dev/null +++ b/src/main/java/homework_2/homework2_1/TrafficLight.java @@ -0,0 +1,74 @@ +package homework_2.homework2_1; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; + + public static void main(String[] args) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + while(true) { + System.out.print("Choose the mode:\n1 - seconds\n2 - hh:mm:ss\n0 - exit\n-> "); + int mode = Integer.parseInt(reader.readLine()); + if (mode == 0) { + break; + } + int seconds = getSeconds(reader, mode); + + printColor(seconds); + } + } catch (IOException e) { + e.printStackTrace(); + } catch (NumberFormatException e){ + System.err.println("Entered invalid value!"); + } + catch (IllegalArgumentException e){ + System.err.println(e.getMessage()); + } + } + + private static int getSeconds(BufferedReader reader, int mode) throws IOException { + int seconds; + if (mode == 1) { + System.out.print("Enter time in seconds: "); + seconds = Integer.parseInt(reader.readLine()); + if (seconds < 0) { + throw new IllegalArgumentException("Only positive integers!"); + } else if (seconds >= 86400) { + throw new IllegalArgumentException("The day is over!"); + } + } else if(mode == 2) { + System.out.print("Enter time in the format(hh:mm:ss): "); + String[] arguments = reader.readLine().split(":"); + + int hh = Integer.parseInt(arguments[0]); + int mm = Integer.parseInt(arguments[1]); + int ss = Integer.parseInt(arguments[2]); + + if(hh < 0 || hh >= 24 || mm < 0 || mm >= 60 || ss < 0 || ss >= 60){ + throw new IllegalArgumentException("Entered time doesn't match the format!"); + } + seconds = hh * 3600 + mm * 60 + ss; + } else{ + throw new IllegalArgumentException("Invalid mode type!"); + } + return seconds; + } + + public static void printColor(int seconds) throws IllegalArgumentException { + seconds %= 60; + + if (seconds < 35) { + System.out.println(ANSI_GREEN + "Green" + ANSI_RESET); + } else if (seconds < 40 || seconds >= 55) { + System.out.println(ANSI_YELLOW + "Yellow" + ANSI_RESET); + } else { + System.out.println(ANSI_RED + "Red" + ANSI_RESET); + } + } +} diff --git a/src/main/java/homework_2/homework2_2/PyramidPrinter.java b/src/main/java/homework_2/homework2_2/PyramidPrinter.java new file mode 100644 index 00000000..5eb606bc --- /dev/null +++ b/src/main/java/homework_2/homework2_2/PyramidPrinter.java @@ -0,0 +1,28 @@ +package homework_2.homework2_2; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + public static void main(String[] args) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + int rows = Integer.parseInt(reader.readLine()); + printPyramid(rows); + } catch (IOException e) { + e.printStackTrace(); + } catch (NumberFormatException e){ + System.err.println("Only integer!"); + } + } + + public static void printPyramid(int rows){ + for (int i = 1; i <= rows; i++) { + for (int j = 0; j < i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } +} + diff --git a/src/main/java/homework_2/homework2_3/RandomCharsTable.java b/src/main/java/homework_2/homework2_3/RandomCharsTable.java new file mode 100644 index 00000000..84904c03 --- /dev/null +++ b/src/main/java/homework_2/homework2_3/RandomCharsTable.java @@ -0,0 +1,110 @@ +package homework_2.homework2_3; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class RandomCharsTable { + + + public static final Random random = new Random(); + + public static void main(String[] args) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.print("Enter the length, width and strategy(\"even\" or \"odd\")\n-> "); + String[] arr = reader.readLine().split(" "); + + int length = Integer.parseInt(arr[0]); + int width = Integer.parseInt(arr[1]); + String strategy = arr[2]; + + if (length < 1 || width < 1) { + throw new IllegalArgumentException("Entered value <= 0"); + } + char[][] randomLetters = getTableWithRandomLetters(length, width); + + printTable(randomLetters); + + printLetters(randomLetters, strategy); + + } catch (IOException e) { + e.printStackTrace(); + } catch (NumberFormatException e) { + System.err.println("Entered invalid arguments!"); + } + catch (IllegalArgumentException e) { + System.err.println(e.getMessage()); + } + } + + + public static char[][] getTableWithRandomLetters(int length, int width) { + char[][] randomLetters = new char[length][width]; + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + randomLetters[i][j] = getRandomLetter(); + } + } + return randomLetters; + } + + public static char getRandomLetter() { + int min = 65; + int max = 90; + int diff = max - min; + int randomInt = random.nextInt(diff + 1); + randomInt += min; + return (char) randomInt; + } + + public static List getEvenLetters(char[][] letters) { + List evenLetters = new ArrayList<>(); + for (char[] row : letters) { + for (char column : row) { + if ((int) column % 2 == 0) { + evenLetters.add(column); + } + } + } + return evenLetters; + } + + + public static List getOddLetters(char[][] letters) { + List oddLetters = new ArrayList<>(); + for (char[] row : letters) { + for (char column : row) { + if ((int) column % 2 != 0) { + oddLetters.add(column); + } + } + } + return oddLetters; + } + + public static void printLetters(char[][] letters, String strategy){ + if (strategy.equalsIgnoreCase("even")) { + System.out.println("Even letters - " + + getEvenLetters(letters).toString().replaceAll("[\\[\\]]", "")); + } else if (strategy.equalsIgnoreCase("odd")) { + System.out.println("Odd letters - " + + getOddLetters(letters).toString().replaceAll("[\\[\\]]", "")); + } else { + throw new IllegalArgumentException("Entered invalid mode for \"strategy\"!"); + } + } + + public static void printTable(char[][] letters) { + for (char[] row : letters) { + System.out.print("| "); + for (char column : row) { + System.out.print(column + " | "); + } + System.out.println(); + } + } + +} From 05f80cc0aa340f601d2162d1eadf940a73465efa Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 16 Jul 2021 12:37:44 +0300 Subject: [PATCH 06/32] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b16e66b1..c9c7e72b 100644 --- a/README.md +++ b/README.md @@ -5,5 +5,8 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/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/GamzatAsadulaev/src/main/java/homework_2/homework2_1) | The app that reads the time from the console (seconds/hh:mm:ss) and calculates the output color of the traffic light | +| | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/homework2_2) | The app that prints a pyramid based on user input | +| | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/homework2_3) | The app that reads length, width, strategy from the console generates the table and prints even/odd letters | -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 41cc0afc313db8aa3651b4df7b570e3b6a848446 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sun, 18 Jul 2021 22:30:04 +0300 Subject: [PATCH 07/32] Update Homework 2 --- .../homework2_2/PyramidPrinter.java | 2 +- .../homework2_3/RandomCharsTable.java | 23 ++++++++----------- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/main/java/homework_2/homework2_2/PyramidPrinter.java b/src/main/java/homework_2/homework2_2/PyramidPrinter.java index 5eb606bc..8eef55f3 100644 --- a/src/main/java/homework_2/homework2_2/PyramidPrinter.java +++ b/src/main/java/homework_2/homework2_2/PyramidPrinter.java @@ -16,7 +16,7 @@ public static void main(String[] args) { } } - public static void printPyramid(int rows){ + static void printPyramid(int rows){ for (int i = 1; i <= rows; i++) { for (int j = 0; j < i; j++) { System.out.print("x"); diff --git a/src/main/java/homework_2/homework2_3/RandomCharsTable.java b/src/main/java/homework_2/homework2_3/RandomCharsTable.java index 84904c03..935de37d 100644 --- a/src/main/java/homework_2/homework2_3/RandomCharsTable.java +++ b/src/main/java/homework_2/homework2_3/RandomCharsTable.java @@ -10,7 +10,7 @@ public class RandomCharsTable { - public static final Random random = new Random(); + static final Random random = new Random(); public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { @@ -41,7 +41,7 @@ public static void main(String[] args) { } - public static char[][] getTableWithRandomLetters(int length, int width) { + static char[][] getTableWithRandomLetters(int length, int width) { char[][] randomLetters = new char[length][width]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { @@ -51,16 +51,11 @@ public static char[][] getTableWithRandomLetters(int length, int width) { return randomLetters; } - public static char getRandomLetter() { - int min = 65; - int max = 90; - int diff = max - min; - int randomInt = random.nextInt(diff + 1); - randomInt += min; - return (char) randomInt; + static char getRandomLetter() { + return (char)(random.nextInt(90 - 65 + 1) + 65); } - public static List getEvenLetters(char[][] letters) { + static List getEvenLetters(char[][] letters) { List evenLetters = new ArrayList<>(); for (char[] row : letters) { for (char column : row) { @@ -73,11 +68,11 @@ public static List getEvenLetters(char[][] letters) { } - public static List getOddLetters(char[][] letters) { + static List getOddLetters(char[][] letters) { List oddLetters = new ArrayList<>(); for (char[] row : letters) { for (char column : row) { - if ((int) column % 2 != 0) { + if (column % 2 != 0) { oddLetters.add(column); } } @@ -85,7 +80,7 @@ public static List getOddLetters(char[][] letters) { return oddLetters; } - public static void printLetters(char[][] letters, String strategy){ + static void printLetters(char[][] letters, String strategy){ if (strategy.equalsIgnoreCase("even")) { System.out.println("Even letters - " + getEvenLetters(letters).toString().replaceAll("[\\[\\]]", "")); @@ -97,7 +92,7 @@ public static void printLetters(char[][] letters, String strategy){ } } - public static void printTable(char[][] letters) { + static void printTable(char[][] letters) { for (char[] row : letters) { System.out.print("| "); for (char column : row) { From abaa02f69f0061de3e5f1bc7b320e82eb731369d Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sat, 24 Jul 2021 05:04:25 +0300 Subject: [PATCH 08/32] Update TrafficLight --- .../homework_2/homework2_1/TrafficLight.java | 74 ------------------- .../traffic_light/ExtraTrafficLight.java | 53 +++++++++++++ .../java/homework_2/traffic_light/Main.java | 7 ++ .../homework_2/traffic_light/PrintColor.java | 31 ++++++++ .../traffic_light/TrafficLight.java | 26 +++++++ 5 files changed, 117 insertions(+), 74 deletions(-) delete mode 100644 src/main/java/homework_2/homework2_1/TrafficLight.java create mode 100644 src/main/java/homework_2/traffic_light/ExtraTrafficLight.java create mode 100644 src/main/java/homework_2/traffic_light/Main.java create mode 100644 src/main/java/homework_2/traffic_light/PrintColor.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLight.java diff --git a/src/main/java/homework_2/homework2_1/TrafficLight.java b/src/main/java/homework_2/homework2_1/TrafficLight.java deleted file mode 100644 index 56339dd6..00000000 --- a/src/main/java/homework_2/homework2_1/TrafficLight.java +++ /dev/null @@ -1,74 +0,0 @@ -package homework_2.homework2_1; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class TrafficLight { - public static final String ANSI_RESET = "\u001B[0m"; - public static final String ANSI_RED = "\u001B[31m"; - public static final String ANSI_GREEN = "\u001B[32m"; - public static final String ANSI_YELLOW = "\u001B[33m"; - - public static void main(String[] args) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { - while(true) { - System.out.print("Choose the mode:\n1 - seconds\n2 - hh:mm:ss\n0 - exit\n-> "); - int mode = Integer.parseInt(reader.readLine()); - if (mode == 0) { - break; - } - int seconds = getSeconds(reader, mode); - - printColor(seconds); - } - } catch (IOException e) { - e.printStackTrace(); - } catch (NumberFormatException e){ - System.err.println("Entered invalid value!"); - } - catch (IllegalArgumentException e){ - System.err.println(e.getMessage()); - } - } - - private static int getSeconds(BufferedReader reader, int mode) throws IOException { - int seconds; - if (mode == 1) { - System.out.print("Enter time in seconds: "); - seconds = Integer.parseInt(reader.readLine()); - if (seconds < 0) { - throw new IllegalArgumentException("Only positive integers!"); - } else if (seconds >= 86400) { - throw new IllegalArgumentException("The day is over!"); - } - } else if(mode == 2) { - System.out.print("Enter time in the format(hh:mm:ss): "); - String[] arguments = reader.readLine().split(":"); - - int hh = Integer.parseInt(arguments[0]); - int mm = Integer.parseInt(arguments[1]); - int ss = Integer.parseInt(arguments[2]); - - if(hh < 0 || hh >= 24 || mm < 0 || mm >= 60 || ss < 0 || ss >= 60){ - throw new IllegalArgumentException("Entered time doesn't match the format!"); - } - seconds = hh * 3600 + mm * 60 + ss; - } else{ - throw new IllegalArgumentException("Invalid mode type!"); - } - return seconds; - } - - public static void printColor(int seconds) throws IllegalArgumentException { - seconds %= 60; - - if (seconds < 35) { - System.out.println(ANSI_GREEN + "Green" + ANSI_RESET); - } else if (seconds < 40 || seconds >= 55) { - System.out.println(ANSI_YELLOW + "Yellow" + ANSI_RESET); - } else { - System.out.println(ANSI_RED + "Red" + ANSI_RESET); - } - } -} diff --git a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java new file mode 100644 index 00000000..aa3cefe1 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -0,0 +1,53 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ExtraTrafficLight { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run(int mode) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.print("Choose the mode:\n1 - seconds\n2 - hh:mm:ss\n-> "); +// int mode = Integer.parseInt(reader.readLine()); + int seconds = getSeconds(reader, mode); + + new PrintColor().print(seconds); + } catch (IOException e) { + e.printStackTrace(); + } catch (NumberFormatException e) { + System.out.println(ANSI_RED + "Only non-negative integers is allowed as passed parameter" + ANSI_RESET); + } catch (IllegalArgumentException e){ + System.out.println(ANSI_RED + e.getMessage() + ANSI_RESET); + + } + } + + private int getSeconds(BufferedReader reader, int mode) throws IOException { + int seconds; + if (mode == 1) { + System.out.print("Enter time in seconds: "); + seconds = Integer.parseInt(reader.readLine()); + + } else if (mode == 2) { + System.out.print("Enter time in the format(hh:mm:ss): "); + String[] arguments = reader.readLine().split(":"); + + int hh = Integer.parseInt(arguments[0]); + int mm = Integer.parseInt(arguments[1]); + int ss = Integer.parseInt(arguments[2]); + + if (hh < 0 || hh >= 24 || mm < 0 || mm >= 60 || ss < 0 || ss >= 60) { + throw new IllegalArgumentException("Entered time doesn't match the format!"); + } + + seconds = hh * 3600 + mm * 60 + ss; + } else { + throw new IllegalArgumentException("Invalid mode type!"); + } + return seconds; + } +} diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..fa033081 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,7 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args) { + new TrafficLight().run(); + } +} diff --git a/src/main/java/homework_2/traffic_light/PrintColor.java b/src/main/java/homework_2/traffic_light/PrintColor.java new file mode 100644 index 00000000..3636df12 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/PrintColor.java @@ -0,0 +1,31 @@ +package homework_2.traffic_light; + +public class PrintColor { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; + + void print(int seconds){ + + if (seconds < 0) { + throw new NumberFormatException(); + } + + if (seconds >= 86400) { + System.out.println(ANSI_RED + "The day is over!" + ANSI_RESET); + return; + } + + seconds %= 60; + + if (seconds < 35) { + System.out.println(ANSI_GREEN + "GREEN" + ANSI_RESET); + } else if (seconds < 40 || seconds >= 55) { + System.out.println(ANSI_YELLOW + "YELLOW" + ANSI_RESET); + } else { + System.out.println(ANSI_RED + "RED" + ANSI_RESET); + } + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..d3dfed48 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,26 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.print("Enter time in seconds: "); + int seconds = Integer.parseInt(reader.readLine()); + System.out.println(); + + new PrintColor().print(seconds); + + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter" + ANSI_RESET); + } + } +} From a3c38f4bbbded9eb26dc84aee1bbcfe8225ecac4 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sat, 24 Jul 2021 05:05:48 +0300 Subject: [PATCH 09/32] Update PyramidPrinter --- .../pyramid_printer/ExtraPyramidPrinter.java | 47 +++++++++++++++++++ .../java/homework_2/pyramid_printer/Main.java | 7 +++ .../PyramidPrinter.java | 17 +++++-- 3 files changed, 66 insertions(+), 5 deletions(-) create mode 100644 src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java create mode 100644 src/main/java/homework_2/pyramid_printer/Main.java rename src/main/java/homework_2/{homework2_2 => pyramid_printer}/PyramidPrinter.java (53%) diff --git a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java new file mode 100644 index 00000000..c355c318 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java @@ -0,0 +1,47 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ExtraPyramidPrinter { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run(String... args) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("Please input number"); + int rows = Integer.parseInt(reader.readLine()); + printPyramid(rows, args); + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter!" + ANSI_RESET); + + } + } + + void printPyramid(int rows, String[] args) { + if (rows < 0 || args.length == 0) { + System.out.println("arr + length " + args.length); + throw new IllegalArgumentException(); + } + + if (args[0].equalsIgnoreCase("invert")) { + for (int i = rows; i >= 1; --i) { + for (int j = 1; j <= i; ++j) { + System.out.print("x"); + } + System.out.println(); + } + } else { + for (int i = 1; i <= rows; i++) { + for (int j = 0; j < i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } + } +} diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..e50e37eb --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer; + +public class Main { + public static void main(String[] args) { + new PyramidPrinter().run(); + } +} diff --git a/src/main/java/homework_2/homework2_2/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java similarity index 53% rename from src/main/java/homework_2/homework2_2/PyramidPrinter.java rename to src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 8eef55f3..949bd1db 100644 --- a/src/main/java/homework_2/homework2_2/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -1,22 +1,29 @@ -package homework_2.homework2_2; +package homework_2.pyramid_printer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PyramidPrinter { - public static void main(String[] args) { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("Please input number"); int rows = Integer.parseInt(reader.readLine()); printPyramid(rows); } catch (IOException e) { e.printStackTrace(); - } catch (NumberFormatException e){ - System.err.println("Only integer!"); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter!" + ANSI_RESET); } } - static void printPyramid(int rows){ + void printPyramid(int rows) { + if(rows < 0){ + throw new IllegalArgumentException(); + } for (int i = 1; i <= rows; i++) { for (int j = 0; j < i; j++) { System.out.print("x"); From 1a4c1fe7fdf58140e6bea7100099848794ac63f2 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sat, 24 Jul 2021 05:07:13 +0300 Subject: [PATCH 10/32] Update RandomCharsTable --- .../homework2_3/RandomCharsTable.java | 105 ------------------ .../homework_2/random_chars_table/Main.java | 7 ++ .../random_chars_table/PrintChars.java | 54 +++++++++ .../random_chars_table/RandomCharsTable.java | 36 ++++++ .../RandomCharsTableCreator.java | 24 ++++ 5 files changed, 121 insertions(+), 105 deletions(-) delete mode 100644 src/main/java/homework_2/homework2_3/RandomCharsTable.java create mode 100644 src/main/java/homework_2/random_chars_table/Main.java create mode 100644 src/main/java/homework_2/random_chars_table/PrintChars.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTable.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java diff --git a/src/main/java/homework_2/homework2_3/RandomCharsTable.java b/src/main/java/homework_2/homework2_3/RandomCharsTable.java deleted file mode 100644 index 935de37d..00000000 --- a/src/main/java/homework_2/homework2_3/RandomCharsTable.java +++ /dev/null @@ -1,105 +0,0 @@ -package homework_2.homework2_3; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -public class RandomCharsTable { - - - static final Random random = new Random(); - - public static void main(String[] args) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { - System.out.print("Enter the length, width and strategy(\"even\" or \"odd\")\n-> "); - String[] arr = reader.readLine().split(" "); - - int length = Integer.parseInt(arr[0]); - int width = Integer.parseInt(arr[1]); - String strategy = arr[2]; - - if (length < 1 || width < 1) { - throw new IllegalArgumentException("Entered value <= 0"); - } - char[][] randomLetters = getTableWithRandomLetters(length, width); - - printTable(randomLetters); - - printLetters(randomLetters, strategy); - - } catch (IOException e) { - e.printStackTrace(); - } catch (NumberFormatException e) { - System.err.println("Entered invalid arguments!"); - } - catch (IllegalArgumentException e) { - System.err.println(e.getMessage()); - } - } - - - static char[][] getTableWithRandomLetters(int length, int width) { - char[][] randomLetters = new char[length][width]; - for (int i = 0; i < length; i++) { - for (int j = 0; j < width; j++) { - randomLetters[i][j] = getRandomLetter(); - } - } - return randomLetters; - } - - static char getRandomLetter() { - return (char)(random.nextInt(90 - 65 + 1) + 65); - } - - static List getEvenLetters(char[][] letters) { - List evenLetters = new ArrayList<>(); - for (char[] row : letters) { - for (char column : row) { - if ((int) column % 2 == 0) { - evenLetters.add(column); - } - } - } - return evenLetters; - } - - - static List getOddLetters(char[][] letters) { - List oddLetters = new ArrayList<>(); - for (char[] row : letters) { - for (char column : row) { - if (column % 2 != 0) { - oddLetters.add(column); - } - } - } - return oddLetters; - } - - static void printLetters(char[][] letters, String strategy){ - if (strategy.equalsIgnoreCase("even")) { - System.out.println("Even letters - " - + getEvenLetters(letters).toString().replaceAll("[\\[\\]]", "")); - } else if (strategy.equalsIgnoreCase("odd")) { - System.out.println("Odd letters - " - + getOddLetters(letters).toString().replaceAll("[\\[\\]]", "")); - } else { - throw new IllegalArgumentException("Entered invalid mode for \"strategy\"!"); - } - } - - static void printTable(char[][] letters) { - for (char[] row : letters) { - System.out.print("| "); - for (char column : row) { - System.out.print(column + " | "); - } - System.out.println(); - } - } - -} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..682fe366 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,7 @@ +package homework_2.random_chars_table; + +public class Main { + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/PrintChars.java b/src/main/java/homework_2/random_chars_table/PrintChars.java new file mode 100644 index 00000000..c634fa36 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/PrintChars.java @@ -0,0 +1,54 @@ +package homework_2.random_chars_table; + +import java.util.ArrayList; +import java.util.List; + +public class PrintChars { + + void print(char[][] table, String strategy) { + if (strategy.equalsIgnoreCase("even")) { + printEvenChars(table); + } else if (strategy.equalsIgnoreCase("odd")) { + printOddChars(table); + } else { + throw new IllegalArgumentException(); + } + } + + void print(char[][] chars) { + for (char[] row : chars) { + System.out.print("| "); + for (char column : row) { + System.out.print(column + " | "); + } + System.out.println(); + } + } + + void printEvenChars(char[][] table) { + List evenChars = new ArrayList<>(); + for (char[] row : table) { + for (char column : row) { + if (column % 2 == 0) { + evenChars.add(column); + } + } + System.out.println("Even letters - " + + evenChars.toString().replaceAll("[\\[\\]]", "")); + } + } + + void printOddChars(char[][] table) { + List evenChars = new ArrayList<>(); + for (char[] row : table) { + for (char column : row) { + if (column % 2 != 0) { + evenChars.add(column); + } + } + System.out.println("Even letters - " + + evenChars.toString().replaceAll("[\\[\\]]", "")); + } + } + +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..d5bf2466 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,36 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.print("Enter the length, width and strategy(\"even\" or \"odd\")\n-> "); + String[] arr = reader.readLine().split(" "); + + int length = Integer.parseInt(arr[0]); + int width = Integer.parseInt(arr[1]); + String strategy = arr[2]; + + char[][] table = new RandomCharsTableCreator().create(length, width); + + PrintChars printChars = new PrintChars(); + + printChars.print(table); + printChars.print(table, strategy); + + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]" + ANSI_RESET); + } + } + +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java new file mode 100644 index 00000000..3d42b8f9 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -0,0 +1,24 @@ +package homework_2.random_chars_table; + +import java.util.Random; + +public class RandomCharsTableCreator { + private final Random random = new Random(); + + char[][] create(int length, int width) { + if (length < 1 || width < 1) { + throw new IllegalArgumentException(); + } + char[][] randomChars = new char[length][width]; + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + randomChars[i][j] = getRandomChar(); + } + } + return randomChars; + } + + private char getRandomChar() { + return (char) (random.nextInt(90 - 65 + 1) + 65); + } +} From fe7492b923ad2932e44c1c477a7c263dc8907cbb Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sat, 24 Jul 2021 08:15:36 +0300 Subject: [PATCH 11/32] Add tests for Homework 2 --- build.gradle | 2 + .../ExtraPyramidPrinterTest.java | 114 +++++++++++++ .../pyramid_printer/PyramidPrinterTest.java | 90 ++++++++++ .../RandomCharsTableTest.java | 155 ++++++++++++++++++ .../traffic_light/ExtraTrafficLightTest.java | 126 ++++++++++++++ .../traffic_light/TrafficLightTest.java | 96 +++++++++++ 6 files changed, 583 insertions(+) create mode 100644 src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java create mode 100644 src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java create mode 100644 src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java create mode 100644 src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java create mode 100644 src/test/java/homework_2/traffic_light/TrafficLightTest.java diff --git a/build.gradle b/build.gradle index b91dc843..1c448dee 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,8 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testImplementation 'org.hamcrest:hamcrest:2.2' + testImplementation 'org.hamcrest:hamcrest-library:2.2' } test { diff --git a/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java new file mode 100644 index 00000000..ed322c9c --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java @@ -0,0 +1,114 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ExtraPyramidPrinterTest extends UnitBase { + + @Test + void given_1_whenRun_then_printPyramid() { + setInput("1"); + + new ExtraPyramidPrinter().run(""); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given_1_whenRun_then_printInvertPyramid() { + setInput("1"); + + new ExtraPyramidPrinter().run("invert"); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given_3_whenRun_then_printPyramid() { + setInput("3"); + + new ExtraPyramidPrinter().run(""); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + } + + @Test + void given_3_whenRun_then_printInvertPyramid() { + setInput("3"); + + new ExtraPyramidPrinter().run("invert"); + + removeFromOutput("Please input number"); + + assertEquals("xxx", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("x", getOutputLines()[2]); + } + + @Test + void given_0_whenRun_then_printNothing() { + setInput("0"); + + new ExtraPyramidPrinter().run(""); + + removeFromOutput("Please input number"); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void given_emptyArgument_whenRun_then_printErrorMessage() { + setInput(""); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_smth_whenRun_then_printErrorMessage() { + setInput("abc"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_floatingPointArgument_whenRun_then_printErrorMessage() { + setInput("0.5"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_tooBigNumber_whenRun_then_printErrorMessage() { + setInput("9999999999"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..1ded1901 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,90 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterTest extends UnitBase { + + @Test + void given_1_whenRun_then_printPyramid() { + setInput("1"); + + new PyramidPrinter().run(); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given_3_whenRun_then_printPyramid() { + setInput("3"); + + new PyramidPrinter().run(); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + } + + @Test + void given_0_whenRun_then_printNothing() { + setInput("0"); + + new PyramidPrinter().run(); + + removeFromOutput("Please input number"); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void given_emptyArgument_whenRun_then_printErrorMessage() { + setInput(""); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_smth_whenRun_then_printErrorMessage() { + setInput("abc"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_floatingPointArgument_whenRun_then_printErrorMessage() { + setInput("0.5"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_tooBigNumber_whenRun_then_printErrorMessage() { + setInput("9999999999"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..0c5ba87b --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,155 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RandomCharsTableTest extends UnitBase { + + + + // Hamcrest + @Test + void given_lengthWidth_whenRun_then_printChars() { + setInput("4 4 even"); + + new RandomCharsTable().run(); + removeFromOutput("Enter the length, width and strategy(\"even\" or \"odd\")\n-> "); + removeFromOutput("Even letters - "); + removeFromOutput(","); + removeFromOutput(" "); + removeFromOutput("|"); + + List strings = new ArrayList<>(Arrays.asList(getOutputLines())); + + assertThat(strings, everyItem(matchesPattern("[A-Z]+"))); + } + + + @Test + void given_negativeIntegerFirstArgument_whenRun_then_printErrorMessage() { + setInput("-2 2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_negativeIntegerSecondArgument_whenRun_then_printErrorMessage() { + setInput("2 -2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_smthStrategy_whenRun_then_printErrorMessage() { + setInput("2 2 abc"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_smthFirstArgument_whenRun_then_printErrorMessage() { + setInput("b 2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_smthSecondArgument_whenRun_then_printErrorMessage() { + setInput("2 b even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_floatingPointFirstArgument_whenRun_then_printErrorMessage() { + setInput("0.2 2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_floatingPointSecondArgument_whenRun_then_printErrorMessage() { + setInput("2 0.2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + + @Test + void given_moreThanThreeArguments_whenRun_then_printErrorMessage() { + setInput("4 4 4 odd"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_lengthWidthStrategy_whenRun_then_printEvenChars() { + setInput("4 4 even"); + + new RandomCharsTable().run(); + removeFromOutput("Even letters - "); + removeFromOutput(","); + removeFromOutput(" "); + + String str = getOutputLines()[getOutputLines().length - 1]; + + for (int i = 0; i < str.length(); i++) { + assertEquals(0, str.charAt(i) % 2); + } + } + + + @Test + void given_lengthWidthStrategy_whenRun_then_printOddChars() { + setInput("4 4 odd"); + + new RandomCharsTable().run(); + removeFromOutput("Even letters - "); + removeFromOutput(","); + removeFromOutput(" "); + + String str = getOutputLines()[getOutputLines().length - 1]; + + for (int i = 0; i < str.length(); i++) { + assertEquals(1, str.charAt(i) % 2); + } + } + + + + +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java new file mode 100644 index 00000000..d6f25558 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java @@ -0,0 +1,126 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ExtraTrafficLightTest extends UnitBase { + + @Test + void given_minSeconds_whenRun_then_printColor() { + setInput("0"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_maxSeconds_whenRun_then_printColor() { + setInput("86399"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_5_whenRun_then_printColor() { + setInput("5"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_35_whenRun_then_printColor() { + setInput("35"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_54_whenRun_then_printColor() { + setInput("54"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("RED")); + } + + + @Test + void given_86401_whenRun_then_printErrorMessage() { + setInput("86401"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("The day is over!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("Only non-negative integers is allowed as passed parameter")); + } + + @Test + void given_string_whenRun_then_printErrorMessage() { + setInput("abc"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("Only non-negative integers is allowed as passed parameter")); + } + + @Test + void given_minTime_whenRun_then_printColor() { + setInput("00:00:00"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_maxTime_whenRun_then_printColor() { + setInput("23:59:59"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_timeOutOfRange_whenRun_then_printErrorMessage() { + setInput("24:00:00"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("Entered time doesn't match the format!")); + } + + @Test + void given_negativeTime_whenRun_then_printErrorMessage() { + setInput("-23:00:00"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("Entered time doesn't match the format!")); + } + @Test + void given_timeWithStringArgument_whenRun_then_printErrorMessage() { + setInput("23:00:b"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("Only non-negative integers is allowed as passed parameter")); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java new file mode 100644 index 00000000..8d720097 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,96 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + + + +class TrafficLightTest extends UnitBase { + + @Test + void given_minSeconds_whenRun_then_printColor() { + setInput("0"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_maxSeconds_whenRun_then_printColor() { + setInput("86399"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_5_whenRun_then_printColor() { + setInput("5"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_35_whenRun_then_printColor() { + setInput("35"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_54_whenRun_then_printColor() { + setInput("54"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("RED")); + } + + + @Test + void given_86401_whenRun_then_printErrorMessage() { + setInput("86401"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("The day is over!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + + + @Test + void given_string_whenRun_then_printErrorMessage() { + setInput("abc"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + @Test + void given_severalArguments_whenRun_then_printErrorMessage() { + setInput("2 2"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + +} \ No newline at end of file From 33b884346f32ea6abe8d0a09c8d2d47630cccf13 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sat, 24 Jul 2021 08:17:34 +0300 Subject: [PATCH 12/32] Homework 3 --- src/main/java/homework_3/Book.java | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/homework_3/Book.java diff --git a/src/main/java/homework_3/Book.java b/src/main/java/homework_3/Book.java new file mode 100644 index 00000000..94d9e10b --- /dev/null +++ b/src/main/java/homework_3/Book.java @@ -0,0 +1,50 @@ +package homework_3; + +import java.util.*; + +public final class Book { + + private final String title; + private final int year; + private final String[] authors; + + public Book(String name, int age,String... authors) { + this.title = name; + this.year = age; + this.authors = authors; + } + + public Book(String name, String... authors) { + this.title = name; + this.year = 0; + this.authors = authors; + } + + public Book(String name, int age) { + this.title = name; + this.year = age; + this.authors = new String[0]; + } + + public Book() { + this.title = ""; + this.year = 0; + this.authors = new String[0]; + } + + public String getTitle() { + return this.title; + } + + public int getYear() { + return this.year; + } + + public List getAuthors() { + return Arrays.asList(authors); + } + + public Book changeTitle(String title) { + return new Book(title, year, authors); + } +} From 1600ec2a369b695a256d813ee8b4f200b3d38adf Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sat, 24 Jul 2021 08:17:47 +0300 Subject: [PATCH 13/32] add test for homework 3 --- src/test/java/homework_3/BookTest.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/test/java/homework_3/BookTest.java diff --git a/src/test/java/homework_3/BookTest.java b/src/test/java/homework_3/BookTest.java new file mode 100644 index 00000000..2c4bb771 --- /dev/null +++ b/src/test/java/homework_3/BookTest.java @@ -0,0 +1,21 @@ +package homework_3; + +import base.UnitBase; +import homework_2.traffic_light.TrafficLight; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class BookTest extends UnitBase { + @Test + void testImmutableClass() { + Book book1 = new Book("Test-Driven Java Development", 2015, " Viktor Farcic", + "Alex Garcia"); + Book book2 = book1.changeTitle("Test-Driven Java Development"); + assertNotEquals(book1, book2); + assertEquals("Test-Driven Java Development", book1.getTitle()); + assertEquals(book2.getTitle(), book1.getTitle()); + } + + +} \ No newline at end of file From 26bcf1022826769901d530266b55951ec4167d05 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sat, 24 Jul 2021 08:33:00 +0300 Subject: [PATCH 14/32] Update README --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c9c7e72b..319a9364 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,9 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/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/GamzatAsadulaev/src/main/java/homework_2/homework2_1) | The app that reads the time from the console (seconds/hh:mm:ss) and calculates the output color of the traffic light | -| | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/homework2_2) | The app that prints a pyramid based on user input | -| | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/homework2_3) | The app that reads length, width, strategy from the console generates the table and prints even/odd letters | +| HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/traffic_light) | The app that reads the time from the console (seconds/hh:mm:ss) and calculates the output color of the traffic light | +| | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/pyramid_printer) | The app that prints a pyramid based on user input | +| | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/random_chars_table) | The app that reads length, width, strategy from the console generates the table and prints even/odd letters | +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_3) | Immutable Class "Book" | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 3cadaf86f3419ca6111d3cf23c6a0308c7101e82 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sun, 15 Aug 2021 02:55:37 +0300 Subject: [PATCH 15/32] homework 4 --- .../custom_annotation/FilePath.java | 12 ++++ .../custom_file_reader/CustomFileReader.java | 65 +++++++++++++++++++ .../homework_4/custom_file_reader/Main.java | 11 ++++ .../java/homework_4/singleton/Singleton.java | 15 +++++ .../resources/custom_file_reader/file.txt | 1 + .../CustomAnnotationTest.java | 14 ++++ .../CustomFileReaderTest.java | 37 +++++++++++ .../homework_4/singleton/SingletonTest.java | 15 +++++ 8 files changed, 170 insertions(+) create mode 100644 src/main/java/homework_4/custom_annotation/FilePath.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/custom_file_reader/file.txt create mode 100644 src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java 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_annotation/FilePath.java b/src/main/java/homework_4/custom_annotation/FilePath.java new file mode 100644 index 00000000..c0d70ab1 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/FilePath.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface FilePath { + String path() default "src/main/resources/custom_file_reader/file.txt"; +} diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..2f4b5618 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,65 @@ +package homework_4.custom_file_reader; + +import homework_4.custom_annotation.FilePath; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Scanner; + +@FilePath +public class CustomFileReader { + private static final String FILE_PATH = CustomFileReader.class.getAnnotation(FilePath.class).path(); + + + public void run1() { + InputStream inputStream = CustomFileReader.class.getResourceAsStream("/custom_file_reader/file.txt"); + if (inputStream != null) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + String result = reader.readLine(); + printResult(result); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void run2() { + try (BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) { + String result = reader.readLine(); + printResult(result); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + public void run3() { + try (Scanner scanner = new Scanner(new File(FILE_PATH))) { + scanner.useDelimiter("[.,]"); + StringBuilder stringBuilder = new StringBuilder(); + while (scanner.hasNext()) { + stringBuilder.append(scanner.next()); + } + System.out.println(stringBuilder); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + //NIO + public void run4() { + Path path = Paths.get(FILE_PATH); + try (BufferedReader reader = Files.newBufferedReader(path)) { + String result = reader.readLine(); + printResult(result); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void printResult(String result) { + System.out.println(result.replaceAll("[.,]", "")); + } +} 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..17e8c99b --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,11 @@ +package homework_4.custom_file_reader; + +public class Main { + public static void main(String[] args) { + CustomFileReader customFileReader = new CustomFileReader(); + customFileReader.run1(); + customFileReader.run2(); + customFileReader.run3(); + customFileReader.run4(); + } +} 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..d95daa39 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +public class Singleton { + private static Singleton instance; + + private Singleton(){} + + + public static Singleton getInstance(){ + if(instance == null){ + instance = new Singleton(); + } + return instance; + } +} diff --git a/src/main/resources/custom_file_reader/file.txt b/src/main/resources/custom_file_reader/file.txt new file mode 100644 index 00000000..d2ff0b7d --- /dev/null +++ b/src/main/resources/custom_file_reader/file.txt @@ -0,0 +1 @@ +Hello,,,,, World......!, \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..5a98ce0c --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,14 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomAnnotationTest extends UnitBase { + @Test + void testAnnotation() { + assertEquals( "src/main/resources/custom_file_reader/file.txt", CustomFileReader.class.getAnnotation(FilePath.class).path()); + } +} 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..7289106f --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,37 @@ +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 { + CustomFileReader reader = new CustomFileReader(); + String expectedString = "Hello World!"; + + @Test + void testInputStreamReader() { + reader.run1(); + assertTrue(getOutput().contains(expectedString)); + } + + @Test + void testFileReader() { + reader.run2(); + assertTrue(getOutput().contains(expectedString)); + } + + @Test + void testScanner() { + reader.run3(); + assertTrue(getOutput().contains(expectedString)); + } + + @Test + void testNIO() { + reader.run4(); + assertTrue(getOutput().contains(expectedString)); + } + + +} \ 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..8f0b39d9 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SingletonTest extends UnitBase { + + @Test + void testSingleton() { + Singleton instance = Singleton.getInstance(); + assertEquals(instance, Singleton.getInstance()); + } +} \ No newline at end of file From ebb46c1e83da9f72567d1c37342d74f0e9a5dd64 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Sun, 15 Aug 2021 03:22:53 +0300 Subject: [PATCH 16/32] update README --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 319a9364..25e42db3 100644 --- a/README.md +++ b/README.md @@ -9,5 +9,10 @@ | | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/pyramid_printer) | The app that prints a pyramid based on user input | | | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/random_chars_table) | The app that reads length, width, strategy from the console generates the table and prints even/odd letters | | HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_3) | Immutable Class "Book" | +| HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/custom_file_reader) |The app that reads the file in different ways and prints the text without(, .) | +| | [CustomSingleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/singleton) | Custom Singleton | +| | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/custom_annotation) | Custom Annotation | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) + +[CodingBat](https://codingbat.com/done?user=asadulaevgamzat@gmail.com&tag=2887423202) \ No newline at end of file From a6e280364f851d189a877f1c3804d4dbcbb1af41 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 27 Aug 2021 14:53:23 +0300 Subject: [PATCH 17/32] homework 5 --- build.gradle | 1 + .../CustomRegexMatcher.java | 18 ++++++++++ .../homework_5/custom_regex_matcher/Main.java | 7 ++++ .../java/homework_5/power_of_number/Main.java | 7 ++++ .../power_of_number/PowerOfNumber.java | 34 +++++++++++++++++++ 5 files changed, 67 insertions(+) create mode 100644 src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java create mode 100644 src/main/java/homework_5/custom_regex_matcher/Main.java create mode 100644 src/main/java/homework_5/power_of_number/Main.java create mode 100644 src/main/java/homework_5/power_of_number/PowerOfNumber.java diff --git a/build.gradle b/build.gradle index 1c448dee..2bdb9b37 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.0' testImplementation 'org.hamcrest:hamcrest:2.2' testImplementation 'org.hamcrest:hamcrest-library:2.2' } 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..2fc64a41 --- /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 { + + public boolean isValidNumber(String number){ + return Pattern.compile("\\+?[7|8] ?[(-. ]?\\d{3}[)-. ]? ?\\d{3}[-. ]?\\d{2}[-. ]?\\d{2}").matcher(number).matches(); + } + + public void run() { + System.out.print("Enter a phone number: "); + Scanner scanner = new Scanner(System.in); + String number = scanner.nextLine(); + System.out.println("Entered the phone number is valid: " + (isValidNumber(number))); + } +} 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..f8b52c06 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + new 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..930f2040 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..edbd54de --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,34 @@ +package homework_5.power_of_number; + +import java.util.Scanner; + +public class PowerOfNumber { + + public int pow(int number, int pow) { + if(number < 0 || pow < 0){ + throw new IllegalArgumentException(); + } + if(pow == 0){ + return 1; + } + if(pow == 1) { + return number; + } + return number * pow(number, --pow); + } + + public void run() { + System.out.print("Enter two numbers(number, pow): "); + Scanner scanner = new Scanner(System.in); + try { + String str = scanner.nextLine(); + String[] split = str.split(",? "); + if (split.length != 2) { + throw new IllegalArgumentException(); + } + System.out.println("Result: " + pow(Integer.parseInt(split[0]), Integer.parseInt(split[1]))); + } catch (Exception e){ + System.out.println("Only 2 non-negative integers are allowed"); + } + } +} From 9798739d726b3ca3e8ea4e34244fe1f54f16b4b8 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 27 Aug 2021 14:54:14 +0300 Subject: [PATCH 18/32] add tests for homework 5 --- .../CustomRegexMatcherTest.java | 54 +++++++++++++++++ .../power_of_number/PowerOfNumberTest.java | 59 +++++++++++++++++++ 2 files changed, 113 insertions(+) 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/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..8d29e214 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,54 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CustomRegexMatcherTest extends UnitBase { + + @ParameterizedTest + @MethodSource("validPhoneNumbers") + void testPhoneNumbers(String number) { + setInput(number); + new CustomRegexMatcher().run(); + assertTrue(getOutput().contains("true")); + } + + @ParameterizedTest + @MethodSource("invalidPhoneNumbers") + void testInvalidPhoneNumbers(String number) { + setInput(number); + new CustomRegexMatcher().run(); + assertTrue(getOutput().contains("false")); + } + + private static Stream validPhoneNumbers() { + return Stream.of( + Arguments.of("79001234567"), + Arguments.of("89001234567"), + Arguments.of("8(900)1234567"), + Arguments.of("+7 (900) 123-45-67"), + Arguments.of("8 900 123 45 67"), + Arguments.of("8-900-123-45-67"), + Arguments.of("8.900.123.45.67") + ); + } + + private static Stream invalidPhoneNumbers() { + return Stream.of( + Arguments.of("7 9 0 0 1 2 3 4 5 6 7"), + Arguments.of("9001234567777"), + Arguments.of("7__9001234567"), + Arguments.of("6(900)1234567"), + Arguments.of("+7 (900) 123-45-67"), + Arguments.of("8 9005 123 45 67"), + Arguments.of("8-900-123-45-6"), + Arguments.of("900.123.45.67.31") + ); + } +} \ 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..69fd7637 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,59 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + + @Test + void given2_2_whenRun_then_print2ToThePowerOf2() { + setInput("2 2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("4")); + } + + + @Test + void given2_1_whenRun_then_print2ToThePowerOf1() { + setInput("2 1"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("2")); + } + + @Test + void given2_0_whenRun_then_print2ToThePowerOf0() { + setInput("2 0"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("1")); + } + + @Test + void given0_2_whenRun_then_print0ToThePowerOf2() { + setInput("0 2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("0")); + } + + @Test + void givenNegativeNumber_whenRun_then_printError() { + setInput("-2 2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } + + @Test + void givenNegativePow_whenRun_then_printError() { + setInput("2 -2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } + + @Test + void givenString_whenRun_then_printError() { + setInput("abc def"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } +} From a8e54e2a2fc5fd90d5afafd09ce9163f08d7d0f6 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 27 Aug 2021 15:09:43 +0300 Subject: [PATCH 19/32] fix homework 5 --- .../custom_regex_matcher/CustomRegexMatcher.java | 8 +++----- .../java/homework_5/power_of_number/PowerOfNumber.java | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java index 2fc64a41..a413e5a0 100644 --- a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -1,18 +1,16 @@ package homework_5.custom_regex_matcher; import java.util.Scanner; -import java.util.regex.Pattern; public class CustomRegexMatcher { - public boolean isValidNumber(String number){ - return Pattern.compile("\\+?[7|8] ?[(-. ]?\\d{3}[)-. ]? ?\\d{3}[-. ]?\\d{2}[-. ]?\\d{2}").matcher(number).matches(); + public boolean isValidPhoneNumber(String number){ + return number.matches("\\+?[7|8]\\s?[(-.\\s]?\\d{3}[)-.\\s]?\\s?\\d{3}[-.\\s]?\\d{2}[-.\\s]?\\d{2}"); } public void run() { System.out.print("Enter a phone number: "); Scanner scanner = new Scanner(System.in); - String number = scanner.nextLine(); - System.out.println("Entered the phone number is valid: " + (isValidNumber(number))); + System.out.println("Entered the phone number is valid: " + (isValidPhoneNumber(scanner.nextLine()))); } } diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java index edbd54de..6e3c32d6 100644 --- a/src/main/java/homework_5/power_of_number/PowerOfNumber.java +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -4,7 +4,7 @@ public class PowerOfNumber { - public int pow(int number, int pow) { + public int pow(int number, int pow) { if(number < 0 || pow < 0){ throw new IllegalArgumentException(); } From 0362a55e1aebb33bc339613b75f6777387a762d4 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 27 Aug 2021 15:37:41 +0300 Subject: [PATCH 20/32] add homework 5 to README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 25e42db3..ecca0268 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ | HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/custom_file_reader) |The app that reads the file in different ways and prints the text without(, .) | | | [CustomSingleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/singleton) | Custom Singleton | | | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/custom_annotation) | Custom Annotation | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/power_of_number) | The app that reads the number from the console and raises it to the power | +| | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/custom_regex_matcher) | The app that reads the number from the console and checks it for validity | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From bbcf76238c8afefa3653b0a7c49be09b88dbe8d0 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 3 Sep 2021 20:15:31 +0300 Subject: [PATCH 21/32] add lombok in dependencies --- build.gradle | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build.gradle b/build.gradle index 2bdb9b37..e63f1244 100644 --- a/build.gradle +++ b/build.gradle @@ -15,6 +15,9 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.0' testImplementation 'org.hamcrest:hamcrest:2.2' testImplementation 'org.hamcrest:hamcrest-library:2.2' + + compileOnly 'org.projectlombok:lombok:1.18.20' + annotationProcessor 'org.projectlombok:lombok:1.18.20' } test { From ab8c9854d9b61235c40bbee7ca01d41fd7ba9ce6 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 3 Sep 2021 20:16:06 +0300 Subject: [PATCH 22/32] add homework_6 --- .../MapProblemsGenerator.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java new file mode 100644 index 00000000..5cf43f74 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,39 @@ +package homework_6.map_problems_generator; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +import java.util.Objects; + +public class MapProblemsGenerator { + + @AllArgsConstructor + @Getter + @Setter + public static class MapProblemsCollisionGenerator { + private int id; + private String name; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsCollisionGenerator that = (MapProblemsCollisionGenerator) o; + return id == that.id && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return 1; + } + } + + @Data + @AllArgsConstructor + public static class MapProblemsMutableGenerator { + private int id; + private String name; + } +} From ebf65a5ae68c65f47964e8b353749e7a1f4c8e29 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 3 Sep 2021 20:20:29 +0300 Subject: [PATCH 23/32] add test for homework_6 --- .../MapProblemsGeneratorTest.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/test/java/homework_6/map_problems_generator/MapProblemsGeneratorTest.java diff --git a/src/test/java/homework_6/map_problems_generator/MapProblemsGeneratorTest.java b/src/test/java/homework_6/map_problems_generator/MapProblemsGeneratorTest.java new file mode 100644 index 00000000..efb15c93 --- /dev/null +++ b/src/test/java/homework_6/map_problems_generator/MapProblemsGeneratorTest.java @@ -0,0 +1,27 @@ +package homework_6.map_problems_generator; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; + +import static homework_6.map_problems_generator.MapProblemsGenerator.MapProblemsMutableGenerator; +import static org.junit.jupiter.api.Assertions.*; + +class MapProblemsGeneratorTest { + + @Test + void testMapProblemsMutableGenerator() { + MapProblemsMutableGenerator element = + new MapProblemsMutableGenerator(27, "Element 1"); + MapProblemsMutableGenerator sameElement = + new MapProblemsMutableGenerator(27, "Element 1"); + assertEquals(element, sameElement); + + HashMap map = new HashMap<>(); + map.put(element, element.getName()); + assertNotNull(map.get(element)); + + element.setId(30); + assertNull(map.get(element)); + } +} \ No newline at end of file From 7dc71ccd2d1bf23297b49cdedfd7c22f6746b120 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 3 Sep 2021 20:34:44 +0300 Subject: [PATCH 24/32] add homework 6 to README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ecca0268..bbfbd3de 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ | | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/custom_annotation) | Custom Annotation | | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/power_of_number) | The app that reads the number from the console and raises it to the power | | | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/custom_regex_matcher) | The app that reads the number from the console and checks it for validity | +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_6/map_problems_generator) | | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 72a80950cdf5e33b10e6fb095079af5b9e3b9f3b Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Mon, 20 Sep 2021 09:05:38 +0300 Subject: [PATCH 25/32] homework 7 --- .../java/homework_7/KittenToCatFunction.java | 10 ++++++++++ src/main/java/homework_7/Main.java | 17 +++++++++++++++++ src/main/java/homework_7/animals/Cat.java | 12 ++++++++++++ src/main/java/homework_7/animals/Kitten.java | 14 ++++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 src/main/java/homework_7/KittenToCatFunction.java create mode 100644 src/main/java/homework_7/Main.java create mode 100644 src/main/java/homework_7/animals/Cat.java create mode 100644 src/main/java/homework_7/animals/Kitten.java diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..8b455d92 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,10 @@ +package homework_7; + +import homework_7.animals.Cat; +import homework_7.animals.Kitten; + +@FunctionalInterface +public interface KittenToCatFunction { + + R grow(T t); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..6067b6f2 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,17 @@ +package homework_7; + +import homework_7.animals.Cat; +import homework_7.animals.Kitten; + +public class Main { + public static void main(String[] args) { + Kitten kitten = new Kitten("Simon", 1, 0.5); + System.out.println(kitten); + + KittenToCatFunction function = (k -> new Cat(k.getName(), + k.getAge() + 1, k.getWeight() * 3)); + + Cat cat = function.grow(kitten); + System.out.println(cat); + } +} diff --git a/src/main/java/homework_7/animals/Cat.java b/src/main/java/homework_7/animals/Cat.java new file mode 100644 index 00000000..0d97b9a9 --- /dev/null +++ b/src/main/java/homework_7/animals/Cat.java @@ -0,0 +1,12 @@ +package homework_7.animals; + + +import lombok.*; + +@Data +@AllArgsConstructor +public class Cat { + private String name; + private int age; + private double weight; +} diff --git a/src/main/java/homework_7/animals/Kitten.java b/src/main/java/homework_7/animals/Kitten.java new file mode 100644 index 00000000..dd56152d --- /dev/null +++ b/src/main/java/homework_7/animals/Kitten.java @@ -0,0 +1,14 @@ +package homework_7.animals; + + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class Kitten { + private String name; + private int age; + private double weight; + +} From dbeb65e1ee2b8db6a520f17fcee7d210d60f1cdd Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Mon, 20 Sep 2021 09:17:07 +0300 Subject: [PATCH 26/32] update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index bbfbd3de..3401ee87 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/power_of_number) | The app that reads the number from the console and raises it to the power | | | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/custom_regex_matcher) | The app that reads the number from the console and checks it for validity | | HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_6/map_problems_generator) | | +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_7) | Custom functional interface that transform Kitten to Cat | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From e70afe3336c2766e874942eb2d31a28556fb90c6 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Tue, 21 Sep 2021 18:16:56 +0300 Subject: [PATCH 27/32] course_project --- README.md | 1 + .../java/course_project/battleship/Main.java | 11 +++ .../battleship/controller/AIController.java | 17 ++++ .../controller/HumanController.java | 52 ++++++++++++ .../controller/PlayerController.java | 10 +++ .../course_project/battleship/game/Game.java | 73 +++++++++++++++++ .../battleship/game/GameMode.java | 21 +++++ .../battleship/game/GameRule.java | 21 +++++ .../battleship/model/Field.java | 29 +++++++ .../course_project/battleship/model/Ship.java | 46 +++++++++++ .../battleship/player/Computer.java | 22 +++++ .../battleship/player/Human.java | 69 ++++++++++++++++ .../battleship/player/Player.java | 47 +++++++++++ .../battleship/utils/Coordinate.java | 43 ++++++++++ .../battleship/utils/Display.java | 47 +++++++++++ .../battleship/utils/ManualShipPlacement.java | 44 ++++++++++ .../course_project/battleship/utils/Menu.java | 67 +++++++++++++++ .../battleship/utils/Position.java | 43 ++++++++++ .../battleship/utils/RandomShipPlacement.java | 36 +++++++++ .../battleship/utils/ShipPlacement.java | 9 +++ .../battleship/utils/Validator.java | 81 +++++++++++++++++++ .../battleship/player/HumanTest.java | 37 +++++++++ .../battleship/utils/ValidatorTest.java | 44 ++++++++++ 23 files changed, 870 insertions(+) create mode 100644 src/main/java/course_project/battleship/Main.java create mode 100644 src/main/java/course_project/battleship/controller/AIController.java create mode 100644 src/main/java/course_project/battleship/controller/HumanController.java create mode 100644 src/main/java/course_project/battleship/controller/PlayerController.java create mode 100644 src/main/java/course_project/battleship/game/Game.java create mode 100644 src/main/java/course_project/battleship/game/GameMode.java create mode 100644 src/main/java/course_project/battleship/game/GameRule.java create mode 100644 src/main/java/course_project/battleship/model/Field.java create mode 100644 src/main/java/course_project/battleship/model/Ship.java create mode 100644 src/main/java/course_project/battleship/player/Computer.java create mode 100644 src/main/java/course_project/battleship/player/Human.java create mode 100644 src/main/java/course_project/battleship/player/Player.java create mode 100644 src/main/java/course_project/battleship/utils/Coordinate.java create mode 100644 src/main/java/course_project/battleship/utils/Display.java create mode 100644 src/main/java/course_project/battleship/utils/ManualShipPlacement.java create mode 100644 src/main/java/course_project/battleship/utils/Menu.java create mode 100644 src/main/java/course_project/battleship/utils/Position.java create mode 100644 src/main/java/course_project/battleship/utils/RandomShipPlacement.java create mode 100644 src/main/java/course_project/battleship/utils/ShipPlacement.java create mode 100644 src/main/java/course_project/battleship/utils/Validator.java create mode 100644 src/test/java/course_project/battleship/player/HumanTest.java create mode 100644 src/test/java/course_project/battleship/utils/ValidatorTest.java diff --git a/README.md b/README.md index 3401ee87..df194332 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ | | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/custom_regex_matcher) | The app that reads the number from the console and checks it for validity | | HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_6/map_problems_generator) | | | HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_7) | Custom functional interface that transform Kitten to Cat | +| CP | [Battleship](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_7/course_project_battleship) | Course project "Battleship" | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/course_project/battleship/Main.java b/src/main/java/course_project/battleship/Main.java new file mode 100644 index 00000000..86385404 --- /dev/null +++ b/src/main/java/course_project/battleship/Main.java @@ -0,0 +1,11 @@ +package course_project.battleship; + + +import course_project.battleship.game.Game; + +public class Main { + + public static void main(String[] args) { + new Game().run(); + } +} diff --git a/src/main/java/course_project/battleship/controller/AIController.java b/src/main/java/course_project/battleship/controller/AIController.java new file mode 100644 index 00000000..285595a3 --- /dev/null +++ b/src/main/java/course_project/battleship/controller/AIController.java @@ -0,0 +1,17 @@ +package course_project.battleship.controller; + + +import course_project.battleship.player.Player; + +public class AIController implements PlayerController { + + @Override + public void placeShips(Player player) { + throw new UnsupportedOperationException(); + } + + @Override + public void makeTurns(Player player1, Player player2) { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/course_project/battleship/controller/HumanController.java b/src/main/java/course_project/battleship/controller/HumanController.java new file mode 100644 index 00000000..be50a347 --- /dev/null +++ b/src/main/java/course_project/battleship/controller/HumanController.java @@ -0,0 +1,52 @@ +package course_project.battleship.controller; + +import course_project.battleship.game.GameRule; +import course_project.battleship.player.Player; +import course_project.battleship.utils.*; + + +public class HumanController implements PlayerController { + + @Override + public void placeShips(Player player) { + System.out.println(player.getName() + " choose the ship placement mode:\n1.Manually\n2.Randomly"); + int setupMode = Menu.getInt(2); + if (setupMode == 1) { + new ManualShipPlacement().placeShips(player); + } else { + new RandomShipPlacement().placeShips(player); + } + + System.out.println("Ships are placed!\n"); + } + + public void makeTurns(Player player1, Player player2) { + System.out.println("Your field: "); + Display.drawField(player1.getBattlefield()); + + while (true) { + System.out.println(); + System.out.println("" + player1.getName() + ", please, make your turn."); + Display.drawField(player1.getMonitorField()); + + Coordinate coordinate = Menu.createCoordinate(); + + if (coordinate == null || !Validator.isValidCoordinate(coordinate)) { + continue; + } + + if (!player1.makeTurn(player2, + coordinate)) { + System.out.println("\nMiss! Your opponents turn!\n"); + break; + } + + if (GameRule.isWinCondition(player1)) { + break; + } +// display.clearConsole(); + } + } + + +} diff --git a/src/main/java/course_project/battleship/controller/PlayerController.java b/src/main/java/course_project/battleship/controller/PlayerController.java new file mode 100644 index 00000000..26f8257c --- /dev/null +++ b/src/main/java/course_project/battleship/controller/PlayerController.java @@ -0,0 +1,10 @@ +package course_project.battleship.controller; + +import course_project.battleship.player.Player; + +public interface PlayerController { + + void placeShips(Player player); + + void makeTurns(Player player1, Player player2); +} diff --git a/src/main/java/course_project/battleship/game/Game.java b/src/main/java/course_project/battleship/game/Game.java new file mode 100644 index 00000000..fe057ff1 --- /dev/null +++ b/src/main/java/course_project/battleship/game/Game.java @@ -0,0 +1,73 @@ +package course_project.battleship.game; + + +import course_project.battleship.controller.HumanController; +import course_project.battleship.controller.PlayerController; +import course_project.battleship.player.Human; +import course_project.battleship.player.Player; +import course_project.battleship.utils.Menu; + +import java.util.Scanner; + +public class Game { + private final GameMode gameMode = new GameMode(); + private static final Scanner scanner = new Scanner(System.in); + + public void run() { + System.out.println("----------SeaBattle---------"); + System.out.println("Choose Mode\n1. PvP\n2. PvE"); + + int mode = Menu.getInt(2); + if (mode == 1) { + gameMode.setMode(GameMode.Mode.PVP); + } else { + gameMode.setMode(GameMode.Mode.PVE); + } + startGame(); + } + + public void startGame() { + if (gameMode.getMode() == GameMode.Mode.PVP) { + playVsHuman(); + } else { + playVsComputer(); + } + } + + private void playVsHuman() { + System.out.println("Player 1, please, enter your name:"); + String playerName1 = scanner.nextLine(); + Player player1 = new Human(playerName1); + System.out.println("Player 2, please, enter your name:"); + String playerName2 = scanner.nextLine(); + Player player2 = new Human(playerName2); + + System.out.println("-----------------------------"); + + PlayerController playerController = new HumanController(); + playerController.placeShips(player1); + playerController.placeShips(player2); + + String winner; + + while (true) { + playerController.makeTurns(player1, player2); + if (GameRule.isWinCondition(player1)) { + winner = player1.getName(); + break; + } + playerController.makeTurns(player2, player1); + if (GameRule.isWinCondition(player2)) { + winner = player1.getName(); + break; + } + } + System.out.println(winner + " win this game!"); + } + + public void playVsComputer() { + throw new UnsupportedOperationException(); + } +} + + diff --git a/src/main/java/course_project/battleship/game/GameMode.java b/src/main/java/course_project/battleship/game/GameMode.java new file mode 100644 index 00000000..c2da32f7 --- /dev/null +++ b/src/main/java/course_project/battleship/game/GameMode.java @@ -0,0 +1,21 @@ +package course_project.battleship.game; + +public class GameMode { + private Mode mode; + + public GameMode() { + } + + public enum Mode { + PVP, + PVE + } + + public Mode getMode() { + return mode; + } + + public void setMode(Mode mode) { + this.mode = mode; + } +} diff --git a/src/main/java/course_project/battleship/game/GameRule.java b/src/main/java/course_project/battleship/game/GameRule.java new file mode 100644 index 00000000..42855c56 --- /dev/null +++ b/src/main/java/course_project/battleship/game/GameRule.java @@ -0,0 +1,21 @@ +package course_project.battleship.game; + + +import course_project.battleship.player.Player; +import course_project.battleship.utils.Position; + +public class GameRule { + private final static int WIN_STREAK = 20; + + public static boolean isWinCondition(Player player) { + int counter = 0; + for (int i = 0; i < player.getMonitorField().getField().length; i++) { + for (int j = 0; j < player.getMonitorField().getField().length; j++) { + if (player.getMonitorField().getField()[i][j].getState() == Position.State.HIT) { + counter++; + } + } + } + return counter >= WIN_STREAK; + } +} diff --git a/src/main/java/course_project/battleship/model/Field.java b/src/main/java/course_project/battleship/model/Field.java new file mode 100644 index 00000000..5bdc7cd4 --- /dev/null +++ b/src/main/java/course_project/battleship/model/Field.java @@ -0,0 +1,29 @@ +package course_project.battleship.model; + +import course_project.battleship.utils.Position; + +public class Field { + public static final int FILED_SIZE = 10; + private Position[][] field; + + public Field() { + this.field = new Position[FILED_SIZE][FILED_SIZE]; + initTable(); + } + + private void initTable() { + for (int i = 0; i < field.length; i++) { + for (int j = 0; j < field[i].length; j++) { + field[i][j] = new Position(); + } + } + } + + public Position[][] getField() { + return field; + } + + public void setField(Position[][] field) { + this.field = field; + } +} diff --git a/src/main/java/course_project/battleship/model/Ship.java b/src/main/java/course_project/battleship/model/Ship.java new file mode 100644 index 00000000..cae4efd4 --- /dev/null +++ b/src/main/java/course_project/battleship/model/Ship.java @@ -0,0 +1,46 @@ +package course_project.battleship.model; + +public class Ship { + private int deck; + private boolean isAlive; + + private int countHits = 1; + + public Ship(int deck) { + this.isAlive = true; + this.deck = deck; + } + + public boolean getDamage() { + if (countHits != deck) { + countHits++; + return true; + } + isAlive = false; + return false; + } + + public int getDeck() { + return deck; + } + + public void setDeck(int deck) { + this.deck = deck; + } + + public boolean isAlive() { + return isAlive; + } + + public void setAlive(boolean alive) { + isAlive = alive; + } + + public int getCountHits() { + return countHits; + } + + public void setCountHits(int countHits) { + this.countHits = countHits; + } +} diff --git a/src/main/java/course_project/battleship/player/Computer.java b/src/main/java/course_project/battleship/player/Computer.java new file mode 100644 index 00000000..ccfc5874 --- /dev/null +++ b/src/main/java/course_project/battleship/player/Computer.java @@ -0,0 +1,22 @@ +package course_project.battleship.player; + + +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; + +public class Computer extends Player { + + public Computer() { + super("Computer"); + } + + @Override + public boolean makeTurn(Player enemy, Coordinate coordinate) { + throw new UnsupportedOperationException(); + } + + @Override + public void placeShip(Coordinate coordinate, Ship ship, int direction) { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/course_project/battleship/player/Human.java b/src/main/java/course_project/battleship/player/Human.java new file mode 100644 index 00000000..fee5ef25 --- /dev/null +++ b/src/main/java/course_project/battleship/player/Human.java @@ -0,0 +1,69 @@ +package course_project.battleship.player; + +import course_project.battleship.model.Field; +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; +import course_project.battleship.utils.Position; + + +public class Human extends Player { + public Human(String name) { + super(name); + } + + public boolean makeTurn(Player enemy, Coordinate coordinate) { + if (enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()] + .getState() == Position.State.HIT || + this.getMonitorField().getField()[coordinate.getX()][coordinate.getY()] + .getState() == Position.State.MISS) { + System.out.println("\nYou have already hit this place!"); + return true; + } + if (enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()] + .getState() == Position.State.SHIP) { + + System.out.println("Hit!"); + + this.getMonitorField().getField()[coordinate.getX()][coordinate.getY()].setState(Position.State.HIT); + enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()].setState(Position.State.HIT); + + Ship ship = enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()].getShip(); + + if (!ship.getDamage()) { + System.out.println("\nThe " + ship.getDeck() + "-deck ship was destroyed!"); + } + + fillAroundHitPlace(coordinate, enemy.getBattlefield(), this.getMonitorField()); + } else { + this.getMonitorField().getField()[coordinate.getX()][coordinate.getY()] + .setState(Position.State.MISS); + return false; + } + return true; + } + + @Override + public void placeShip(Coordinate coordinate, Ship ship, int direction) { + for (int i = 0; i < ship.getDeck(); i++) { + if (direction == 1) { + getBattlefield().getField()[coordinate.getX()] + [coordinate.getY() + i].addShip(ship); + } else { + getBattlefield().getField()[coordinate.getX() + i][coordinate.getY()].addShip(ship); + } + } + } + + public void fillAroundHitPlace(Coordinate coordinate, Field battlefield, Field monitorField) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + int xi = Math.min(Math.max((coordinate.getX() + (j - 1)), 0), monitorField.getField().length - 1); + int yi = Math.min(Math.max((coordinate.getY() + (i - 1)), 0), monitorField.getField()[i].length - 1); + if (monitorField.getField()[xi][yi].getState() == Position.State.EMPTY && + battlefield.getField()[xi][yi].getState() == Position.State.EMPTY) { + monitorField.getField()[xi][yi].setState(Position.State.POINT); + } + } + } + } +} diff --git a/src/main/java/course_project/battleship/player/Player.java b/src/main/java/course_project/battleship/player/Player.java new file mode 100644 index 00000000..eaa5237a --- /dev/null +++ b/src/main/java/course_project/battleship/player/Player.java @@ -0,0 +1,47 @@ +package course_project.battleship.player; + + +import course_project.battleship.model.Field; +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; + +public abstract class Player { + private String name; + private Field battlefield; + private Field monitorField; + + + public Player(String name) { + this.name = name; + battlefield = new Field(); + monitorField = new Field(); + } + + public abstract boolean makeTurn(Player enemy, Coordinate coordinate); + + public abstract void placeShip(Coordinate coordinate, Ship ship, int direction); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Field getBattlefield() { + return battlefield; + } + + public void setBattlefield(Field battlefield) { + this.battlefield = battlefield; + } + + public Field getMonitorField() { + return monitorField; + } + + public void setMonitorField(Field monitorField) { + this.monitorField = monitorField; + } +} diff --git a/src/main/java/course_project/battleship/utils/Coordinate.java b/src/main/java/course_project/battleship/utils/Coordinate.java new file mode 100644 index 00000000..3359c776 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Coordinate.java @@ -0,0 +1,43 @@ +package course_project.battleship.utils; + + +import java.util.Objects; + +public class Coordinate { + private int x; + private int y; + + public Coordinate(int x, int y) { + this.x = x; + this.y = y; + } + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Coordinate that = (Coordinate) o; + return x == that.x && y == that.y; + } + + @Override + public int hashCode() { + return Objects.hash(x, y); + } +} diff --git a/src/main/java/course_project/battleship/utils/Display.java b/src/main/java/course_project/battleship/utils/Display.java new file mode 100644 index 00000000..6e01daf9 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Display.java @@ -0,0 +1,47 @@ +package course_project.battleship.utils; + + +import course_project.battleship.model.Field; + +import java.io.IOException; + +public final class Display { + + private static final String COLUMNS = " 1 2 3 4 5 6 7 8 9 10"; + + private Display(){} + + public static void drawField(Field field) { + System.out.println(COLUMNS); + for (int i = 0; i < field.getField().length; i++) { + System.out.print((char) (i + 65) + " "); + for (int j = 0; j < field.getField()[1].length; j++) { + if (field.getField()[j][i].getState() == Position.State.SHIP) { + System.out.print("+ "); + } else if (field.getField()[j][i].getState() == Position.State.HIT) { + System.out.print("X "); + } else if (field.getField()[j][i].getState() == Position.State.MISS) { + System.out.print("@ "); + } else if (field.getField()[j][i].getState() == Position.State.POINT) { + System.out.print("* "); + } else { + System.out.print("- "); + } + } + System.out.println(); + } + } + + public static void clearConsole() { + String os = System.getProperty("os.name").toLowerCase(); + try { + if (os.contains("win")) { + new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); + } else if (os.contains("nix") || os.contains("nux")) { + new ProcessBuilder("terminal", "/c", "clear").inheritIO().start().waitFor(); + } + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/course_project/battleship/utils/ManualShipPlacement.java b/src/main/java/course_project/battleship/utils/ManualShipPlacement.java new file mode 100644 index 00000000..e9a8b685 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/ManualShipPlacement.java @@ -0,0 +1,44 @@ +package course_project.battleship.utils; + +import course_project.battleship.model.Ship; +import course_project.battleship.player.Player; + +public class ManualShipPlacement implements ShipPlacement { + + @Override + public void placeShips(Player player) { + int deck = 4; + int counter = 1; + for (int i = 1; i <= 4; i++) { + while (counter <= i) { + System.out.println(player.getName() + ", place your " + deck + "-deck ship on the field:"); + Display.drawField(player.getBattlefield()); + + Coordinate coordinate = Menu.createCoordinate(); + if (coordinate == null || !Validator.isValidCoordinate(coordinate)) { + System.out.println("\nEntered Invalid coordinate!\n"); + continue; + } + + int direction = Menu.createDirection(); + if (!Validator.isValidDirection(direction)) { + System.out.println("\nEntered Invalid value for direction!\n"); + continue; + } + + if (!Validator.isAvailable(coordinate, deck, direction, player.getBattlefield())) { + System.out.println("Wrong coordinates or direction!"); + continue; + } + + Ship ship = new Ship(deck); + + player.placeShip(coordinate, ship, direction); + counter++; + } + deck--; + counter = 1; + } + } + +} diff --git a/src/main/java/course_project/battleship/utils/Menu.java b/src/main/java/course_project/battleship/utils/Menu.java new file mode 100644 index 00000000..1ad2de02 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Menu.java @@ -0,0 +1,67 @@ +package course_project.battleship.utils; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public final class Menu { + private static final Scanner scanner = new Scanner(System.in); + + private Menu() { + } + + public static Coordinate createCoordinate() { + System.out.println("Please, enter the number:"); + int x; + try { + x = scanner.nextInt() - 1; + } catch (InputMismatchException e) { + return null; + } finally { + scanner.nextLine(); + } + + System.out.println("Please, enter the char:"); + String str = scanner.nextLine().toUpperCase(); + if (str.length() != 1) { + return null; + } + + int y = (str.charAt(0)) - 65; + + return new Coordinate(x, y); + } + + + public static int createDirection() { + System.out.println("Choose direction: \n1. Vertical\n2. Horizontal"); + + int direction; + try { + direction = scanner.nextInt(); + } catch (InputMismatchException e) { + return -1; + } finally { + scanner.nextLine(); + } + + return direction; + } + + public static int getInt(int range) { + int number; + while (true) { + try { + number = scanner.nextInt(); + if (number > range || number < 1) { + throw new InputMismatchException(); + } + break; + } catch (InputMismatchException ignored) { + System.out.println("Entered invalid value!"); + } finally { + scanner.nextLine(); + } + } + return number; + } +} diff --git a/src/main/java/course_project/battleship/utils/Position.java b/src/main/java/course_project/battleship/utils/Position.java new file mode 100644 index 00000000..c4ccb8fa --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Position.java @@ -0,0 +1,43 @@ +package course_project.battleship.utils; + + +import course_project.battleship.model.Ship; + +public class Position { + private Ship ship; + private State state; + + public enum State { + EMPTY, + SHIP, + HIT, + MISS, + POINT + } + + public Position() { + state = State.EMPTY; + } + + public Position(Ship ship) { + this.ship = ship; + this.state = State.SHIP; + } + + public void addShip(Ship ship) { + this.ship = ship; + state = State.SHIP; + } + + public Ship getShip() { + return ship; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } +} diff --git a/src/main/java/course_project/battleship/utils/RandomShipPlacement.java b/src/main/java/course_project/battleship/utils/RandomShipPlacement.java new file mode 100644 index 00000000..2a1884c2 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/RandomShipPlacement.java @@ -0,0 +1,36 @@ +package course_project.battleship.utils; + +import course_project.battleship.model.Ship; +import course_project.battleship.player.Player; + +import java.util.Random; + +public class RandomShipPlacement implements ShipPlacement { + private final Random random = new Random(); + + @Override + public void placeShips(Player player) { + int deck = 4; + int counter = 1; + for (int i = 1; i <= 4; i++) { + while (counter <= i) { + int x = random.nextInt(10); + int y = random.nextInt(10); + Coordinate coordinate = new Coordinate(x, y); + + int direction = random.nextInt(2) + 1; + + if (!Validator.isAvailable(coordinate, deck, direction, player.getBattlefield())) { + continue; + } + + Ship ship = new Ship(deck); + player.placeShip(coordinate, ship, direction); + + counter++; + } + deck--; + counter = 1; + } + } +} diff --git a/src/main/java/course_project/battleship/utils/ShipPlacement.java b/src/main/java/course_project/battleship/utils/ShipPlacement.java new file mode 100644 index 00000000..ef2455ff --- /dev/null +++ b/src/main/java/course_project/battleship/utils/ShipPlacement.java @@ -0,0 +1,9 @@ +package course_project.battleship.utils; + +import course_project.battleship.player.Player; + +import java.util.Random; + +public interface ShipPlacement { + void placeShips(Player player); +} diff --git a/src/main/java/course_project/battleship/utils/Validator.java b/src/main/java/course_project/battleship/utils/Validator.java new file mode 100644 index 00000000..9fe2bfab --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Validator.java @@ -0,0 +1,81 @@ +package course_project.battleship.utils; + + +import course_project.battleship.model.Field; + +public final class Validator { + + private Validator(){} + + public static boolean isAvailable(Coordinate coordinate, int deck, int direction, Field battlefield) { + if (!isOutOfBound(coordinate, deck, direction, battlefield)) { + return false; + } + + if (battlefield.getField()[coordinate.getX()][coordinate.getY()].getState() == Position.State.SHIP) { + return false; + } + + if (!checkAroundTheShip(coordinate, direction, deck, battlefield)) { + return false; + } + + return true; + } + + public static boolean isValidDirection(int direction) { + return 2 >= direction && direction >= 1; + } + + public static boolean isOutOfBound(Coordinate coordinate, int deck, int direction, Field battlefield) { + if (direction == 1) { + if (coordinate.getY() + deck > battlefield.getField().length) { + return false; + } + } + if (direction == 2) { + if (coordinate.getX() + deck > battlefield.getField()[0].length) { + return false; + } + } + return true; + } + + public static boolean checkAroundTheShip(Coordinate coordinate, int direction, int deck, Field battlefield) { + for (int i = 0; i < deck; i++) { + if (direction == 1) { + if (!checkAroundTheCoordinate(coordinate.getX(), (coordinate.getY() + i), battlefield)) { + return false; + } + } else { + if (!checkAroundTheCoordinate((coordinate.getX() + i), coordinate.getY(), battlefield)) { + return false; + } + } + } + return true; + } + + + + public static boolean isValidCoordinate(Coordinate coordinate) { + if (coordinate.getX() < 0 || coordinate.getX() >= 10 || + coordinate.getY() < 0 || coordinate.getY() >= 10) { + return false; + } + return true; + } + + public static boolean checkAroundTheCoordinate(int x, int y, Field battlefield) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + int xi = Math.min(Math.max((x + (j - 1)), 0), battlefield.getField().length - 1); + int yi = Math.min(Math.max((y + (i - 1)), 0), battlefield.getField()[i].length - 1); + if (battlefield.getField()[xi][yi].getState() != Position.State.EMPTY) { + return false; + } + } + } + return true; + } +} diff --git a/src/test/java/course_project/battleship/player/HumanTest.java b/src/test/java/course_project/battleship/player/HumanTest.java new file mode 100644 index 00000000..c04d9749 --- /dev/null +++ b/src/test/java/course_project/battleship/player/HumanTest.java @@ -0,0 +1,37 @@ +package course_project.battleship.player; + +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; +import course_project.battleship.utils.Position; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class HumanTest { + + @Test + void testPlaceShipMethod() { + Human human = new Human("Test"); + Coordinate coordinate = new Coordinate(5, 5); + int direction = 2; + Ship ship = new Ship(4); + human.placeShip(coordinate, ship, direction); + assertNotNull(human.getBattlefield().getField()[coordinate.getX()][coordinate.getY()].getShip()); + } + + @Test + void testMakeTurnMethod() { + Human human = new Human("Test"); + Coordinate coordinate = new Coordinate(5, 5); + Human enemy = new Human("enemy"); + int direction = 2; + Ship ship = new Ship(4); + enemy.placeShip(coordinate, ship, direction); + human.makeTurn(enemy, coordinate); + assertEquals(Position.State.HIT, human.getMonitorField() + .getField()[coordinate.getX()][coordinate.getY()].getState()); + assertEquals(Position.State.HIT, enemy.getBattlefield() + .getField()[coordinate.getX()][coordinate.getY()].getState()); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship/utils/ValidatorTest.java b/src/test/java/course_project/battleship/utils/ValidatorTest.java new file mode 100644 index 00000000..156ae3b5 --- /dev/null +++ b/src/test/java/course_project/battleship/utils/ValidatorTest.java @@ -0,0 +1,44 @@ +package course_project.battleship.utils; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class ValidatorTest extends UnitBase { + + @ParameterizedTest + @MethodSource("invalidCoordinates") + void givenInvalidCoordinate_whenRun_thenCheckReturn(Coordinate coordinate) { + assertFalse(Validator.isValidCoordinate(coordinate)); + } + + @ParameterizedTest + @MethodSource("invalidDirections") + void givenInvalidCoordinate_whenRun_then_checkReturn(int direction) { + assertFalse(Validator.isValidDirection(direction)); + } + + private static Stream invalidCoordinates() { + return Stream.of( + arguments(new Coordinate(12, 5)), + arguments(new Coordinate(-5, 5)), + arguments(new Coordinate(5, 12)), + arguments(new Coordinate(5, -5)) + ); + } + + private static Stream invalidDirections() { + return Stream.of( + arguments(3), + arguments(-1) + ); + } + + +} \ No newline at end of file From 62cffc250c0218ebd371a5512efd9ac9088966e6 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Tue, 21 Sep 2021 21:12:55 +0300 Subject: [PATCH 28/32] fixed homework 3 --- src/main/java/homework_3/Book.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/homework_3/Book.java b/src/main/java/homework_3/Book.java index 94d9e10b..98b4a343 100644 --- a/src/main/java/homework_3/Book.java +++ b/src/main/java/homework_3/Book.java @@ -1,14 +1,12 @@ package homework_3; -import java.util.*; - public final class Book { private final String title; private final int year; private final String[] authors; - public Book(String name, int age,String... authors) { + public Book(String name, int age, String... authors) { this.title = name; this.year = age; this.authors = authors; @@ -40,8 +38,10 @@ public int getYear() { return this.year; } - public List getAuthors() { - return Arrays.asList(authors); + public String[] getAuthors() { + String[] copyAuthors = new String[this.authors.length]; + System.arraycopy(this.authors, 0, copyAuthors, 0, this.authors.length); + return copyAuthors; } public Book changeTitle(String title) { From 2f7a81e1f5c979cb58ac9f7ea9cae10f6c95607a Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Tue, 21 Sep 2021 21:12:55 +0300 Subject: [PATCH 29/32] fixed homework 3 --- src/main/java/homework_3/Book.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/homework_3/Book.java b/src/main/java/homework_3/Book.java index 94d9e10b..e8f33ac0 100644 --- a/src/main/java/homework_3/Book.java +++ b/src/main/java/homework_3/Book.java @@ -1,14 +1,12 @@ package homework_3; -import java.util.*; - public final class Book { private final String title; private final int year; private final String[] authors; - public Book(String name, int age,String... authors) { + public Book(String name, int age, String... authors) { this.title = name; this.year = age; this.authors = authors; @@ -17,7 +15,9 @@ public Book(String name, int age,String... authors) { public Book(String name, String... authors) { this.title = name; this.year = 0; - this.authors = authors; + String[] arrayCopy = new String[authors.length]; + System.arraycopy(authors, 0 , arrayCopy, 0, authors.length); + this.authors = arrayCopy; } public Book(String name, int age) { @@ -40,8 +40,10 @@ public int getYear() { return this.year; } - public List getAuthors() { - return Arrays.asList(authors); + public String[] getAuthors() { + String[] copyAuthors = new String[this.authors.length]; + System.arraycopy(this.authors, 0, copyAuthors, 0, this.authors.length); + return copyAuthors; } public Book changeTitle(String title) { From 9715ccde00c8f90eb8e6b996b5f9650d2ac559d3 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Wed, 22 Sep 2021 18:17:39 +0300 Subject: [PATCH 30/32] fixed homework3 --- src/main/java/homework_3/Book.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_3/Book.java b/src/main/java/homework_3/Book.java index e8f33ac0..1a078170 100644 --- a/src/main/java/homework_3/Book.java +++ b/src/main/java/homework_3/Book.java @@ -16,7 +16,7 @@ public Book(String name, String... authors) { this.title = name; this.year = 0; String[] arrayCopy = new String[authors.length]; - System.arraycopy(authors, 0 , arrayCopy, 0, authors.length); + System.arraycopy(authors, 0, arrayCopy, 0, authors.length); this.authors = arrayCopy; } From 8d55a6b4777cf6ed8de83278379a41a06aa29407 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Wed, 22 Sep 2021 21:39:48 +0300 Subject: [PATCH 31/32] fixed homework_3 --- src/main/java/homework_3/Book.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/homework_3/Book.java b/src/main/java/homework_3/Book.java index 1a078170..40c8316d 100644 --- a/src/main/java/homework_3/Book.java +++ b/src/main/java/homework_3/Book.java @@ -15,9 +15,9 @@ public Book(String name, int age, String... authors) { public Book(String name, String... authors) { this.title = name; this.year = 0; - String[] arrayCopy = new String[authors.length]; - System.arraycopy(authors, 0, arrayCopy, 0, authors.length); - this.authors = arrayCopy; + String[] copyAuthors = new String[authors.length]; + System.arraycopy(authors, 0, copyAuthors, 0, authors.length); + this.authors = copyAuthors; } public Book(String name, int age) { From 29d37c232e1880f0f09c70573c49bbd073fe06a7 Mon Sep 17 00:00:00 2001 From: Gamzat Asadulaev Date: Fri, 24 Sep 2021 00:09:09 +0300 Subject: [PATCH 32/32] fixed constructors and getter in homework 3 --- src/main/java/homework_3/Book.java | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/main/java/homework_3/Book.java b/src/main/java/homework_3/Book.java index 40c8316d..e904e021 100644 --- a/src/main/java/homework_3/Book.java +++ b/src/main/java/homework_3/Book.java @@ -1,5 +1,7 @@ package homework_3; +import java.util.Arrays; + public final class Book { private final String title; @@ -9,15 +11,13 @@ public final class Book { public Book(String name, int age, String... authors) { this.title = name; this.year = age; - this.authors = authors; + this.authors = Arrays.copyOf(authors, authors.length); } public Book(String name, String... authors) { this.title = name; this.year = 0; - String[] copyAuthors = new String[authors.length]; - System.arraycopy(authors, 0, copyAuthors, 0, authors.length); - this.authors = copyAuthors; + this.authors = Arrays.copyOf(authors, authors.length); } public Book(String name, int age) { @@ -41,12 +41,10 @@ public int getYear() { } public String[] getAuthors() { - String[] copyAuthors = new String[this.authors.length]; - System.arraycopy(this.authors, 0, copyAuthors, 0, this.authors.length); - return copyAuthors; + return Arrays.copyOf(authors, authors.length); } public Book changeTitle(String title) { - return new Book(title, year, authors); + return new Book(title, year, Arrays.copyOf(authors, authors.length)); } -} +} \ No newline at end of file