From c81cfc49b8e2f175871e9ad39e16eef6c1888a0e Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 5 Jul 2021 19:25:28 +0300 Subject: [PATCH 01/80] new branch --- 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 e3fb8015a889a00e3d4edcf8713c70d07e9287a1 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 5 Jul 2021 19:58:06 +0300 Subject: [PATCH 02/80] update gitignore --- .gitignore | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8a0a60d2..2cdc4005 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,33 @@ # Project exclude paths /.gradle/ /build/ -/build/classes/java/main/ \ No newline at end of file +/build/classes/java/main/ + +# Default ignored files +# Intellij +.idea/ +*.iml +*.iws + +# Eclipse +**/*.project +**/*.classpath +**/*.settings + +# Mac +.DS_Store + +# Package Files # +*.jar +*.war +*.ear +*.log + +out +target +build +.gradle +gradle +gradle* + +*.class \ No newline at end of file From f9b91e7707fe36f63a1b4a1901b30530179dcce4 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 5 Jul 2021 20:03:55 +0300 Subject: [PATCH 03/80] add readme --- README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..8c9f1a12 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# New Project \ No newline at end of file From d833a1f810b9b192f5a7bc696caadc40f7e44cf8 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 6 Jul 2021 17:00:04 +0300 Subject: [PATCH 04/80] add homework_1 --- src/main/java/homework_1/Homework.java | 38 ++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/homework_1/Homework.java diff --git a/src/main/java/homework_1/Homework.java b/src/main/java/homework_1/Homework.java new file mode 100644 index 00000000..6bac8161 --- /dev/null +++ b/src/main/java/homework_1/Homework.java @@ -0,0 +1,38 @@ +package homework_1; + +public class Homework { + private static final String WARNING_MESSAGE = "Тревога!"; + private static final String NOT_FOUND_MESSAGE = "Аргументы не найдены! Задайте аргументы при запуске программы!"; + private static final String INVALID_ARGUMENT = "ошибка"; + private static final String OUTPUT_PATTERN = "%s: %d %s\n"; + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println(NOT_FOUND_MESSAGE); + return; + } + for (String s : args) { + if (s.equals(INVALID_ARGUMENT)) { + System.err.println(WARNING_MESSAGE); + return; + } + System.out.printf(OUTPUT_PATTERN, s, s.length(), generateNumerator(s.length())); + } + } + + private static String generateNumerator(int wordLength) { + if (wordLength % 10 == 1 && wordLength != 11) { + return "буква"; + } + return getPlural(wordLength); + } + + private static String getPlural(int wordLength){ + if ((wordLength % 10 == 2 && wordLength != 12) || + (wordLength % 10 == 3 && wordLength != 13) || + (wordLength % 10 == 4 && wordLength != 14)) { + return "буквы"; + } + return "букв"; + } +} \ No newline at end of file From c542dbbd4b5d3ba42b822db4f0dae8e659bd5274 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 6 Jul 2021 17:39:08 +0300 Subject: [PATCH 05/80] add refactoring to English to homework_1 --- src/main/java/homework_1/Homework.java | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/src/main/java/homework_1/Homework.java b/src/main/java/homework_1/Homework.java index 6bac8161..7ea7cc85 100644 --- a/src/main/java/homework_1/Homework.java +++ b/src/main/java/homework_1/Homework.java @@ -1,9 +1,9 @@ package homework_1; public class Homework { - private static final String WARNING_MESSAGE = "Тревога!"; - private static final String NOT_FOUND_MESSAGE = "Аргументы не найдены! Задайте аргументы при запуске программы!"; - private static final String INVALID_ARGUMENT = "ошибка"; + private static final String WARNING_MESSAGE = "Alarm!"; + private static final String NOT_FOUND_MESSAGE = "Arguments have not been found! Please enter arguments when starting the program!"; + private static final String INVALID_ARGUMENT = "error"; private static final String OUTPUT_PATTERN = "%s: %d %s\n"; public static void main(String[] args) { @@ -21,18 +21,6 @@ public static void main(String[] args) { } private static String generateNumerator(int wordLength) { - if (wordLength % 10 == 1 && wordLength != 11) { - return "буква"; - } - return getPlural(wordLength); - } - - private static String getPlural(int wordLength){ - if ((wordLength % 10 == 2 && wordLength != 12) || - (wordLength % 10 == 3 && wordLength != 13) || - (wordLength % 10 == 4 && wordLength != 14)) { - return "буквы"; - } - return "букв"; + return wordLength == 1 ? "letter" : "letters"; } } \ No newline at end of file From fef0824beb55382da11810f1f1d299d542d730c6 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 7 Jul 2021 18:41:43 +0300 Subject: [PATCH 06/80] update readme, homework_1 --- README.md | 8 +++++++- src/main/java/Main.java | 7 ------- src/main/java/homework_1/{Homework.java => Main.java} | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) delete mode 100644 src/main/java/Main.java rename src/main/java/homework_1/{Homework.java => Main.java} (97%) diff --git a/README.md b/README.md index 8c9f1a12..7861d359 100644 --- a/README.md +++ b/README.md @@ -1 +1,7 @@ -# New Project \ No newline at end of file +# Java Core June 2021 + +## *Emelianchik Svetlana* + +| Number | Solution | Short description +| --- | --- | --- | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | \ No newline at end of file diff --git a/src/main/java/Main.java b/src/main/java/Main.java deleted file mode 100644 index 79a1fa9b..00000000 --- a/src/main/java/Main.java +++ /dev/null @@ -1,7 +0,0 @@ -public class Main { - - public static void main(String[] args) { - System.out.println("Hello, Russia!"); - } - -} diff --git a/src/main/java/homework_1/Homework.java b/src/main/java/homework_1/Main.java similarity index 97% rename from src/main/java/homework_1/Homework.java rename to src/main/java/homework_1/Main.java index 7ea7cc85..23f396bb 100644 --- a/src/main/java/homework_1/Homework.java +++ b/src/main/java/homework_1/Main.java @@ -1,6 +1,6 @@ package homework_1; -public class Homework { +public class Main { private static final String WARNING_MESSAGE = "Alarm!"; private static final String NOT_FOUND_MESSAGE = "Arguments have not been found! Please enter arguments when starting the program!"; private static final String INVALID_ARGUMENT = "error"; From 8377630db6ea73e72989ff50743788da9792e07b Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 12 Jul 2021 00:45:46 +0300 Subject: [PATCH 07/80] update gitignore --- .gitignore | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/.gitignore b/.gitignore index 2cdc4005..14f3f265 100644 --- a/.gitignore +++ b/.gitignore @@ -2,32 +2,36 @@ /.gradle/ /build/ /build/classes/java/main/ +/.idea/ +/gradle/ +/.DS_Store/ -# Default ignored files -# Intellij -.idea/ -*.iml -*.iws +# Compiled class file +*.class + +# Log file +*.log -# Eclipse -**/*.project -**/*.classpath -**/*.settings +# BlueJ files +*.ctxt -# Mac -.DS_Store +# Mobile Tools for Java (J2ME) +.mtj.tmp/ # Package Files # *.jar *.war +*.nar *.ear -*.log +*.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 -build -.gradle -gradle -gradle* - -*.class \ No newline at end of file +*.iml +.idea \ No newline at end of file From 9e2f25fab5159bfcdfcb095bd215ebd6441e8a74 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 12 Jul 2021 11:26:44 +0300 Subject: [PATCH 08/80] update homework_1 --- src/main/java/homework_1/Main.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 23f396bb..62700232 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -5,15 +5,16 @@ public class Main { private static final String NOT_FOUND_MESSAGE = "Arguments have not been found! Please enter arguments when starting the program!"; private static final String INVALID_ARGUMENT = "error"; private static final String OUTPUT_PATTERN = "%s: %d %s\n"; + public static final String ANSI_RED = "\u001B[31m"; public static void main(String[] args) { if (args.length < 1) { - System.err.println(NOT_FOUND_MESSAGE); + System.out.println(ANSI_RED + NOT_FOUND_MESSAGE + ANSI_RED); return; } for (String s : args) { if (s.equals(INVALID_ARGUMENT)) { - System.err.println(WARNING_MESSAGE); + System.out.println(ANSI_RED + WARNING_MESSAGE + ANSI_RED); return; } System.out.printf(OUTPUT_PATTERN, s, s.length(), generateNumerator(s.length())); From 133b5b549ff8aabff39bd1481adc6eb1ae984508 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 12 Jul 2021 11:38:56 +0300 Subject: [PATCH 09/80] Merge branch 'master' into feature/SvetlanaEmelianchik --- gradlew | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 gradlew diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 From ada747e33f435a0fab81c45bc1bd89b8693fe758 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 12 Jul 2021 14:25:37 +0300 Subject: [PATCH 10/80] update homework_1 --- src/main/java/homework_1/Main.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 62700232..b5b23ce7 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -9,12 +9,12 @@ public class Main { public static void main(String[] args) { if (args.length < 1) { - System.out.println(ANSI_RED + NOT_FOUND_MESSAGE + ANSI_RED); + System.out.println(ANSI_RED + NOT_FOUND_MESSAGE); return; } for (String s : args) { if (s.equals(INVALID_ARGUMENT)) { - System.out.println(ANSI_RED + WARNING_MESSAGE + ANSI_RED); + System.out.println(ANSI_RED + WARNING_MESSAGE); return; } System.out.printf(OUTPUT_PATTERN, s, s.length(), generateNumerator(s.length())); From 4e2980bc12a66435f29c87fd2214007b442b00d3 Mon Sep 17 00:00:00 2001 From: Artem Nikolaev Date: Mon, 12 Jul 2021 21:20:29 +0500 Subject: [PATCH 11/80] Update --- src/main/java/homework_1/Main.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/homework_1/Main.java diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java new file mode 100644 index 00000000..b5b23ce7 --- /dev/null +++ b/src/main/java/homework_1/Main.java @@ -0,0 +1,27 @@ +package homework_1; + +public class Main { + private static final String WARNING_MESSAGE = "Alarm!"; + private static final String NOT_FOUND_MESSAGE = "Arguments have not been found! Please enter arguments when starting the program!"; + private static final String INVALID_ARGUMENT = "error"; + private static final String OUTPUT_PATTERN = "%s: %d %s\n"; + public static final String ANSI_RED = "\u001B[31m"; + + public static void main(String[] args) { + if (args.length < 1) { + System.out.println(ANSI_RED + NOT_FOUND_MESSAGE); + return; + } + for (String s : args) { + if (s.equals(INVALID_ARGUMENT)) { + System.out.println(ANSI_RED + WARNING_MESSAGE); + return; + } + System.out.printf(OUTPUT_PATTERN, s, s.length(), generateNumerator(s.length())); + } + } + + private static String generateNumerator(int wordLength) { + return wordLength == 1 ? "letter" : "letters"; + } +} \ No newline at end of file From 9f16a902af9022a1af4da4efd7ca9e082896722c Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 12 Jul 2021 22:32:08 +0300 Subject: [PATCH 12/80] update homework_1 --- src/main/java/homework_1/Main.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index b5b23ce7..62700232 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -9,12 +9,12 @@ public class Main { public static void main(String[] args) { if (args.length < 1) { - System.out.println(ANSI_RED + NOT_FOUND_MESSAGE); + System.out.println(ANSI_RED + NOT_FOUND_MESSAGE + ANSI_RED); return; } for (String s : args) { if (s.equals(INVALID_ARGUMENT)) { - System.out.println(ANSI_RED + WARNING_MESSAGE); + System.out.println(ANSI_RED + WARNING_MESSAGE + ANSI_RED); return; } System.out.printf(OUTPUT_PATTERN, s, s.length(), generateNumerator(s.length())); From f3c09be114d9afc1625b5e2a59a102b39bbe5a91 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 13 Jul 2021 15:32:24 +0300 Subject: [PATCH 13/80] update homework_1 --- src/main/java/homework_1/Main.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 62700232..f706148f 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -6,15 +6,16 @@ public class Main { private static final String INVALID_ARGUMENT = "error"; private static final String OUTPUT_PATTERN = "%s: %d %s\n"; public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_RESET = "\u001B[0m"; public static void main(String[] args) { if (args.length < 1) { - System.out.println(ANSI_RED + NOT_FOUND_MESSAGE + ANSI_RED); + System.out.println(ANSI_RED + NOT_FOUND_MESSAGE + ANSI_RESET); return; } for (String s : args) { if (s.equals(INVALID_ARGUMENT)) { - System.out.println(ANSI_RED + WARNING_MESSAGE + ANSI_RED); + System.out.println(ANSI_RED + WARNING_MESSAGE + ANSI_RESET); return; } System.out.printf(OUTPUT_PATTERN, s, s.length(), generateNumerator(s.length())); From af2a08fcf76ab91a5f2e7e0d77d787d6ed5d09af Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 14 Jul 2021 20:15:53 +0300 Subject: [PATCH 14/80] add homework_2 --- .../pyramid_printer/PyramidPrinter.java | 55 ++++++++ .../random_chars_table/RandomCharsTable.java | 110 +++++++++++++++ .../traffic_light/TrafficLight.java | 129 ++++++++++++++++++ 3 files changed, 294 insertions(+) create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinter.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTable.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLight.java diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java new file mode 100644 index 00000000..5b118ad4 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,55 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static java.lang.System.lineSeparator; + +public class PyramidPrinter { + private static final String LETTER = "x"; + private static final String INFO_MESSAGE = "Please enter a positive integer for rows"; + private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; + + public static void main(String[] args) { + printPyramid(); + } + + private static void printPyramid() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + int rows = -1; + while (rows == -1) { + printMessage(INFO_MESSAGE); + String line = reader.readLine(); + rows = isValidNumber(line) ? Integer.parseInt(line) : -1; + } + generatePyramid(rows); + } catch (IOException e) { + printMessage(ERROR_MESSAGE); + } + } + + private static boolean isValidNumber(String number) { + try { + if (Integer.parseInt(number) < 1) { + return false; + } + } catch (NumberFormatException e) { + return false; + } + return true; + } + + private static void generatePyramid(int rows) { + for (int i = 1; i <= rows; i++) { + for (int j = 1; j <= i; j++) { + printMessage(LETTER); + } + printMessage(lineSeparator()); + } + } + + private static void printMessage(String text) { + System.out.print(text); + } +} \ No newline at end of file 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..bd0bac81 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,110 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import static java.lang.System.lineSeparator; + +public class RandomCharsTable { + private static final int MAX_CHAR = 90; + private static final int MIN_CHAR = 65; + private static final String INFO_MESSAGE_FOR_COLUMNS = "Enter a positive integer for columns: "; + private static final String INFO_MESSAGE_FOR_ROWS = "Enter a positive integer for rows: "; + private static final String INFO_MESSAGE_FOR_STRATEGY = "Enter the word \"odd\" or \"even\" without quotes for strategy: "; + private static final String INTEGER_ERROR_MESSAGE = "It was not a positive integer. Please try again: "; + private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; + private static final String STRATEGY_ERROR_MESSAGE = "It was not a word \"odd\" or \"even\"! Please try again: "; + + public static void main(String[] args) { + printCharsTable(); + } + + private static void printCharsTable() { + int columns = -1; + int rows = -1; + String strategy = ""; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + String line; + printMessage(INFO_MESSAGE_FOR_COLUMNS); + while (columns == -1) { + line = reader.readLine(); + columns = isValidNumber(line) ? Integer.parseInt(line) : -1; + } + printMessage(INFO_MESSAGE_FOR_ROWS); + while (rows == -1) { + line = reader.readLine(); + rows = isValidNumber(line) ? Integer.parseInt(line) : -1; + } + printMessage(INFO_MESSAGE_FOR_STRATEGY); + while (strategy.equals("")) { + line = reader.readLine(); + strategy = isOddOrEven(line) ? line : ""; + } + showCharsTable(columns, rows, strategy); + } catch (IOException e) { + printMessage(ERROR_MESSAGE); + } + } + + private static void showCharsTable(int columns, int rows, String strategy) { + Set charsByStrategySet = new HashSet<>(); + for (int i = 0; i < rows; i++) { + printMessage("|"); + for (int j = 0; j < columns; j++) { + char ch = getRandomChar(); + if (isCharFitsStrategy(ch, strategy)) { + charsByStrategySet.add(ch); + } + printMessage(ch + "|"); + } + printMessage(lineSeparator()); + } + printMessage(getFormattedStringForPrinting(strategy, charsByStrategySet)); + } + + private static char getRandomChar() { + return (char) ThreadLocalRandom.current().nextInt(MIN_CHAR, MAX_CHAR + 1); + } + + private static boolean isValidNumber(String number) { + try { + if (Integer.parseInt(number) < 1) { + printMessage(INTEGER_ERROR_MESSAGE); + return false; + } + } catch (NumberFormatException e) { + printMessage(INTEGER_ERROR_MESSAGE); + return false; + } + return true; + } + + private static boolean isOddOrEven(String line) { + if (line.toLowerCase().equals("odd") || line.toLowerCase().equals("even")) { + return true; + } + printMessage(STRATEGY_ERROR_MESSAGE); + return false; + } + + private static boolean isCharFitsStrategy(char ch, String strategy) { + return strategy.equals("even") == (ch % 2 == 0); + } + + private static String getFormattedStringForPrinting(String strategy, Set letters) { + String capFirst = strategy.substring(0, 1).toUpperCase() + strategy.substring(1); + StringBuilder result = new StringBuilder(capFirst + " letters - "); + for (Character ch : letters) { + result.append(ch).append(", "); + } + return result.substring(0, result.toString().trim().length() - 1); + } + + private static void printMessage(String text) { + System.out.print(text); + } +} \ No newline at end of file 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..2a4feffc --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,129 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static java.lang.System.lineSeparator; + +public class TrafficLight { + private static final String INFO_MESSAGE = "Hi! This is your guide to cross the road blindly!\n" + + "Please choose the format to enter the time:\n" + + "1 - time in format hh:mm:ss. From 00:00:00 to 23:59:59\n" + + "2 - time in seconds. From 0 to 86399."; + private static final String INFO_MESSAGE_TO_CHOOSE_MODE = "Please enter 1 or 2."; + private static final String INFO_MESSAGE_TO_MODE_1 = "Please enter time in format hh:mm:ss. From 00:00:00 to 23:59:59."; + private static final String INFO_MESSAGE_TO_MODE_2 = "Please enter time in seconds. From 0 to 86399."; + private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; + private static final String WARNING_MESSAGE_POSITIVE_NUMS = "You should enter only positive numbers or 0."; + private static final String WARNING_MESSAGE_INCORRECT_FORMAT = "You entered time in wrong format."; + private static final String WARNING_MESSAGE_EXCEED_LIMIT = "Please do not exceed the time limits. There are only 86399 seconds or 24 hours in a day!"; + private static final String LIGHT_RED = "\u001B[31m" + "RED" + "\u001B[0m" + "\nDo not cross the road!"; + private static final String LIGHT_GREEN = "\u001B[32m" + "GREEN" + "\u001B[0m" + "\nYou can cross the road!"; + private static final String LIGHT_YELLOW = "\u001B[33m" + "YELLOW" + "\u001B[0m" + "\nDo not cross the road, wait a little!"; + private static final int SECONDS_IN_DAY = 86399; + private static final int SECONDS_IN_HOUR = 3600; + private static final int SECONDS_IN_MINUTE = 60; + + public static void main(String[] args) { + crossRoad(); + } + + private static void crossRoad() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + printMessage(INFO_MESSAGE); + int mode = getMode(reader); + checkLight(mode, reader); + } catch (IOException e) { + printMessage(ERROR_MESSAGE); + } + } + + private static int getMode(BufferedReader reader) throws IOException { + while (true) { + String choice = reader.readLine(); + if (choice.equals("1") || choice.equals("2")) { + return Integer.parseInt(choice); + } + printMessage(INFO_MESSAGE_TO_CHOOSE_MODE); + } + } + + private static void checkLight(int mode, BufferedReader reader) throws IOException { + String line; + if (mode == 1) { + printMessage(INFO_MESSAGE_TO_MODE_1); + line = reader.readLine(); + if (isValidString(line)) { + printLight(parseToSeconds(line)); + } else { + checkLight(mode, reader); + } + } else { + printMessage(INFO_MESSAGE_TO_MODE_2); + line = reader.readLine(); + if (isValidSeconds(line)) { + printLight(Integer.parseInt(line)); + } else { + checkLight(mode, reader); + } + } + } + + private static boolean isValidString(String time) { + String[] timeArray = time.trim().split(":"); + if (timeArray.length != 3) { + printMessage(WARNING_MESSAGE_INCORRECT_FORMAT + lineSeparator()); + return false; + } else if (time.contains("-")) { + printMessage(WARNING_MESSAGE_POSITIVE_NUMS + lineSeparator()); + return false; + } + int hours = Integer.parseInt(timeArray[0]); + int minutes = Integer.parseInt(timeArray[1]); + int seconds = Integer.parseInt(timeArray[2]); + if (hours > 23 || minutes > 59 || seconds > 59) { + printMessage(WARNING_MESSAGE_EXCEED_LIMIT + lineSeparator()); + return false; + } + return true; + } + + private static boolean isValidSeconds(String time) { + int seconds; + try { + seconds = Integer.parseInt(time); + if (seconds < 1) { + printMessage(WARNING_MESSAGE_POSITIVE_NUMS + lineSeparator()); + return false; + } + } catch (NumberFormatException e) { + printMessage(WARNING_MESSAGE_INCORRECT_FORMAT + lineSeparator()); + return false; + } + return seconds <= SECONDS_IN_DAY; + } + + private static int parseToSeconds(String time) { + String[] timeArray = time.split(":"); + int hours = Integer.parseInt(timeArray[0]); + int minutes = Integer.parseInt(timeArray[1]); + int seconds = Integer.parseInt(timeArray[2]); + return hours * SECONDS_IN_HOUR + minutes * SECONDS_IN_MINUTE + seconds; + } + + private static void printLight(int seconds) { + int reminder = seconds % SECONDS_IN_MINUTE; + if (reminder >= 0 && reminder < 35) { + printMessage(LIGHT_GREEN); + } else if (reminder >= 35 && reminder < 40) { + printMessage(LIGHT_YELLOW); + } else { + printMessage(LIGHT_RED); + } + } + + private static void printMessage(String text) { + System.out.print(text); + } +} \ No newline at end of file From ab87918d1ad125f39ce4595fcfa59fee11acfb3a Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 14 Jul 2021 20:30:27 +0300 Subject: [PATCH 15/80] update readme with hw2 --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7861d359..8af5b89c 100644 --- a/README.md +++ b/README.md @@ -4,4 +4,7 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | \ No newline at end of file +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/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/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| +| HW2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | +| HW2 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | \ No newline at end of file From d1e07fd209cb1e1b37b931aa2e3bd88f7770e77a Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 19 Jul 2021 20:48:13 +0300 Subject: [PATCH 16/80] update hw2 with Main classes --- README.md | 4 +++- .../pyramid_printer/PyramidPrinter.java | 12 ++++------- .../random_chars_table/RandomCharsTable.java | 20 ++++++++----------- .../traffic_light/TrafficLight.java | 20 ++++++++----------- 4 files changed, 23 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 8af5b89c..1d5afe18 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,6 @@ | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/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/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| | HW2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | -| HW2 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | \ No newline at end of file +| HW2 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | + +[Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 5b118ad4..653e8a10 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -11,11 +11,7 @@ public class PyramidPrinter { private static final String INFO_MESSAGE = "Please enter a positive integer for rows"; private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; - public static void main(String[] args) { - printPyramid(); - } - - private static void printPyramid() { + public void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { int rows = -1; while (rows == -1) { @@ -29,7 +25,7 @@ private static void printPyramid() { } } - private static boolean isValidNumber(String number) { + private boolean isValidNumber(String number) { try { if (Integer.parseInt(number) < 1) { return false; @@ -40,7 +36,7 @@ private static boolean isValidNumber(String number) { return true; } - private static void generatePyramid(int rows) { + private void generatePyramid(int rows) { for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { printMessage(LETTER); @@ -49,7 +45,7 @@ private static void generatePyramid(int rows) { } } - private static void printMessage(String text) { + private void printMessage(String text) { System.out.print(text); } } \ No newline at end of file diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index bd0bac81..634bb9ea 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -19,11 +19,7 @@ public class RandomCharsTable { private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; private static final String STRATEGY_ERROR_MESSAGE = "It was not a word \"odd\" or \"even\"! Please try again: "; - public static void main(String[] args) { - printCharsTable(); - } - - private static void printCharsTable() { + public void run() { int columns = -1; int rows = -1; String strategy = ""; @@ -50,7 +46,7 @@ private static void printCharsTable() { } } - private static void showCharsTable(int columns, int rows, String strategy) { + private void showCharsTable(int columns, int rows, String strategy) { Set charsByStrategySet = new HashSet<>(); for (int i = 0; i < rows; i++) { printMessage("|"); @@ -66,11 +62,11 @@ private static void showCharsTable(int columns, int rows, String strategy) { printMessage(getFormattedStringForPrinting(strategy, charsByStrategySet)); } - private static char getRandomChar() { + private char getRandomChar() { return (char) ThreadLocalRandom.current().nextInt(MIN_CHAR, MAX_CHAR + 1); } - private static boolean isValidNumber(String number) { + private boolean isValidNumber(String number) { try { if (Integer.parseInt(number) < 1) { printMessage(INTEGER_ERROR_MESSAGE); @@ -83,7 +79,7 @@ private static boolean isValidNumber(String number) { return true; } - private static boolean isOddOrEven(String line) { + private boolean isOddOrEven(String line) { if (line.toLowerCase().equals("odd") || line.toLowerCase().equals("even")) { return true; } @@ -91,11 +87,11 @@ private static boolean isOddOrEven(String line) { return false; } - private static boolean isCharFitsStrategy(char ch, String strategy) { + private boolean isCharFitsStrategy(char ch, String strategy) { return strategy.equals("even") == (ch % 2 == 0); } - private static String getFormattedStringForPrinting(String strategy, Set letters) { + private String getFormattedStringForPrinting(String strategy, Set letters) { String capFirst = strategy.substring(0, 1).toUpperCase() + strategy.substring(1); StringBuilder result = new StringBuilder(capFirst + " letters - "); for (Character ch : letters) { @@ -104,7 +100,7 @@ private static String getFormattedStringForPrinting(String strategy, Set= 0 && reminder < 35) { printMessage(LIGHT_GREEN); @@ -123,7 +119,7 @@ private static void printLight(int seconds) { } } - private static void printMessage(String text) { + private void printMessage(String text) { System.out.print(text); } } \ No newline at end of file From 63db4023f0a072b02c4d0937b19cd2baad1a2894 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 19 Jul 2021 21:22:17 +0300 Subject: [PATCH 17/80] update hw2 with Main classes --- src/main/java/homework_2/pyramid_printer/Main.java | 7 +++++++ src/main/java/homework_2/random_chars_table/Main.java | 7 +++++++ src/main/java/homework_2/traffic_light/Main.java | 7 +++++++ 3 files changed, 21 insertions(+) create mode 100644 src/main/java/homework_2/pyramid_printer/Main.java create mode 100644 src/main/java/homework_2/random_chars_table/Main.java create mode 100644 src/main/java/homework_2/traffic_light/Main.java diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..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/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/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(); + } +} From 4a79147b99b06cc2ed773424f4b103d07d46f32b Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 21 Jul 2021 16:26:59 +0300 Subject: [PATCH 18/80] refactor homework_2 --- .../java/homework_2/pyramid_printer/Main.java | 2 +- .../pyramid_printer/MessageType.java | 17 +++ .../pyramid_printer/PyramidPrinter.java | 37 +++-- .../PyramidPrinterException.java | 7 + .../homework_2/pyramid_printer/Utils.java | 7 + .../homework_2/random_chars_table/Main.java | 2 +- .../random_chars_table/MessageType.java | 20 +++ .../random_chars_table/RandomCharsTable.java | 70 ++++------ .../RandomCharsTableException.java | 7 + .../homework_2/random_chars_table/Utils.java | 7 + .../java/homework_2/traffic_light/Main.java | 5 +- .../homework_2/traffic_light/MessageType.java | 25 ++++ .../traffic_light/TrafficLight.java | 132 ++++++------------ .../traffic_light/TrafficLightException.java | 7 + .../java/homework_2/traffic_light/Utils.java | 24 ++++ 15 files changed, 217 insertions(+), 152 deletions(-) create mode 100644 src/main/java/homework_2/pyramid_printer/MessageType.java create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinterException.java create mode 100644 src/main/java/homework_2/pyramid_printer/Utils.java create mode 100644 src/main/java/homework_2/random_chars_table/MessageType.java create mode 100644 src/main/java/homework_2/random_chars_table/RandomCharsTableException.java create mode 100644 src/main/java/homework_2/random_chars_table/Utils.java create mode 100644 src/main/java/homework_2/traffic_light/MessageType.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightException.java create mode 100644 src/main/java/homework_2/traffic_light/Utils.java diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index e50e37eb..641e9bdc 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - new PyramidPrinter().run(); + new PyramidPrinter().start(); } } diff --git a/src/main/java/homework_2/pyramid_printer/MessageType.java b/src/main/java/homework_2/pyramid_printer/MessageType.java new file mode 100644 index 00000000..e273129d --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/MessageType.java @@ -0,0 +1,17 @@ +package homework_2.pyramid_printer; + +public enum MessageType { + INFO_MESSAGE("Please enter a positive integer for rows"), + ERROR_MESSAGE("Something went wrong. Please restart the program!"), + ERROR_WRONG_FORMAT_MESSAGE("Only positive integers are allowed."); + + private final String message; + + MessageType(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 653e8a10..e4c8219f 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -4,36 +4,39 @@ import java.io.IOException; import java.io.InputStreamReader; +import static homework_2.pyramid_printer.MessageType.ERROR_MESSAGE; +import static homework_2.pyramid_printer.MessageType.ERROR_WRONG_FORMAT_MESSAGE; +import static homework_2.pyramid_printer.MessageType.INFO_MESSAGE; +import static homework_2.pyramid_printer.Utils.printMessage; import static java.lang.System.lineSeparator; public class PyramidPrinter { private static final String LETTER = "x"; - private static final String INFO_MESSAGE = "Please enter a positive integer for rows"; - private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; - public void run() { + public void start() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { - int rows = -1; - while (rows == -1) { - printMessage(INFO_MESSAGE); - String line = reader.readLine(); - rows = isValidNumber(line) ? Integer.parseInt(line) : -1; - } + printMessage(INFO_MESSAGE.getMessage()); + String line = reader.readLine(); + int rows = getNumber(line); generatePyramid(rows); } catch (IOException e) { - printMessage(ERROR_MESSAGE); + printMessage(ERROR_MESSAGE.getMessage()); + } catch (PyramidPrinterException e) { + printMessage(e.getMessage()); } } - private boolean isValidNumber(String number) { + private int getNumber(String text) throws PyramidPrinterException { + int number; try { - if (Integer.parseInt(number) < 1) { - return false; + number = Integer.parseInt(text); + if (number < 1) { + throw new PyramidPrinterException(ERROR_WRONG_FORMAT_MESSAGE); } } catch (NumberFormatException e) { - return false; + throw new PyramidPrinterException(ERROR_WRONG_FORMAT_MESSAGE); } - return true; + return number; } private void generatePyramid(int rows) { @@ -44,8 +47,4 @@ private void generatePyramid(int rows) { printMessage(lineSeparator()); } } - - private void printMessage(String text) { - System.out.print(text); - } } \ No newline at end of file diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinterException.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinterException.java new file mode 100644 index 00000000..17fdb62d --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinterException.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer; + +public class PyramidPrinterException extends Throwable { + public PyramidPrinterException(MessageType e) { + super(e.getMessage()); + } +} diff --git a/src/main/java/homework_2/pyramid_printer/Utils.java b/src/main/java/homework_2/pyramid_printer/Utils.java new file mode 100644 index 00000000..ded2bbef --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Utils.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer; + +public class Utils { + public static void printMessage(String text) { + System.out.print(text); + } +} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java index 682fe366..6bc4bee1 100644 --- a/src/main/java/homework_2/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - new RandomCharsTable().run(); + new RandomCharsTable().start(); } } diff --git a/src/main/java/homework_2/random_chars_table/MessageType.java b/src/main/java/homework_2/random_chars_table/MessageType.java new file mode 100644 index 00000000..c138d1cc --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/MessageType.java @@ -0,0 +1,20 @@ +package homework_2.random_chars_table; + +public enum MessageType { + INFO_MESSAGE_FOR_COLUMNS("Enter a positive integer for columns: "), + INFO_MESSAGE_FOR_ROWS("Enter a positive integer for rows: "), + INFO_MESSAGE_FOR_STRATEGY("Enter the word \"odd\" or \"even\" without quotes for strategy: "), + INTEGER_ERROR_MESSAGE("It was not a positive integer."), + ERROR_MESSAGE("Something went wrong. Please restart the program!"), + STRATEGY_ERROR_MESSAGE("It was not a word \"odd\" or \"even\"."); + + private final String message; + + MessageType(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 634bb9ea..c429518d 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -7,42 +7,32 @@ import java.util.Set; import java.util.concurrent.ThreadLocalRandom; +import static homework_2.random_chars_table.MessageType.ERROR_MESSAGE; +import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_COLUMNS; +import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_ROWS; +import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_STRATEGY; +import static homework_2.random_chars_table.MessageType.INTEGER_ERROR_MESSAGE; +import static homework_2.random_chars_table.MessageType.STRATEGY_ERROR_MESSAGE; +import static homework_2.random_chars_table.Utils.printMessage; import static java.lang.System.lineSeparator; public class RandomCharsTable { private static final int MAX_CHAR = 90; private static final int MIN_CHAR = 65; - private static final String INFO_MESSAGE_FOR_COLUMNS = "Enter a positive integer for columns: "; - private static final String INFO_MESSAGE_FOR_ROWS = "Enter a positive integer for rows: "; - private static final String INFO_MESSAGE_FOR_STRATEGY = "Enter the word \"odd\" or \"even\" without quotes for strategy: "; - private static final String INTEGER_ERROR_MESSAGE = "It was not a positive integer. Please try again: "; - private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; - private static final String STRATEGY_ERROR_MESSAGE = "It was not a word \"odd\" or \"even\"! Please try again: "; - public void run() { - int columns = -1; - int rows = -1; - String strategy = ""; + public void start() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { - String line; - printMessage(INFO_MESSAGE_FOR_COLUMNS); - while (columns == -1) { - line = reader.readLine(); - columns = isValidNumber(line) ? Integer.parseInt(line) : -1; - } - printMessage(INFO_MESSAGE_FOR_ROWS); - while (rows == -1) { - line = reader.readLine(); - rows = isValidNumber(line) ? Integer.parseInt(line) : -1; - } - printMessage(INFO_MESSAGE_FOR_STRATEGY); - while (strategy.equals("")) { - line = reader.readLine(); - strategy = isOddOrEven(line) ? line : ""; - } + printMessage(INFO_MESSAGE_FOR_COLUMNS.getMessage()); + int columns = getNumber(reader.readLine()); + printMessage(INFO_MESSAGE_FOR_ROWS.getMessage()); + int rows = getNumber(reader.readLine()); + printMessage(INFO_MESSAGE_FOR_STRATEGY.getMessage()); + String strategy = getStrategy(reader.readLine()); showCharsTable(columns, rows, strategy); } catch (IOException e) { - printMessage(ERROR_MESSAGE); + throw new RandomCharsTableException(ERROR_MESSAGE); + } catch (RandomCharsTableException e) { + printMessage(e.getMessage()); } } @@ -66,25 +56,25 @@ private char getRandomChar() { return (char) ThreadLocalRandom.current().nextInt(MIN_CHAR, MAX_CHAR + 1); } - private boolean isValidNumber(String number) { + private int getNumber(String text) throws RandomCharsTableException { + int number; try { - if (Integer.parseInt(number) < 1) { - printMessage(INTEGER_ERROR_MESSAGE); - return false; + number = Integer.parseInt(text); + if (number < 1) { + throw new RandomCharsTableException(INTEGER_ERROR_MESSAGE); } } catch (NumberFormatException e) { - printMessage(INTEGER_ERROR_MESSAGE); - return false; + throw new RandomCharsTableException(INTEGER_ERROR_MESSAGE); } - return true; + return number; } - private boolean isOddOrEven(String line) { + private String getStrategy(String line) throws RandomCharsTableException { if (line.toLowerCase().equals("odd") || line.toLowerCase().equals("even")) { - return true; + return line.toLowerCase(); + } else { + throw new RandomCharsTableException(STRATEGY_ERROR_MESSAGE); } - printMessage(STRATEGY_ERROR_MESSAGE); - return false; } private boolean isCharFitsStrategy(char ch, String strategy) { @@ -99,8 +89,4 @@ private String getFormattedStringForPrinting(String strategy, Set let } return result.substring(0, result.toString().trim().length() - 1); } - - private void printMessage(String text) { - System.out.print(text); - } } \ No newline at end of file diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableException.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableException.java new file mode 100644 index 00000000..68b2f4db --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableException.java @@ -0,0 +1,7 @@ +package homework_2.random_chars_table; + +public class RandomCharsTableException extends RuntimeException { + public RandomCharsTableException(MessageType e) { + super(e.getMessage()); + } +} diff --git a/src/main/java/homework_2/random_chars_table/Utils.java b/src/main/java/homework_2/random_chars_table/Utils.java new file mode 100644 index 00000000..eb728f58 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Utils.java @@ -0,0 +1,7 @@ +package homework_2.random_chars_table; + +public class Utils { + public static void printMessage(String text) { + System.out.print(text); + } +} diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index fa033081..633559c3 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -1,7 +1,10 @@ package homework_2.traffic_light; +import static homework_2.traffic_light.Utils.isExtraMode; + public class Main { public static void main(String[] args) { - new TrafficLight().run(); + int mode = args.length > 0 && isExtraMode(args[0]) ? 1 : 0; + new TrafficLight(mode).start(); } } diff --git a/src/main/java/homework_2/traffic_light/MessageType.java b/src/main/java/homework_2/traffic_light/MessageType.java new file mode 100644 index 00000000..947c7308 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/MessageType.java @@ -0,0 +1,25 @@ +package homework_2.traffic_light; + +public enum MessageType { + WARNING_MESSAGE_POSITIVE_NUMBERS("You should enter only positive numbers or 0."), + WARNING_MESSAGE_INCORRECT_FORMAT("You entered time in wrong format."), + WARNING_MESSAGE_EXCEED_LIMIT("Please do not exceed the time limits. There are only 86399 seconds or 23:59:59 in a day!"), + ERROR_MESSAGE("Something went wrong. Please restart the program!"), + INFO_MESSAGE("Hi! This is your guide to cross the road blindly!\n"), + INFO_MESSAGE_TO_MODE_0("You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + + "Please enter time in seconds. From 0 to 86399."), + INFO_MESSAGE_TO_MODE_1("You are in the extra mode.\nPlease enter time in format hh:mm:ss. From 00:00:00 to 23:59:59."), + LIGHT_RED_MESSAGE("\u001B[31m" + "RED" + "\u001B[0m" + "\nDo not cross the road!"), + LIGHT_GREEN_MESSAGE("\u001B[32m" + "GREEN" + "\u001B[0m" + "\nYou can cross the road!"), + LIGHT_YELLOW_MESSAGE("\u001B[33m" + "YELLOW" + "\u001B[0m" + "\nDo not cross the road, wait a little!"); + + private final String message; + + MessageType(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 8b2c3ef8..2e9d091d 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,125 +1,81 @@ package homework_2.traffic_light; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import static java.lang.System.lineSeparator; +import static homework_2.traffic_light.MessageType.INFO_MESSAGE; +import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_0; +import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_1; +import static homework_2.traffic_light.MessageType.LIGHT_GREEN_MESSAGE; +import static homework_2.traffic_light.MessageType.LIGHT_RED_MESSAGE; +import static homework_2.traffic_light.MessageType.LIGHT_YELLOW_MESSAGE; +import static homework_2.traffic_light.MessageType.WARNING_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.MessageType.WARNING_MESSAGE_INCORRECT_FORMAT; +import static homework_2.traffic_light.MessageType.WARNING_MESSAGE_POSITIVE_NUMBERS; +import static homework_2.traffic_light.Utils.getData; +import static homework_2.traffic_light.Utils.printMessage; public class TrafficLight { - private static final String INFO_MESSAGE = "Hi! This is your guide to cross the road blindly!\n" + - "Please choose the format to enter the time:\n" + - "1 - time in format hh:mm:ss. From 00:00:00 to 23:59:59\n" + - "2 - time in seconds. From 0 to 86399."; - private static final String INFO_MESSAGE_TO_CHOOSE_MODE = "Please enter 1 or 2."; - private static final String INFO_MESSAGE_TO_MODE_1 = "Please enter time in format hh:mm:ss. From 00:00:00 to 23:59:59."; - private static final String INFO_MESSAGE_TO_MODE_2 = "Please enter time in seconds. From 0 to 86399."; - private static final String ERROR_MESSAGE = "Something went wrong. Please restart the program!"; - private static final String WARNING_MESSAGE_POSITIVE_NUMS = "You should enter only positive numbers or 0."; - private static final String WARNING_MESSAGE_INCORRECT_FORMAT = "You entered time in wrong format."; - private static final String WARNING_MESSAGE_EXCEED_LIMIT = "Please do not exceed the time limits. There are only 86399 seconds or 24 hours in a day!"; - private static final String LIGHT_RED = "\u001B[31m" + "RED" + "\u001B[0m" + "\nDo not cross the road!"; - private static final String LIGHT_GREEN = "\u001B[32m" + "GREEN" + "\u001B[0m" + "\nYou can cross the road!"; - private static final String LIGHT_YELLOW = "\u001B[33m" + "YELLOW" + "\u001B[0m" + "\nDo not cross the road, wait a little!"; private static final int SECONDS_IN_DAY = 86399; private static final int SECONDS_IN_HOUR = 3600; private static final int SECONDS_IN_MINUTE = 60; + private final int mode; - public void run() { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { - printMessage(INFO_MESSAGE); - int mode = getMode(reader); - checkLight(mode, reader); - } catch (IOException e) { - printMessage(ERROR_MESSAGE); - } + public TrafficLight(int mode) { + this.mode = mode; } - private int getMode(BufferedReader reader) throws IOException { - while (true) { - String choice = reader.readLine(); - if (choice.equals("1") || choice.equals("2")) { - return Integer.parseInt(choice); - } - printMessage(INFO_MESSAGE_TO_CHOOSE_MODE); + public void start() { + printMessage(INFO_MESSAGE.getMessage()); + MessageType modeMessage = mode > 0 ? INFO_MESSAGE_TO_MODE_1 : INFO_MESSAGE_TO_MODE_0; + printMessage(modeMessage.getMessage()); + String data = getData(); + try { + printLight(getSeconds(mode, data)); + } catch (TrafficLightException e) { + printMessage(e.getMessage()); } } - private void checkLight(int mode, BufferedReader reader) throws IOException { - String line; - if (mode == 1) { - printMessage(INFO_MESSAGE_TO_MODE_1); - line = reader.readLine(); - if (isValidString(line)) { - printLight(parseToSeconds(line)); - } else { - checkLight(mode, reader); - } - } else { - printMessage(INFO_MESSAGE_TO_MODE_2); - line = reader.readLine(); - if (isValidSeconds(line)) { - printLight(Integer.parseInt(line)); - } else { - checkLight(mode, reader); + private int getSeconds(String time) { + int seconds; + try { + seconds = Integer.parseInt(time); + if (seconds < 1) { + throw new TrafficLightException(WARNING_MESSAGE_POSITIVE_NUMBERS); + } else if (seconds > SECONDS_IN_DAY) { + throw new TrafficLightException(WARNING_MESSAGE_EXCEED_LIMIT); } + } catch (NumberFormatException e) { + throw new TrafficLightException(WARNING_MESSAGE_INCORRECT_FORMAT); } + return seconds; } - private boolean isValidString(String time) { + private int getSeconds(int mode, String time) { + if (mode == 0) { + getSeconds(time); + } String[] timeArray = time.trim().split(":"); if (timeArray.length != 3) { - printMessage(WARNING_MESSAGE_INCORRECT_FORMAT + lineSeparator()); - return false; + throw new TrafficLightException(WARNING_MESSAGE_INCORRECT_FORMAT); } else if (time.contains("-")) { - printMessage(WARNING_MESSAGE_POSITIVE_NUMS + lineSeparator()); - return false; + throw new TrafficLightException(WARNING_MESSAGE_POSITIVE_NUMBERS); } int hours = Integer.parseInt(timeArray[0]); int minutes = Integer.parseInt(timeArray[1]); int seconds = Integer.parseInt(timeArray[2]); if (hours > 23 || minutes > 59 || seconds > 59) { - printMessage(WARNING_MESSAGE_EXCEED_LIMIT + lineSeparator()); - return false; - } - return true; - } - - private boolean isValidSeconds(String time) { - int seconds; - try { - seconds = Integer.parseInt(time); - if (seconds < 1) { - printMessage(WARNING_MESSAGE_POSITIVE_NUMS + lineSeparator()); - return false; - } - } catch (NumberFormatException e) { - printMessage(WARNING_MESSAGE_INCORRECT_FORMAT + lineSeparator()); - return false; + throw new TrafficLightException(WARNING_MESSAGE_EXCEED_LIMIT); } - return seconds <= SECONDS_IN_DAY; - } - - private int parseToSeconds(String time) { - String[] timeArray = time.split(":"); - int hours = Integer.parseInt(timeArray[0]); - int minutes = Integer.parseInt(timeArray[1]); - int seconds = Integer.parseInt(timeArray[2]); return hours * SECONDS_IN_HOUR + minutes * SECONDS_IN_MINUTE + seconds; } private void printLight(int seconds) { int reminder = seconds % SECONDS_IN_MINUTE; if (reminder >= 0 && reminder < 35) { - printMessage(LIGHT_GREEN); + printMessage(LIGHT_GREEN_MESSAGE.getMessage()); } else if (reminder >= 35 && reminder < 40) { - printMessage(LIGHT_YELLOW); + printMessage(LIGHT_YELLOW_MESSAGE.getMessage()); } else { - printMessage(LIGHT_RED); + printMessage(LIGHT_RED_MESSAGE.getMessage()); } } - - private void printMessage(String text) { - System.out.print(text); - } } \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/TrafficLightException.java b/src/main/java/homework_2/traffic_light/TrafficLightException.java new file mode 100644 index 00000000..fe854ee7 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightException.java @@ -0,0 +1,7 @@ +package homework_2.traffic_light; + +public class TrafficLightException extends RuntimeException { + public TrafficLightException(MessageType e) { + super(e.getMessage()); + } +} diff --git a/src/main/java/homework_2/traffic_light/Utils.java b/src/main/java/homework_2/traffic_light/Utils.java new file mode 100644 index 00000000..b20c9bd3 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Utils.java @@ -0,0 +1,24 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Utils { + public static void printMessage(String text) { + System.out.print(text); + } + + public static boolean isExtraMode(String mode) { + return mode.equals("1"); + } + + public static String getData() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + return reader.readLine(); + } catch (IOException e) { + throw new TrafficLightException(MessageType.ERROR_MESSAGE); + } + } + +} From 2c266b6e2d0dc63a53b35297b14740a0a0e61cd5 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 21 Jul 2021 16:30:57 +0300 Subject: [PATCH 19/80] add homework_3 --- src/main/java/homework_3/Age.java | 40 +++++++++++++ src/main/java/homework_3/ImmutableWorker.java | 57 +++++++++++++++++++ src/main/java/homework_3/Main.java | 19 +++++++ 3 files changed, 116 insertions(+) create mode 100644 src/main/java/homework_3/Age.java create mode 100644 src/main/java/homework_3/ImmutableWorker.java create mode 100644 src/main/java/homework_3/Main.java diff --git a/src/main/java/homework_3/Age.java b/src/main/java/homework_3/Age.java new file mode 100644 index 00000000..785c08da --- /dev/null +++ b/src/main/java/homework_3/Age.java @@ -0,0 +1,40 @@ +package homework_3; + +public class Age { + private int day; + private int month; + private int year; + + public Age() { + } + + public Age(int day, int month, int year) { + this.day = day; + this.month = month; + this.year = year; + } + + public int getDay() { + return day; + } + + public void setDay(int day) { + this.day = day; + } + + public int getMonth() { + return month; + } + + public void setMonth(int month) { + this.month = month; + } + + public int getYear() { + return year; + } + + public void setYear(int year) { + this.year = year; + } +} diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java new file mode 100644 index 00000000..7fb3c7ac --- /dev/null +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -0,0 +1,57 @@ +package homework_3; + +import java.util.ArrayList; +import java.util.List; + + +public final class ImmutableWorker { + private final String name; + private final String department; + private final int id; + private final List tasks; + private final Age age; + + public ImmutableWorker(String name, String department, int id, Age age) { + this.name = name; + this.department = department; + this.id = id; + this.tasks = new ArrayList<>(); + Age tempAge = new Age(); + tempAge.setDay(age.getDay()); + tempAge.setMonth(age.getMonth()); + tempAge.setYear(age.getYear()); + this.age = tempAge; + } + + public ImmutableWorker(String name, String department, int id, List tasks, Age age) { + this.name = name; + this.department = department; + this.id = id; + this.tasks = new ArrayList<>(tasks); + Age tempAge = new Age(); + tempAge.setDay(age.getDay()); + tempAge.setMonth(age.getMonth()); + tempAge.setYear(age.getYear()); + this.age = tempAge; + } + + public String getName() { + return name; + } + + public String getDepartment() { + return department; + } + + public int getId() { + return id; + } + + public List getTasks() { + return tasks; + } + + public Age getAge() { + return age; + } +} diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java new file mode 100644 index 00000000..52f85dc1 --- /dev/null +++ b/src/main/java/homework_3/Main.java @@ -0,0 +1,19 @@ +package homework_3; + +import java.util.ArrayList; +import java.util.List; + +public class Main { + public static void main(String[] args) { + List testList = new ArrayList<>(); + testList.add("task1"); + Age age = new Age(13, 5, 1980); + ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); + testList.add("task2"); + System.out.println("worker tasks list size: " + worker.getTasks().size()); + System.out.println("testList size: " + testList.size()); + age.setDay(5); + System.out.println(age.getDay()); + System.out.println(worker.getAge().getDay()); + } +} From 9f0773b663114f0c92c846fdc77aa5a8e3dc8b57 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 21 Jul 2021 16:34:27 +0300 Subject: [PATCH 20/80] add homework_3 --- src/main/java/homework_3/ImmutableWorker.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 7fb3c7ac..562292fa 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.List; - public final class ImmutableWorker { private final String name; private final String department; From af9e990805e1e975497dfaa57a5420c8306f5fb7 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 21 Jul 2021 18:52:37 +0300 Subject: [PATCH 21/80] add homework_3 --- src/main/java/homework_3/ImmutableWorker.java | 50 ++++++++++++++----- src/main/java/homework_3/Main.java | 5 ++ .../java/homework_3/ImmutableWorkerTest.java | 20 ++++++++ 3 files changed, 63 insertions(+), 12 deletions(-) create mode 100644 src/main/test/java/homework_3/ImmutableWorkerTest.java diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 562292fa..05d6cb23 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -3,6 +3,14 @@ import java.util.ArrayList; import java.util.List; +/** + * In general immutable class means that once an object is created, we cannot change its content, so: + * Immutable class should be final. + * Its fields should be private final. + * There should be getters but no setters. + * For link objects there should be a deep copy in the constructor. + */ + public final class ImmutableWorker { private final String name; private final String department; @@ -10,18 +18,6 @@ public final class ImmutableWorker { private final List tasks; private final Age age; - public ImmutableWorker(String name, String department, int id, Age age) { - this.name = name; - this.department = department; - this.id = id; - this.tasks = new ArrayList<>(); - Age tempAge = new Age(); - tempAge.setDay(age.getDay()); - tempAge.setMonth(age.getMonth()); - tempAge.setYear(age.getYear()); - this.age = tempAge; - } - public ImmutableWorker(String name, String department, int id, List tasks, Age age) { this.name = name; this.department = department; @@ -53,4 +49,34 @@ public List getTasks() { public Age getAge() { return age; } + + public ImmutableWorker updateWorker(String name, String department, int id, List tasks, Age age) { + if (name == null) { + name = this.getName(); + } + if (department == null) { + department = this.getDepartment(); + } + if (id == 0) { + id = this.getId(); + } + if (tasks == null) { + tasks = this.getTasks(); + } + if (age == null) { + age = this.getAge(); + } + return new ImmutableWorker(name, department, id, tasks, age); + } + + @Override + public String toString() { + return "ImmutableWorker{" + + "name='" + name + '\'' + + ", department='" + department + '\'' + + ", id=" + id + + ", tasks_size=" + tasks.size() + + ", age=" + age.getDay() + "." + age.getMonth() + "." + age.getYear() + + '}'; + } } diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java index 52f85dc1..78e9aba1 100644 --- a/src/main/java/homework_3/Main.java +++ b/src/main/java/homework_3/Main.java @@ -15,5 +15,10 @@ public static void main(String[] args) { age.setDay(5); System.out.println(age.getDay()); System.out.println(worker.getAge().getDay()); + System.out.println(worker.getName()); + worker = worker.updateWorker("Jackson", "Sales", 897, testList, age); + System.out.println(worker); + worker = worker.updateWorker(null, "Account", 0, null, null); + System.out.println(worker); } } diff --git a/src/main/test/java/homework_3/ImmutableWorkerTest.java b/src/main/test/java/homework_3/ImmutableWorkerTest.java new file mode 100644 index 00000000..135fa33d --- /dev/null +++ b/src/main/test/java/homework_3/ImmutableWorkerTest.java @@ -0,0 +1,20 @@ +package homework_3; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ImmutableWorkerTest { + + @Test + void testUpdateImmutable() { + List testList = new ArrayList<>(); + Age age = new Age(13, 5, 1980); + ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); + worker = worker.updateWorker(null, "Sales", 0, null, null); + assertEquals("Sales", worker.getDepartment()); + } +} From 7fe8fa12b2050c3fa74cf14c780c10a5b1affdef Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 22 Jul 2021 01:16:17 +0300 Subject: [PATCH 22/80] refactor homework_2 --- .../random_chars_table/MessageType.java | 4 +-- .../homework_2/traffic_light/MessageType.java | 12 +++---- .../traffic_light/TrafficLight.java | 31 +++++++++---------- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/MessageType.java b/src/main/java/homework_2/random_chars_table/MessageType.java index c138d1cc..87be4be7 100644 --- a/src/main/java/homework_2/random_chars_table/MessageType.java +++ b/src/main/java/homework_2/random_chars_table/MessageType.java @@ -5,8 +5,8 @@ public enum MessageType { INFO_MESSAGE_FOR_ROWS("Enter a positive integer for rows: "), INFO_MESSAGE_FOR_STRATEGY("Enter the word \"odd\" or \"even\" without quotes for strategy: "), INTEGER_ERROR_MESSAGE("It was not a positive integer."), - ERROR_MESSAGE("Something went wrong. Please restart the program!"), - STRATEGY_ERROR_MESSAGE("It was not a word \"odd\" or \"even\"."); + STRATEGY_ERROR_MESSAGE("It was not a word \"odd\" or \"even\"."), + ERROR_MESSAGE("Something went wrong. Please restart the program!"); private final String message; diff --git a/src/main/java/homework_2/traffic_light/MessageType.java b/src/main/java/homework_2/traffic_light/MessageType.java index 947c7308..7236aec1 100644 --- a/src/main/java/homework_2/traffic_light/MessageType.java +++ b/src/main/java/homework_2/traffic_light/MessageType.java @@ -1,17 +1,17 @@ package homework_2.traffic_light; public enum MessageType { - WARNING_MESSAGE_POSITIVE_NUMBERS("You should enter only positive numbers or 0."), - WARNING_MESSAGE_INCORRECT_FORMAT("You entered time in wrong format."), - WARNING_MESSAGE_EXCEED_LIMIT("Please do not exceed the time limits. There are only 86399 seconds or 23:59:59 in a day!"), + ERROR_MESSAGE_NEGATIVE_NUMBERS("You should enter only positive numbers or 0."), + ERROR_MESSAGE_INCORRECT_FORMAT("You entered time in wrong format."), + ERROR_MESSAGE_EXCEED_LIMIT("Please do not exceed the time limits. There are only 86399 seconds or 23:59:59 in a day!"), ERROR_MESSAGE("Something went wrong. Please restart the program!"), INFO_MESSAGE("Hi! This is your guide to cross the road blindly!\n"), INFO_MESSAGE_TO_MODE_0("You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + "Please enter time in seconds. From 0 to 86399."), INFO_MESSAGE_TO_MODE_1("You are in the extra mode.\nPlease enter time in format hh:mm:ss. From 00:00:00 to 23:59:59."), - LIGHT_RED_MESSAGE("\u001B[31m" + "RED" + "\u001B[0m" + "\nDo not cross the road!"), - LIGHT_GREEN_MESSAGE("\u001B[32m" + "GREEN" + "\u001B[0m" + "\nYou can cross the road!"), - LIGHT_YELLOW_MESSAGE("\u001B[33m" + "YELLOW" + "\u001B[0m" + "\nDo not cross the road, wait a little!"); + LIGHT_RED_MESSAGE("RED" + "\nDo not cross the road!"), + LIGHT_GREEN_MESSAGE("GREEN" + "\nYou can cross the road!"), + LIGHT_YELLOW_MESSAGE("YELLOW" + "\nDo not cross the road, wait a little!"); private final String message; diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 2e9d091d..0c958fd9 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -6,9 +6,9 @@ import static homework_2.traffic_light.MessageType.LIGHT_GREEN_MESSAGE; import static homework_2.traffic_light.MessageType.LIGHT_RED_MESSAGE; import static homework_2.traffic_light.MessageType.LIGHT_YELLOW_MESSAGE; -import static homework_2.traffic_light.MessageType.WARNING_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.MessageType.WARNING_MESSAGE_INCORRECT_FORMAT; -import static homework_2.traffic_light.MessageType.WARNING_MESSAGE_POSITIVE_NUMBERS; +import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; +import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; import static homework_2.traffic_light.Utils.getData; import static homework_2.traffic_light.Utils.printMessage; @@ -35,44 +35,43 @@ public void start() { } private int getSeconds(String time) { - int seconds; try { - seconds = Integer.parseInt(time); + int seconds = Integer.parseInt(time); if (seconds < 1) { - throw new TrafficLightException(WARNING_MESSAGE_POSITIVE_NUMBERS); + throw new TrafficLightException(ERROR_MESSAGE_NEGATIVE_NUMBERS); } else if (seconds > SECONDS_IN_DAY) { - throw new TrafficLightException(WARNING_MESSAGE_EXCEED_LIMIT); + throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); } + return seconds; } catch (NumberFormatException e) { - throw new TrafficLightException(WARNING_MESSAGE_INCORRECT_FORMAT); + throw new TrafficLightException(ERROR_MESSAGE_INCORRECT_FORMAT); } - return seconds; } private int getSeconds(int mode, String time) { if (mode == 0) { - getSeconds(time); + return getSeconds(time); } String[] timeArray = time.trim().split(":"); if (timeArray.length != 3) { - throw new TrafficLightException(WARNING_MESSAGE_INCORRECT_FORMAT); + throw new TrafficLightException(ERROR_MESSAGE_INCORRECT_FORMAT); } else if (time.contains("-")) { - throw new TrafficLightException(WARNING_MESSAGE_POSITIVE_NUMBERS); + throw new TrafficLightException(ERROR_MESSAGE_NEGATIVE_NUMBERS); } int hours = Integer.parseInt(timeArray[0]); int minutes = Integer.parseInt(timeArray[1]); int seconds = Integer.parseInt(timeArray[2]); if (hours > 23 || minutes > 59 || seconds > 59) { - throw new TrafficLightException(WARNING_MESSAGE_EXCEED_LIMIT); + throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); } return hours * SECONDS_IN_HOUR + minutes * SECONDS_IN_MINUTE + seconds; } private void printLight(int seconds) { - int reminder = seconds % SECONDS_IN_MINUTE; - if (reminder >= 0 && reminder < 35) { + int remainder = seconds % SECONDS_IN_MINUTE; + if (remainder >= 0 && remainder < 35) { printMessage(LIGHT_GREEN_MESSAGE.getMessage()); - } else if (reminder >= 35 && reminder < 40) { + } else if (remainder >= 35 && remainder < 40) { printMessage(LIGHT_YELLOW_MESSAGE.getMessage()); } else { printMessage(LIGHT_RED_MESSAGE.getMessage()); From 06bb33a7eb414b67d600d75732492bfe282ba71d Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 22 Jul 2021 01:17:14 +0300 Subject: [PATCH 23/80] add unit tests for homework_2 --- .../pyramid_printer/PyramidPrinterTest.java | 49 ++++++++ .../RandomCharsTableTest.java | 64 ++++++++++ .../traffic_light/TrafficLightTest.java | 117 ++++++++++++++++++ .../java/homework_3/ImmutableWorkerTest.java | 0 4 files changed, 230 insertions(+) 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/TrafficLightTest.java rename src/{main => }/test/java/homework_3/ImmutableWorkerTest.java (100%) 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..9dc69bfa --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,49 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_2.pyramid_printer.MessageType.ERROR_WRONG_FORMAT_MESSAGE; +import static homework_2.pyramid_printer.MessageType.INFO_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PyramidPrinterTest extends UnitBase { + + void run() { + new PyramidPrinter().start(); + removeFromOutput(INFO_MESSAGE.getMessage()); + printOut(); + } + + @Test + void given1_whenRun_thenPrintPyramid() { + setInput("1"); + run(); + assertEquals("x", getOutput()); + } + + @Test + void given5_whenRun_thenPrintPyramid() { + setInput("5"); + run(); + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + assertEquals("xxxx", getOutputLines()[3]); + assertEquals("xxxxx", getOutputLines()[4]); + } + + @Test + void givenNaN_whenRun_getWrongFormatMessage() { + setInput("word"); + run(); + assertEquals(ERROR_WRONG_FORMAT_MESSAGE.getMessage(), getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_getWrongFormatMessage() { + setInput("-5"); + run(); + assertEquals(ERROR_WRONG_FORMAT_MESSAGE.getMessage(), getOutput()); + } +} 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..01f69c19 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,64 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_COLUMNS; +import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_ROWS; +import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_STRATEGY; +import static homework_2.random_chars_table.MessageType.INTEGER_ERROR_MESSAGE; +import static homework_2.random_chars_table.MessageType.STRATEGY_ERROR_MESSAGE; +import static java.lang.System.lineSeparator; +import static org.junit.jupiter.api.Assertions.assertEquals; + + +public class RandomCharsTableTest extends UnitBase { + + void setInput(String[] args) { + StringBuilder input = new StringBuilder(); + for(String s: args) { + input.append(s).append(lineSeparator()); + } + super.setInput(input.substring(0, input.length()-1)); + } + + void run() { + new RandomCharsTable().start(); + removeFromOutput(INFO_MESSAGE_FOR_COLUMNS.getMessage()); + removeFromOutput(INFO_MESSAGE_FOR_ROWS.getMessage()); + removeFromOutput(INFO_MESSAGE_FOR_STRATEGY.getMessage()); + printOut(); + } + + @Test + void given1Row2Columns_whenRun_thenPrintRandomCharsTable() { + String[] lines = {"2", "1", "odd"}; + setInput(lines); + run(); + assertEquals(5, getOutputLines()[0].length()); + } + + @Test + void given1stNaN_whenRun_thenPrintNotIntegerMessage() { + String[] lines = {"word", "1", "even"}; + setInput(lines); + run(); + assertEquals(INTEGER_ERROR_MESSAGE.getMessage(), getOutput()); + } + + @Test + void given2ndNaN_whenRun_thenPrintNotIntegerMessage() { + String[] lines = {"1", "word", "odd"}; + setInput(lines); + run(); + assertEquals(INTEGER_ERROR_MESSAGE.getMessage(), getOutput()); + } + + @Test + void givenWrongStrategy_whenRun_thenPrintNotIntegerMessage() { + String[] lines = {"1", "3", "5"}; + setInput(lines); + run(); + assertEquals(STRATEGY_ERROR_MESSAGE.getMessage(), getOutput()); + } +} 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..4ef81e72 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,117 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + + +import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; +import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; +import static homework_2.traffic_light.MessageType.INFO_MESSAGE; +import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_0; +import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_1; +import static homework_2.traffic_light.MessageType.LIGHT_GREEN_MESSAGE; +import static homework_2.traffic_light.MessageType.LIGHT_RED_MESSAGE; +import static homework_2.traffic_light.MessageType.LIGHT_YELLOW_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightTest extends UnitBase { + + void run() { + new TrafficLight(0).start(); + removeFromOutput(INFO_MESSAGE.getMessage()); + removeFromOutput(INFO_MESSAGE_TO_MODE_0.getMessage()); + printOut(); + } + + void runExtraMode() { + new TrafficLight(1).start(); + removeFromOutput(INFO_MESSAGE.getMessage()); + removeFromOutput(INFO_MESSAGE_TO_MODE_1.getMessage()); + printOut(); + } + + @Test + void givenSecondsRemainderFrom0To34_whenRun_thenPrintGreenLight() { + setInput("315"); + run(); + assertEquals(LIGHT_GREEN_MESSAGE.getMessage(), getOutput()); + } + + @Test + void givenSecondsRemainderFrom35To39_whenRun_thenPrintYellowLight() { + setInput("217"); + run(); + assertEquals(LIGHT_YELLOW_MESSAGE.getMessage(), getOutput()); + } + + @Test + void givenSecondsRemainderFrom40To59_whenRun_thenPrintRedLight() { + setInput("538"); + run(); + assertEquals(LIGHT_RED_MESSAGE.getMessage(), getOutput()); + } + + @Test + void givenNaN_whenRun_thenPrintIncorrectFormatMessage() { + setInput("word"); + run(); + assertEquals(ERROR_MESSAGE_INCORRECT_FORMAT.getMessage(), getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_thenPrintNegativeNumberMessage() { + setInput("-600"); + run(); + assertEquals(ERROR_MESSAGE_NEGATIVE_NUMBERS.getMessage(), getOutput()); + } + + @Test + void givenExceedLimitSeconds_whenRun_thenPrintExceedLimitMessage() { + setInput("87000"); + run(); + assertEquals(ERROR_MESSAGE_EXCEED_LIMIT.getMessage(), getOutput()); + } + + @Test + void givenExceedLimitTimeString_whenRun_thenPrintExceedLimitMessage() { + setInput("28:15:18"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_EXCEED_LIMIT.getMessage(), getOutput()); + } + + @Test + void givenNegativeNumberTimeString_whenRun_thenPrintNegativeNumberMessage() { + setInput("-18:25:31"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_NEGATIVE_NUMBERS.getMessage(), getOutput()); + } + + @Test + void givenWrongFormatTimeString_whenRun_thenPrintIncorrectFormatMessage() { + setInput("29-17-16"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_INCORRECT_FORMAT.getMessage(), getOutput()); + } + + @Test + void givenTimeStringForGreen_whenRun_thenPrintGreenLight() { + setInput("13:24:12"); + runExtraMode(); + assertEquals(LIGHT_GREEN_MESSAGE.getMessage(), getOutput()); + } + + @Test + void givenTimeStringForYellow_whenRun_thenPrintYellowLight() { + setInput("18:37:39"); + runExtraMode(); + assertEquals(LIGHT_YELLOW_MESSAGE.getMessage(), getOutput()); + } + + @Test + void givenTimeStringForRed_whenRun_thenPrintRedLight() { + setInput("08:13:52"); + runExtraMode(); + assertEquals(LIGHT_RED_MESSAGE.getMessage(), getOutput()); + } +} diff --git a/src/main/test/java/homework_3/ImmutableWorkerTest.java b/src/test/java/homework_3/ImmutableWorkerTest.java similarity index 100% rename from src/main/test/java/homework_3/ImmutableWorkerTest.java rename to src/test/java/homework_3/ImmutableWorkerTest.java From 912f78e66a275531aba349f92ac676be48bc8a56 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 22 Jul 2021 01:40:16 +0300 Subject: [PATCH 24/80] refactor homework_3 --- src/main/java/homework_3/Age.java | 7 ++-- src/main/java/homework_3/ImmutableWorker.java | 40 ++++++++++++++++--- 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/src/main/java/homework_3/Age.java b/src/main/java/homework_3/Age.java index 785c08da..c9aa24ed 100644 --- a/src/main/java/homework_3/Age.java +++ b/src/main/java/homework_3/Age.java @@ -5,15 +5,16 @@ public class Age { private int month; private int year; - public Age() { - } - public Age(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } + public Age(Age age) { + this(age.getDay(), age.getMonth(), age.getYear()); + } + public int getDay() { return day; } diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 05d6cb23..90b12efe 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** * In general immutable class means that once an object is created, we cannot change its content, so: @@ -23,11 +24,23 @@ public ImmutableWorker(String name, String department, int id, List task this.department = department; this.id = id; this.tasks = new ArrayList<>(tasks); - Age tempAge = new Age(); - tempAge.setDay(age.getDay()); - tempAge.setMonth(age.getMonth()); - tempAge.setYear(age.getYear()); - this.age = tempAge; + this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); + } + + public ImmutableWorker(String name, String department, int id, Age age) { + this.name = name; + this.department = department; + this.id = id; + this.tasks = new ArrayList<>(); + this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); + } + + public ImmutableWorker(String name, int id, Age age) { + this.name = name; + this.department = null; + this.id = id; + this.tasks = new ArrayList<>(); + this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); } public String getName() { @@ -69,6 +82,23 @@ public ImmutableWorker updateWorker(String name, String department, int id, List return new ImmutableWorker(name, department, id, tasks, age); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ImmutableWorker that = (ImmutableWorker) o; + return getId() == that.getId() && + getName().equals(that.getName()) && + Objects.equals(getDepartment(), that.getDepartment()) && + Objects.equals(getTasks(), that.getTasks()) && + Objects.equals(getAge(), that.getAge()); + } + + @Override + public int hashCode() { + return Objects.hash(getName(), getDepartment(), getId(), getTasks(), getAge()); + } + @Override public String toString() { return "ImmutableWorker{" + From 8d5f2284499a9e56d63ed46df2a5591c0e26a0e6 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 22 Jul 2021 01:56:25 +0300 Subject: [PATCH 25/80] refactor homework_3 --- src/main/java/homework_3/ImmutableWorker.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 90b12efe..48beffee 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -1,5 +1,7 @@ package homework_3; +import jdk.nashorn.internal.ir.annotations.Immutable; + import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -37,7 +39,7 @@ public ImmutableWorker(String name, String department, int id, Age age) { public ImmutableWorker(String name, int id, Age age) { this.name = name; - this.department = null; + this.department = "No department"; this.id = id; this.tasks = new ArrayList<>(); this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); From ba3464271466af4a9076f07a0cf3ad24651f8c62 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 22 Jul 2021 09:05:47 +0300 Subject: [PATCH 26/80] update readme --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 1d5afe18..023ccaee 100644 --- a/README.md +++ b/README.md @@ -8,5 +8,9 @@ | HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| | HW2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | | HW2 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | +| HW3 | [Traffic light test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/traffic_light) | Add unit tests for Traffic Light app | +| HW3 | [Pyramid printer test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/pyramid_printer) | Add unit tests for Print Pyramid app| +| HW3 | [Random Chars table test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/random_chars_table) | Add unit tests for Random Chars Table app | +| HW3 | [Immutable Class Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3) | Add Immutable class | [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file From e72c2f8c89d393f383c0360002a005f9e24d8c77 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 22 Jul 2021 09:11:24 +0300 Subject: [PATCH 27/80] refactor homework_2, homework_3 --- .../pyramid_printer/PyramidPrinter.java | 10 +++++--- .../PyramidPrinterException.java | 4 ++- .../{ => utils}/MessageType.java | 2 +- .../pyramid_printer/{ => utils}/Utils.java | 2 +- .../random_chars_table/RandomCharsTable.java | 16 ++++++------ .../RandomCharsTableException.java | 4 ++- .../{ => utils}/MessageType.java | 2 +- .../random_chars_table/{ => utils}/Utils.java | 2 +- .../java/homework_2/traffic_light/Main.java | 2 +- .../traffic_light/TrafficLight.java | 25 +++++++++++-------- .../TrafficLightException.java | 4 ++- .../{ => utils}/MessageType.java | 2 +- .../traffic_light/{ => utils}/Utils.java | 5 +++- .../pyramid_printer/PyramidPrinterTest.java | 4 +-- .../RandomCharsTableTest.java | 10 ++++---- .../traffic_light/TrafficLightTest.java | 18 ++++++------- 16 files changed, 64 insertions(+), 48 deletions(-) rename src/main/java/homework_2/pyramid_printer/{ => exception}/PyramidPrinterException.java (59%) rename src/main/java/homework_2/pyramid_printer/{ => utils}/MessageType.java (90%) rename src/main/java/homework_2/pyramid_printer/{ => utils}/Utils.java (72%) rename src/main/java/homework_2/random_chars_table/{ => exception}/RandomCharsTableException.java (60%) rename src/main/java/homework_2/random_chars_table/{ => utils}/MessageType.java (93%) rename src/main/java/homework_2/random_chars_table/{ => utils}/Utils.java (71%) rename src/main/java/homework_2/traffic_light/{ => exception}/TrafficLightException.java (61%) rename src/main/java/homework_2/traffic_light/{ => utils}/MessageType.java (96%) rename src/main/java/homework_2/traffic_light/{ => utils}/Utils.java (79%) diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index e4c8219f..324e161f 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -1,13 +1,15 @@ package homework_2.pyramid_printer; +import homework_2.pyramid_printer.exception.PyramidPrinterException; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import static homework_2.pyramid_printer.MessageType.ERROR_MESSAGE; -import static homework_2.pyramid_printer.MessageType.ERROR_WRONG_FORMAT_MESSAGE; -import static homework_2.pyramid_printer.MessageType.INFO_MESSAGE; -import static homework_2.pyramid_printer.Utils.printMessage; +import static homework_2.pyramid_printer.utils.MessageType.ERROR_MESSAGE; +import static homework_2.pyramid_printer.utils.MessageType.ERROR_WRONG_FORMAT_MESSAGE; +import static homework_2.pyramid_printer.utils.MessageType.INFO_MESSAGE; +import static homework_2.pyramid_printer.utils.Utils.printMessage; import static java.lang.System.lineSeparator; public class PyramidPrinter { diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinterException.java b/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java similarity index 59% rename from src/main/java/homework_2/pyramid_printer/PyramidPrinterException.java rename to src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java index 17fdb62d..d08c9f67 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinterException.java +++ b/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java @@ -1,4 +1,6 @@ -package homework_2.pyramid_printer; +package homework_2.pyramid_printer.exception; + +import homework_2.pyramid_printer.utils.MessageType; public class PyramidPrinterException extends Throwable { public PyramidPrinterException(MessageType e) { diff --git a/src/main/java/homework_2/pyramid_printer/MessageType.java b/src/main/java/homework_2/pyramid_printer/utils/MessageType.java similarity index 90% rename from src/main/java/homework_2/pyramid_printer/MessageType.java rename to src/main/java/homework_2/pyramid_printer/utils/MessageType.java index e273129d..2c270044 100644 --- a/src/main/java/homework_2/pyramid_printer/MessageType.java +++ b/src/main/java/homework_2/pyramid_printer/utils/MessageType.java @@ -1,4 +1,4 @@ -package homework_2.pyramid_printer; +package homework_2.pyramid_printer.utils; public enum MessageType { INFO_MESSAGE("Please enter a positive integer for rows"), diff --git a/src/main/java/homework_2/pyramid_printer/Utils.java b/src/main/java/homework_2/pyramid_printer/utils/Utils.java similarity index 72% rename from src/main/java/homework_2/pyramid_printer/Utils.java rename to src/main/java/homework_2/pyramid_printer/utils/Utils.java index ded2bbef..dda1d646 100644 --- a/src/main/java/homework_2/pyramid_printer/Utils.java +++ b/src/main/java/homework_2/pyramid_printer/utils/Utils.java @@ -1,4 +1,4 @@ -package homework_2.pyramid_printer; +package homework_2.pyramid_printer.utils; public class Utils { public static void printMessage(String text) { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index c429518d..1c3a0a2c 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,5 +1,7 @@ package homework_2.random_chars_table; +import homework_2.random_chars_table.exception.RandomCharsTableException; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -7,13 +9,13 @@ import java.util.Set; import java.util.concurrent.ThreadLocalRandom; -import static homework_2.random_chars_table.MessageType.ERROR_MESSAGE; -import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_COLUMNS; -import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_ROWS; -import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_STRATEGY; -import static homework_2.random_chars_table.MessageType.INTEGER_ERROR_MESSAGE; -import static homework_2.random_chars_table.MessageType.STRATEGY_ERROR_MESSAGE; -import static homework_2.random_chars_table.Utils.printMessage; +import static homework_2.random_chars_table.utils.MessageType.ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_COLUMNS; +import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_ROWS; +import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_STRATEGY; +import static homework_2.random_chars_table.utils.MessageType.INTEGER_ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.MessageType.STRATEGY_ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.Utils.printMessage; import static java.lang.System.lineSeparator; public class RandomCharsTable { diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableException.java b/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java similarity index 60% rename from src/main/java/homework_2/random_chars_table/RandomCharsTableException.java rename to src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java index 68b2f4db..5784afa8 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTableException.java +++ b/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java @@ -1,4 +1,6 @@ -package homework_2.random_chars_table; +package homework_2.random_chars_table.exception; + +import homework_2.random_chars_table.utils.MessageType; public class RandomCharsTableException extends RuntimeException { public RandomCharsTableException(MessageType e) { diff --git a/src/main/java/homework_2/random_chars_table/MessageType.java b/src/main/java/homework_2/random_chars_table/utils/MessageType.java similarity index 93% rename from src/main/java/homework_2/random_chars_table/MessageType.java rename to src/main/java/homework_2/random_chars_table/utils/MessageType.java index 87be4be7..9d35b137 100644 --- a/src/main/java/homework_2/random_chars_table/MessageType.java +++ b/src/main/java/homework_2/random_chars_table/utils/MessageType.java @@ -1,4 +1,4 @@ -package homework_2.random_chars_table; +package homework_2.random_chars_table.utils; public enum MessageType { INFO_MESSAGE_FOR_COLUMNS("Enter a positive integer for columns: "), diff --git a/src/main/java/homework_2/random_chars_table/Utils.java b/src/main/java/homework_2/random_chars_table/utils/Utils.java similarity index 71% rename from src/main/java/homework_2/random_chars_table/Utils.java rename to src/main/java/homework_2/random_chars_table/utils/Utils.java index eb728f58..10e53f69 100644 --- a/src/main/java/homework_2/random_chars_table/Utils.java +++ b/src/main/java/homework_2/random_chars_table/utils/Utils.java @@ -1,4 +1,4 @@ -package homework_2.random_chars_table; +package homework_2.random_chars_table.utils; public class Utils { public static void printMessage(String text) { diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index 633559c3..b873ef74 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -1,6 +1,6 @@ package homework_2.traffic_light; -import static homework_2.traffic_light.Utils.isExtraMode; +import static homework_2.traffic_light.utils.Utils.isExtraMode; public class Main { public static void main(String[] args) { diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 0c958fd9..f7cb7ec4 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,16 +1,19 @@ package homework_2.traffic_light; -import static homework_2.traffic_light.MessageType.INFO_MESSAGE; -import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_0; -import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_1; -import static homework_2.traffic_light.MessageType.LIGHT_GREEN_MESSAGE; -import static homework_2.traffic_light.MessageType.LIGHT_RED_MESSAGE; -import static homework_2.traffic_light.MessageType.LIGHT_YELLOW_MESSAGE; -import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; -import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; -import static homework_2.traffic_light.Utils.getData; -import static homework_2.traffic_light.Utils.printMessage; +import homework_2.traffic_light.exception.TrafficLightException; +import homework_2.traffic_light.utils.MessageType; + +import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_0; +import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_1; +import static homework_2.traffic_light.utils.MessageType.LIGHT_GREEN_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.LIGHT_RED_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.LIGHT_YELLOW_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; +import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; +import static homework_2.traffic_light.utils.Utils.getData; +import static homework_2.traffic_light.utils.Utils.printMessage; public class TrafficLight { private static final int SECONDS_IN_DAY = 86399; diff --git a/src/main/java/homework_2/traffic_light/TrafficLightException.java b/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java similarity index 61% rename from src/main/java/homework_2/traffic_light/TrafficLightException.java rename to src/main/java/homework_2/traffic_light/exception/TrafficLightException.java index fe854ee7..ec5f6c34 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightException.java +++ b/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java @@ -1,4 +1,6 @@ -package homework_2.traffic_light; +package homework_2.traffic_light.exception; + +import homework_2.traffic_light.utils.MessageType; public class TrafficLightException extends RuntimeException { public TrafficLightException(MessageType e) { diff --git a/src/main/java/homework_2/traffic_light/MessageType.java b/src/main/java/homework_2/traffic_light/utils/MessageType.java similarity index 96% rename from src/main/java/homework_2/traffic_light/MessageType.java rename to src/main/java/homework_2/traffic_light/utils/MessageType.java index 7236aec1..f9e36f0c 100644 --- a/src/main/java/homework_2/traffic_light/MessageType.java +++ b/src/main/java/homework_2/traffic_light/utils/MessageType.java @@ -1,4 +1,4 @@ -package homework_2.traffic_light; +package homework_2.traffic_light.utils; public enum MessageType { ERROR_MESSAGE_NEGATIVE_NUMBERS("You should enter only positive numbers or 0."), diff --git a/src/main/java/homework_2/traffic_light/Utils.java b/src/main/java/homework_2/traffic_light/utils/Utils.java similarity index 79% rename from src/main/java/homework_2/traffic_light/Utils.java rename to src/main/java/homework_2/traffic_light/utils/Utils.java index b20c9bd3..bd503871 100644 --- a/src/main/java/homework_2/traffic_light/Utils.java +++ b/src/main/java/homework_2/traffic_light/utils/Utils.java @@ -1,4 +1,7 @@ -package homework_2.traffic_light; +package homework_2.traffic_light.utils; + +import homework_2.traffic_light.exception.TrafficLightException; +import homework_2.traffic_light.utils.MessageType; import java.io.BufferedReader; import java.io.IOException; diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java index 9dc69bfa..2052e7a8 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -3,8 +3,8 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static homework_2.pyramid_printer.MessageType.ERROR_WRONG_FORMAT_MESSAGE; -import static homework_2.pyramid_printer.MessageType.INFO_MESSAGE; +import static homework_2.pyramid_printer.utils.MessageType.ERROR_WRONG_FORMAT_MESSAGE; +import static homework_2.pyramid_printer.utils.MessageType.INFO_MESSAGE; import static org.junit.jupiter.api.Assertions.assertEquals; public class PyramidPrinterTest extends UnitBase { diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index 01f69c19..efd88748 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -3,11 +3,11 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_COLUMNS; -import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_ROWS; -import static homework_2.random_chars_table.MessageType.INFO_MESSAGE_FOR_STRATEGY; -import static homework_2.random_chars_table.MessageType.INTEGER_ERROR_MESSAGE; -import static homework_2.random_chars_table.MessageType.STRATEGY_ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_COLUMNS; +import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_ROWS; +import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_STRATEGY; +import static homework_2.random_chars_table.utils.MessageType.INTEGER_ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.MessageType.STRATEGY_ERROR_MESSAGE; import static java.lang.System.lineSeparator; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java index 4ef81e72..339a587b 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -4,15 +4,15 @@ import org.junit.jupiter.api.Test; -import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; -import static homework_2.traffic_light.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; -import static homework_2.traffic_light.MessageType.INFO_MESSAGE; -import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_0; -import static homework_2.traffic_light.MessageType.INFO_MESSAGE_TO_MODE_1; -import static homework_2.traffic_light.MessageType.LIGHT_GREEN_MESSAGE; -import static homework_2.traffic_light.MessageType.LIGHT_RED_MESSAGE; -import static homework_2.traffic_light.MessageType.LIGHT_YELLOW_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; +import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; +import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_0; +import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_1; +import static homework_2.traffic_light.utils.MessageType.LIGHT_GREEN_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.LIGHT_RED_MESSAGE; +import static homework_2.traffic_light.utils.MessageType.LIGHT_YELLOW_MESSAGE; import static org.junit.jupiter.api.Assertions.assertEquals; public class TrafficLightTest extends UnitBase { From e98f980c21e1e1c0f20faabf6682fe23bcc6cd44 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 22 Jul 2021 09:13:39 +0300 Subject: [PATCH 28/80] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 023ccaee..a71d9ae1 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,6 @@ | HW3 | [Traffic light test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/traffic_light) | Add unit tests for Traffic Light app | | HW3 | [Pyramid printer test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/pyramid_printer) | Add unit tests for Print Pyramid app| | HW3 | [Random Chars table test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/random_chars_table) | Add unit tests for Random Chars Table app | -| HW3 | [Immutable Class Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3) | Add Immutable class | +| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3) [Immutable Class test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_3) | Add Immutable class | [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file From 9be84aee53b575875d3e37cc4eb36a762a1be300 Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 25 Jul 2021 15:28:31 +0400 Subject: [PATCH 29/80] refactor hw2 and hw3 --- .../java/homework_2/pyramid_printer/Main.java | 2 +- .../pyramid_printer/PyramidPrinter.java | 38 +++--- .../exception/PyramidPrinterException.java | 6 +- .../pyramid_printer/utils/Constants.java | 7 ++ .../pyramid_printer/utils/MessageType.java | 17 --- .../pyramid_printer/utils/Utils.java | 7 -- .../homework_2/random_chars_table/Main.java | 2 +- .../random_chars_table/RandomCharsTable.java | 68 ++++++---- .../exception/RandomCharsTableException.java | 5 +- .../random_chars_table/utils/Constants.java | 9 ++ .../random_chars_table/utils/MessageType.java | 20 --- .../random_chars_table/utils/Utils.java | 18 +++ .../java/homework_2/traffic_light/Main.java | 4 +- .../traffic_light/TrafficLight.java | 85 ++----------- .../TrafficLightExtraModeImpl.java | 40 ++++++ .../traffic_light/TrafficLightImpl.java | 40 ++++++ .../exception/TrafficLightException.java | 6 +- .../traffic_light/utils/Constants.java | 18 +++ .../traffic_light/utils/MessageType.java | 25 ---- .../homework_2/traffic_light/utils/Utils.java | 7 +- src/main/java/homework_3/Age.java | 12 -- src/main/java/homework_3/ImmutableWorker.java | 3 +- src/main/java/homework_3/Main.java | 8 +- .../pyramid_printer/PyramidPrinterTest.java | 12 +- .../RandomCharsTableTest.java | 62 +++++----- .../traffic_light/TrafficLightImplTest.java | 112 +++++++++++++++++ .../traffic_light/TrafficLightTest.java | 117 ------------------ .../java/homework_3/ImmutableWorkerTest.java | 7 +- src/test/java/utils/Constants.java | 22 ++++ 29 files changed, 398 insertions(+), 381 deletions(-) create mode 100644 src/main/java/homework_2/pyramid_printer/utils/Constants.java delete mode 100644 src/main/java/homework_2/pyramid_printer/utils/MessageType.java delete mode 100644 src/main/java/homework_2/pyramid_printer/utils/Utils.java create mode 100644 src/main/java/homework_2/random_chars_table/utils/Constants.java delete mode 100644 src/main/java/homework_2/random_chars_table/utils/MessageType.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightExtraModeImpl.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLightImpl.java create mode 100644 src/main/java/homework_2/traffic_light/utils/Constants.java delete mode 100644 src/main/java/homework_2/traffic_light/utils/MessageType.java create mode 100644 src/test/java/homework_2/traffic_light/TrafficLightImplTest.java delete mode 100644 src/test/java/homework_2/traffic_light/TrafficLightTest.java create mode 100644 src/test/java/utils/Constants.java diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java index 641e9bdc..e50e37eb 100644 --- a/src/main/java/homework_2/pyramid_printer/Main.java +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - new PyramidPrinter().start(); + new PyramidPrinter().run(); } } diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 324e161f..f9eea6b9 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,47 +6,41 @@ import java.io.IOException; import java.io.InputStreamReader; -import static homework_2.pyramid_printer.utils.MessageType.ERROR_MESSAGE; -import static homework_2.pyramid_printer.utils.MessageType.ERROR_WRONG_FORMAT_MESSAGE; -import static homework_2.pyramid_printer.utils.MessageType.INFO_MESSAGE; -import static homework_2.pyramid_printer.utils.Utils.printMessage; -import static java.lang.System.lineSeparator; +import static homework_2.pyramid_printer.utils.Constants.ERROR_MESSAGE; +import static homework_2.pyramid_printer.utils.Constants.INFO_MESSAGE; +import static homework_2.pyramid_printer.utils.Constants.LETTER; public class PyramidPrinter { - private static final String LETTER = "x"; - public void start() { + public void run() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { - printMessage(INFO_MESSAGE.getMessage()); + System.out.println(INFO_MESSAGE); String line = reader.readLine(); int rows = getNumber(line); generatePyramid(rows); - } catch (IOException e) { - printMessage(ERROR_MESSAGE.getMessage()); - } catch (PyramidPrinterException e) { - printMessage(e.getMessage()); + } catch (IOException | PyramidPrinterException e) { + System.out.println(ERROR_MESSAGE); } } private int getNumber(String text) throws PyramidPrinterException { - int number; try { - number = Integer.parseInt(text); - if (number < 1) { - throw new PyramidPrinterException(ERROR_WRONG_FORMAT_MESSAGE); + int number = Integer.parseInt(text); + if (number < 0) { + throw new PyramidPrinterException(ERROR_MESSAGE); } + return number; } catch (NumberFormatException e) { - throw new PyramidPrinterException(ERROR_WRONG_FORMAT_MESSAGE); + throw new PyramidPrinterException(ERROR_MESSAGE); } - return number; } private void generatePyramid(int rows) { - for (int i = 1; i <= rows; i++) { - for (int j = 1; j <= i; j++) { - printMessage(LETTER); + for (int i = 0; i < rows; i++) { + for (int j = 0; j <= i; j++) { + System.out.print(LETTER); } - printMessage(lineSeparator()); + System.out.println(); } } } \ No newline at end of file diff --git a/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java b/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java index d08c9f67..a0c7fc65 100644 --- a/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java +++ b/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java @@ -1,9 +1,7 @@ package homework_2.pyramid_printer.exception; -import homework_2.pyramid_printer.utils.MessageType; - public class PyramidPrinterException extends Throwable { - public PyramidPrinterException(MessageType e) { - super(e.getMessage()); + public PyramidPrinterException(String detailMessage) { + super(detailMessage); } } diff --git a/src/main/java/homework_2/pyramid_printer/utils/Constants.java b/src/main/java/homework_2/pyramid_printer/utils/Constants.java new file mode 100644 index 00000000..80a0f5b2 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/utils/Constants.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer.utils; + +public class Constants { + public static final String INFO_MESSAGE = "Please enter a positive integer for rows"; + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String LETTER = "x"; +} diff --git a/src/main/java/homework_2/pyramid_printer/utils/MessageType.java b/src/main/java/homework_2/pyramid_printer/utils/MessageType.java deleted file mode 100644 index 2c270044..00000000 --- a/src/main/java/homework_2/pyramid_printer/utils/MessageType.java +++ /dev/null @@ -1,17 +0,0 @@ -package homework_2.pyramid_printer.utils; - -public enum MessageType { - INFO_MESSAGE("Please enter a positive integer for rows"), - ERROR_MESSAGE("Something went wrong. Please restart the program!"), - ERROR_WRONG_FORMAT_MESSAGE("Only positive integers are allowed."); - - private final String message; - - MessageType(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } -} diff --git a/src/main/java/homework_2/pyramid_printer/utils/Utils.java b/src/main/java/homework_2/pyramid_printer/utils/Utils.java deleted file mode 100644 index dda1d646..00000000 --- a/src/main/java/homework_2/pyramid_printer/utils/Utils.java +++ /dev/null @@ -1,7 +0,0 @@ -package homework_2.pyramid_printer.utils; - -public class Utils { - public static void printMessage(String text) { - System.out.print(text); - } -} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java index 6bc4bee1..682fe366 100644 --- a/src/main/java/homework_2/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - new RandomCharsTable().start(); + new RandomCharsTable().run(); } } diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 1c3a0a2c..19ead935 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -2,42 +2,36 @@ import homework_2.random_chars_table.exception.RandomCharsTableException; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; -import static homework_2.random_chars_table.utils.MessageType.ERROR_MESSAGE; -import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_COLUMNS; -import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_ROWS; -import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_STRATEGY; -import static homework_2.random_chars_table.utils.MessageType.INTEGER_ERROR_MESSAGE; -import static homework_2.random_chars_table.utils.MessageType.STRATEGY_ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.Constants.ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.Constants.MAX_CHAR; +import static homework_2.random_chars_table.utils.Constants.MIN_CHAR; +import static homework_2.random_chars_table.utils.Utils.getData; import static homework_2.random_chars_table.utils.Utils.printMessage; import static java.lang.System.lineSeparator; public class RandomCharsTable { - private static final int MAX_CHAR = 90; - private static final int MIN_CHAR = 65; - public void start() { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { - printMessage(INFO_MESSAGE_FOR_COLUMNS.getMessage()); - int columns = getNumber(reader.readLine()); - printMessage(INFO_MESSAGE_FOR_ROWS.getMessage()); - int rows = getNumber(reader.readLine()); - printMessage(INFO_MESSAGE_FOR_STRATEGY.getMessage()); - String strategy = getStrategy(reader.readLine()); - showCharsTable(columns, rows, strategy); - } catch (IOException e) { - throw new RandomCharsTableException(ERROR_MESSAGE); + public void run() { + try { + String[] data = getData().split(" "); + if (isValidData(data)) { + showCharsTable(getNumber(data[0]), getNumber(data[1]), getStrategy(data[2])); + } else { + printMessage(ERROR_MESSAGE); + } } catch (RandomCharsTableException e) { - printMessage(e.getMessage()); + printMessage(ERROR_MESSAGE); } } + private boolean isValidData(String[] data) { + return data.length == 3; + } + private void showCharsTable(int columns, int rows, String strategy) { Set charsByStrategySet = new HashSet<>(); for (int i = 0; i < rows; i++) { @@ -63,10 +57,10 @@ private int getNumber(String text) throws RandomCharsTableException { try { number = Integer.parseInt(text); if (number < 1) { - throw new RandomCharsTableException(INTEGER_ERROR_MESSAGE); + throw new RandomCharsTableException(); } } catch (NumberFormatException e) { - throw new RandomCharsTableException(INTEGER_ERROR_MESSAGE); + throw new RandomCharsTableException(); } return number; } @@ -75,7 +69,7 @@ private String getStrategy(String line) throws RandomCharsTableException { if (line.toLowerCase().equals("odd") || line.toLowerCase().equals("even")) { return line.toLowerCase(); } else { - throw new RandomCharsTableException(STRATEGY_ERROR_MESSAGE); + throw new RandomCharsTableException(); } } @@ -91,4 +85,26 @@ private String getFormattedStringForPrinting(String strategy, Set let } return result.substring(0, result.toString().trim().length() - 1); } + + public void debug(String input, char[] chars) { + String[] data = input.split(" "); + int count = 0; + if (isValidData(data)) { + Set charsByStrategySet = new HashSet<>(); + for (int i = 0; i < getNumber(data[0]); i++) { + printMessage("|"); + for (int j = 0; j < getNumber(data[1]); j++) { + count = count > chars.length - 1 ? 0 : count; + char ch = chars[count]; + count++; + if (isCharFitsStrategy(ch, getStrategy(data[2]))) { + charsByStrategySet.add(ch); + } + printMessage(ch + "|"); + } + printMessage(lineSeparator()); + } + printMessage(getFormattedStringForPrinting(getStrategy(data[2]), charsByStrategySet)); + } + } } \ No newline at end of file diff --git a/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java b/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java index 5784afa8..cd113268 100644 --- a/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java +++ b/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java @@ -1,9 +1,6 @@ package homework_2.random_chars_table.exception; -import homework_2.random_chars_table.utils.MessageType; - public class RandomCharsTableException extends RuntimeException { - public RandomCharsTableException(MessageType e) { - super(e.getMessage()); + public RandomCharsTableException() { } } diff --git a/src/main/java/homework_2/random_chars_table/utils/Constants.java b/src/main/java/homework_2/random_chars_table/utils/Constants.java new file mode 100644 index 00000000..2fd48440 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/utils/Constants.java @@ -0,0 +1,9 @@ +package homework_2.random_chars_table.utils; + +public class Constants { + + public static final String INFO_MESSAGE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; + public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + public static final int MAX_CHAR = 90; + public static final int MIN_CHAR = 65; +} diff --git a/src/main/java/homework_2/random_chars_table/utils/MessageType.java b/src/main/java/homework_2/random_chars_table/utils/MessageType.java deleted file mode 100644 index 9d35b137..00000000 --- a/src/main/java/homework_2/random_chars_table/utils/MessageType.java +++ /dev/null @@ -1,20 +0,0 @@ -package homework_2.random_chars_table.utils; - -public enum MessageType { - INFO_MESSAGE_FOR_COLUMNS("Enter a positive integer for columns: "), - INFO_MESSAGE_FOR_ROWS("Enter a positive integer for rows: "), - INFO_MESSAGE_FOR_STRATEGY("Enter the word \"odd\" or \"even\" without quotes for strategy: "), - INTEGER_ERROR_MESSAGE("It was not a positive integer."), - STRATEGY_ERROR_MESSAGE("It was not a word \"odd\" or \"even\"."), - ERROR_MESSAGE("Something went wrong. Please restart the program!"); - - private final String message; - - MessageType(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } -} diff --git a/src/main/java/homework_2/random_chars_table/utils/Utils.java b/src/main/java/homework_2/random_chars_table/utils/Utils.java index 10e53f69..5f3a1422 100644 --- a/src/main/java/homework_2/random_chars_table/utils/Utils.java +++ b/src/main/java/homework_2/random_chars_table/utils/Utils.java @@ -1,7 +1,25 @@ package homework_2.random_chars_table.utils; +import homework_2.random_chars_table.exception.RandomCharsTableException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static homework_2.random_chars_table.utils.Constants.INFO_MESSAGE; + + public class Utils { public static void printMessage(String text) { System.out.print(text); } + + public static String getData() { + printMessage(INFO_MESSAGE); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + return reader.readLine(); + } catch (IOException e) { + throw new RandomCharsTableException(); + } + } } diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index b873ef74..f884d000 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -4,7 +4,7 @@ public class Main { public static void main(String[] args) { - int mode = args.length > 0 && isExtraMode(args[0]) ? 1 : 0; - new TrafficLight(mode).start(); + TrafficLight trafficLight = args.length > 0 && isExtraMode(args[0]) ? new TrafficLightExtraModeImpl() : new TrafficLightImpl(); + trafficLight.run(); } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index f7cb7ec4..da3ad6ba 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,83 +1,24 @@ package homework_2.traffic_light; -import homework_2.traffic_light.exception.TrafficLightException; -import homework_2.traffic_light.utils.MessageType; - -import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE; -import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_0; -import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_1; -import static homework_2.traffic_light.utils.MessageType.LIGHT_GREEN_MESSAGE; -import static homework_2.traffic_light.utils.MessageType.LIGHT_RED_MESSAGE; -import static homework_2.traffic_light.utils.MessageType.LIGHT_YELLOW_MESSAGE; -import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; -import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; -import static homework_2.traffic_light.utils.Utils.getData; +import static homework_2.traffic_light.utils.Constants.LIGHT_GREEN_MESSAGE; +import static homework_2.traffic_light.utils.Constants.LIGHT_RED_MESSAGE; +import static homework_2.traffic_light.utils.Constants.LIGHT_YELLOW_MESSAGE; +import static homework_2.traffic_light.utils.Constants.SECONDS_IN_MINUTE; import static homework_2.traffic_light.utils.Utils.printMessage; -public class TrafficLight { - private static final int SECONDS_IN_DAY = 86399; - private static final int SECONDS_IN_HOUR = 3600; - private static final int SECONDS_IN_MINUTE = 60; - private final int mode; - - public TrafficLight(int mode) { - this.mode = mode; - } +public abstract class TrafficLight { + public abstract void run(); - public void start() { - printMessage(INFO_MESSAGE.getMessage()); - MessageType modeMessage = mode > 0 ? INFO_MESSAGE_TO_MODE_1 : INFO_MESSAGE_TO_MODE_0; - printMessage(modeMessage.getMessage()); - String data = getData(); - try { - printLight(getSeconds(mode, data)); - } catch (TrafficLightException e) { - printMessage(e.getMessage()); - } - } - - private int getSeconds(String time) { - try { - int seconds = Integer.parseInt(time); - if (seconds < 1) { - throw new TrafficLightException(ERROR_MESSAGE_NEGATIVE_NUMBERS); - } else if (seconds > SECONDS_IN_DAY) { - throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); - } - return seconds; - } catch (NumberFormatException e) { - throw new TrafficLightException(ERROR_MESSAGE_INCORRECT_FORMAT); - } - } - - private int getSeconds(int mode, String time) { - if (mode == 0) { - return getSeconds(time); - } - String[] timeArray = time.trim().split(":"); - if (timeArray.length != 3) { - throw new TrafficLightException(ERROR_MESSAGE_INCORRECT_FORMAT); - } else if (time.contains("-")) { - throw new TrafficLightException(ERROR_MESSAGE_NEGATIVE_NUMBERS); - } - int hours = Integer.parseInt(timeArray[0]); - int minutes = Integer.parseInt(timeArray[1]); - int seconds = Integer.parseInt(timeArray[2]); - if (hours > 23 || minutes > 59 || seconds > 59) { - throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); - } - return hours * SECONDS_IN_HOUR + minutes * SECONDS_IN_MINUTE + seconds; - } + protected abstract int getSeconds(String time); - private void printLight(int seconds) { + protected void printLight(int seconds) { int remainder = seconds % SECONDS_IN_MINUTE; if (remainder >= 0 && remainder < 35) { - printMessage(LIGHT_GREEN_MESSAGE.getMessage()); - } else if (remainder >= 35 && remainder < 40) { - printMessage(LIGHT_YELLOW_MESSAGE.getMessage()); + printMessage(LIGHT_GREEN_MESSAGE); + } else if (remainder >= 40 && remainder < 55) { + printMessage(LIGHT_RED_MESSAGE); } else { - printMessage(LIGHT_RED_MESSAGE.getMessage()); + printMessage(LIGHT_YELLOW_MESSAGE); } } -} \ No newline at end of file +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraModeImpl.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraModeImpl.java new file mode 100644 index 00000000..4920a0ea --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraModeImpl.java @@ -0,0 +1,40 @@ +package homework_2.traffic_light; + +import homework_2.traffic_light.exception.TrafficLightException; + +import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.Constants.INFO_MESSAGE_TO_EXTRA_MODE; +import static homework_2.traffic_light.utils.Constants.SECONDS_IN_HOUR; +import static homework_2.traffic_light.utils.Constants.SECONDS_IN_MINUTE; +import static homework_2.traffic_light.utils.Utils.getData; +import static homework_2.traffic_light.utils.Utils.printMessage; + +public class TrafficLightExtraModeImpl extends TrafficLight { + + @Override + public void run() { + printMessage(INFO_MESSAGE_TO_EXTRA_MODE); + try { + String data = getData(); + printLight(getSeconds(data)); + } catch (TrafficLightException e) { + printMessage(e.getMessage()); + } + } + + @Override + protected int getSeconds(String time) { + String[] timeArray = time.trim().split(":"); + if (timeArray.length != 3 || time.contains("-")) { + throw new TrafficLightException(ERROR_MESSAGE); + } + int hours = Integer.parseInt(timeArray[0]); + int minutes = Integer.parseInt(timeArray[1]); + int seconds = Integer.parseInt(timeArray[2]); + if (hours > 23 || minutes > 59 || seconds > 59) { + throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); + } + return hours * SECONDS_IN_HOUR + minutes * SECONDS_IN_MINUTE + seconds; + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLightImpl.java b/src/main/java/homework_2/traffic_light/TrafficLightImpl.java new file mode 100644 index 00000000..577eeb8d --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightImpl.java @@ -0,0 +1,40 @@ +package homework_2.traffic_light; + +import homework_2.traffic_light.exception.TrafficLightException; + +import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.Constants.INFO_MESSAGE; +import static homework_2.traffic_light.utils.Constants.SECONDS_IN_DAY; +import static homework_2.traffic_light.utils.Utils.getData; +import static homework_2.traffic_light.utils.Utils.printMessage; + +public class TrafficLightImpl extends TrafficLight { + + @Override + public void run() { + printMessage(INFO_MESSAGE); + try { + String data = getData(); + printLight(getSeconds(data)); + } catch (TrafficLightException e) { + printMessage(e.getMessage()); + } + } + + @Override + protected int getSeconds(String time) { + try { + int seconds = Integer.parseInt(time); + if (seconds < 0) { + throw new TrafficLightException(ERROR_MESSAGE); + } else if (seconds > SECONDS_IN_DAY) { + throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); + } + return seconds; + } catch (NumberFormatException e) { + throw new TrafficLightException(ERROR_MESSAGE); + } + } +} + diff --git a/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java b/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java index ec5f6c34..e570b76c 100644 --- a/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java +++ b/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java @@ -1,9 +1,7 @@ package homework_2.traffic_light.exception; -import homework_2.traffic_light.utils.MessageType; - public class TrafficLightException extends RuntimeException { - public TrafficLightException(MessageType e) { - super(e.getMessage()); + public TrafficLightException(String message) { + super(message); } } diff --git a/src/main/java/homework_2/traffic_light/utils/Constants.java b/src/main/java/homework_2/traffic_light/utils/Constants.java new file mode 100644 index 00000000..b38137ee --- /dev/null +++ b/src/main/java/homework_2/traffic_light/utils/Constants.java @@ -0,0 +1,18 @@ +package homework_2.traffic_light.utils; + +public class Constants { + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String INFO_MESSAGE = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + + "Please enter time in seconds. From 0 to 86399: "; + public static final String INFO_MESSAGE_TO_EXTRA_MODE = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the extra mode. To enter the default mode you should restart the program with no arguments.\n" + + "Please enter time in format hh:mm:ss: "; + public static final String ERROR_MESSAGE_EXCEED_LIMIT = "The day is over"; + public static final String LIGHT_RED_MESSAGE = "RED"; + public static final String LIGHT_GREEN_MESSAGE = "GREEN"; + public static final String LIGHT_YELLOW_MESSAGE = "YELLOW"; + public static final int SECONDS_IN_DAY = 86399; + public static final int SECONDS_IN_HOUR = 3600; + public static final int SECONDS_IN_MINUTE = 60; +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/utils/MessageType.java b/src/main/java/homework_2/traffic_light/utils/MessageType.java deleted file mode 100644 index f9e36f0c..00000000 --- a/src/main/java/homework_2/traffic_light/utils/MessageType.java +++ /dev/null @@ -1,25 +0,0 @@ -package homework_2.traffic_light.utils; - -public enum MessageType { - ERROR_MESSAGE_NEGATIVE_NUMBERS("You should enter only positive numbers or 0."), - ERROR_MESSAGE_INCORRECT_FORMAT("You entered time in wrong format."), - ERROR_MESSAGE_EXCEED_LIMIT("Please do not exceed the time limits. There are only 86399 seconds or 23:59:59 in a day!"), - ERROR_MESSAGE("Something went wrong. Please restart the program!"), - INFO_MESSAGE("Hi! This is your guide to cross the road blindly!\n"), - INFO_MESSAGE_TO_MODE_0("You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + - "Please enter time in seconds. From 0 to 86399."), - INFO_MESSAGE_TO_MODE_1("You are in the extra mode.\nPlease enter time in format hh:mm:ss. From 00:00:00 to 23:59:59."), - LIGHT_RED_MESSAGE("RED" + "\nDo not cross the road!"), - LIGHT_GREEN_MESSAGE("GREEN" + "\nYou can cross the road!"), - LIGHT_YELLOW_MESSAGE("YELLOW" + "\nDo not cross the road, wait a little!"); - - private final String message; - - MessageType(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } -} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/utils/Utils.java b/src/main/java/homework_2/traffic_light/utils/Utils.java index bd503871..8ecb2c0f 100644 --- a/src/main/java/homework_2/traffic_light/utils/Utils.java +++ b/src/main/java/homework_2/traffic_light/utils/Utils.java @@ -1,13 +1,15 @@ package homework_2.traffic_light.utils; import homework_2.traffic_light.exception.TrafficLightException; -import homework_2.traffic_light.utils.MessageType; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; + public class Utils { + public static void printMessage(String text) { System.out.print(text); } @@ -20,8 +22,7 @@ public static String getData() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { return reader.readLine(); } catch (IOException e) { - throw new TrafficLightException(MessageType.ERROR_MESSAGE); + throw new TrafficLightException(ERROR_MESSAGE); } } - } diff --git a/src/main/java/homework_3/Age.java b/src/main/java/homework_3/Age.java index c9aa24ed..4d8f7449 100644 --- a/src/main/java/homework_3/Age.java +++ b/src/main/java/homework_3/Age.java @@ -19,23 +19,11 @@ public int getDay() { return day; } - public void setDay(int day) { - this.day = day; - } - public int getMonth() { return month; } - public void setMonth(int month) { - this.month = month; - } - public int getYear() { return year; } - - public void setYear(int year) { - this.year = year; - } } diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 48beffee..ea26d133 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -1,7 +1,5 @@ package homework_3; -import jdk.nashorn.internal.ir.annotations.Immutable; - import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -12,6 +10,7 @@ * Its fields should be private final. * There should be getters but no setters. * For link objects there should be a deep copy in the constructor. + * Constructor always creates a new object. */ public final class ImmutableWorker { diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java index 78e9aba1..c3b80b48 100644 --- a/src/main/java/homework_3/Main.java +++ b/src/main/java/homework_3/Main.java @@ -12,9 +12,11 @@ public static void main(String[] args) { testList.add("task2"); System.out.println("worker tasks list size: " + worker.getTasks().size()); System.out.println("testList size: " + testList.size()); - age.setDay(5); - System.out.println(age.getDay()); - System.out.println(worker.getAge().getDay()); + //age.setDay(5); + //System.out.println("updated Age = " + age.getDay()); + //System.out.println("age day of the worker = " + worker.getAge().getDay()); + //worker.getAge().setDay(5); + System.out.println("age day of the worker = " + worker.getAge().getDay()); System.out.println(worker.getName()); worker = worker.updateWorker("Jackson", "Sales", 897, testList, age); System.out.println(worker); diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java index 2052e7a8..cc96117d 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -3,15 +3,15 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static homework_2.pyramid_printer.utils.MessageType.ERROR_WRONG_FORMAT_MESSAGE; -import static homework_2.pyramid_printer.utils.MessageType.INFO_MESSAGE; import static org.junit.jupiter.api.Assertions.assertEquals; +import static utils.Constants.ERROR_MESSAGE_PYRAMID_PRINTER; +import static utils.Constants.INFO_MESSAGE_PYRAMID_PRINTER; public class PyramidPrinterTest extends UnitBase { void run() { - new PyramidPrinter().start(); - removeFromOutput(INFO_MESSAGE.getMessage()); + new PyramidPrinter().run(); + removeFromOutput(INFO_MESSAGE_PYRAMID_PRINTER); printOut(); } @@ -37,13 +37,13 @@ void given5_whenRun_thenPrintPyramid() { void givenNaN_whenRun_getWrongFormatMessage() { setInput("word"); run(); - assertEquals(ERROR_WRONG_FORMAT_MESSAGE.getMessage(), getOutput()); + assertEquals(ERROR_MESSAGE_PYRAMID_PRINTER, getOutput()); } @Test void givenNegativeNumber_whenRun_getWrongFormatMessage() { setInput("-5"); run(); - assertEquals(ERROR_WRONG_FORMAT_MESSAGE.getMessage(), getOutput()); + assertEquals(ERROR_MESSAGE_PYRAMID_PRINTER, getOutput()); } } diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index efd88748..6f5ce7dd 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -3,62 +3,64 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_COLUMNS; -import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_ROWS; -import static homework_2.random_chars_table.utils.MessageType.INFO_MESSAGE_FOR_STRATEGY; -import static homework_2.random_chars_table.utils.MessageType.INTEGER_ERROR_MESSAGE; -import static homework_2.random_chars_table.utils.MessageType.STRATEGY_ERROR_MESSAGE; -import static java.lang.System.lineSeparator; import static org.junit.jupiter.api.Assertions.assertEquals; +import static utils.Constants.ERROR_MESSAGE_RANDOM_CHARS_TABLE; +import static utils.Constants.INFO_MESSAGE_RANDOM_CHARS_TABLE; public class RandomCharsTableTest extends UnitBase { - void setInput(String[] args) { - StringBuilder input = new StringBuilder(); - for(String s: args) { - input.append(s).append(lineSeparator()); - } - super.setInput(input.substring(0, input.length()-1)); - } - void run() { - new RandomCharsTable().start(); - removeFromOutput(INFO_MESSAGE_FOR_COLUMNS.getMessage()); - removeFromOutput(INFO_MESSAGE_FOR_ROWS.getMessage()); - removeFromOutput(INFO_MESSAGE_FOR_STRATEGY.getMessage()); + new RandomCharsTable().run(); + removeFromOutput(INFO_MESSAGE_RANDOM_CHARS_TABLE); printOut(); } @Test - void given1Row2Columns_whenRun_thenPrintRandomCharsTable() { - String[] lines = {"2", "1", "odd"}; - setInput(lines); + void given2Columns1Row_whenRun_thenPrintRandomCharsTable() { + setInput("2 1 odd"); run(); assertEquals(5, getOutputLines()[0].length()); } + @Test + void given2Rows2ColumnsOdd_whenRun_thenPrintRandomCharsTable() { + String input = "2 2 odd"; + setInput(input); + char[] charArray = {'A', 'B', 'C', 'D'}; + new RandomCharsTable().debug(input, charArray); + removeFromOutput("Odd letters - "); + assertEquals("|A|B|\n|C|D|\nA, C", getOutput()); + } + + @Test + void given3Rows2ColumnsEven_whenRun_thenPrintRandomCharsTable() { + String input ="3 2 even"; + setInput(input); + char[] charArray = {'A', 'B', 'C', 'D'}; + new RandomCharsTable().debug(input, charArray); + removeFromOutput("Even letters - "); + assertEquals("|A|B|\n|C|D|\n|A|B|\nB, D", getOutput()); + } + @Test void given1stNaN_whenRun_thenPrintNotIntegerMessage() { - String[] lines = {"word", "1", "even"}; - setInput(lines); + setInput("word 1 even"); run(); - assertEquals(INTEGER_ERROR_MESSAGE.getMessage(), getOutput()); + assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); } @Test void given2ndNaN_whenRun_thenPrintNotIntegerMessage() { - String[] lines = {"1", "word", "odd"}; - setInput(lines); + setInput("1 word odd"); run(); - assertEquals(INTEGER_ERROR_MESSAGE.getMessage(), getOutput()); + assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); } @Test void givenWrongStrategy_whenRun_thenPrintNotIntegerMessage() { - String[] lines = {"1", "3", "5"}; - setInput(lines); + setInput("1 3 5"); run(); - assertEquals(STRATEGY_ERROR_MESSAGE.getMessage(), getOutput()); + assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); } } diff --git a/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java b/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java new file mode 100644 index 00000000..83fb5d64 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java @@ -0,0 +1,112 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT; +import static utils.Constants.ERROR_MESSAGE_TRAFFIC_LIGHT; +import static utils.Constants.GREEN_MESSAGE_TRAFFIC_LIGHT; +import static utils.Constants.INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT; +import static utils.Constants.INFO_MESSAGE_TRAFFIC_LIGHT; +import static utils.Constants.RED_MESSAGE_TRAFFIC_LIGHT; +import static utils.Constants.YELLOW_MESSAGE_TRAFFIC_LIGHT; + +public class TrafficLightImplTest extends UnitBase { + + void run() { + new TrafficLightImpl().run(); + removeFromOutput(INFO_MESSAGE_TRAFFIC_LIGHT); + printOut(); + } + + void runExtraMode() { + new TrafficLightExtraModeImpl().run(); + removeFromOutput(INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT); + printOut(); + } + + @Test + void givenSecondsRemainderFrom0To34_whenRun_thenPrintGreenLight() { + setInput("315"); + run(); + assertEquals(GREEN_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenSecondsRemainderFrom35To39_whenRun_thenPrintYellowLight() { + setInput("55"); + run(); + assertEquals(YELLOW_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenSecondsRemainderFrom40To59_whenRun_thenPrintRedLight() { + setInput("174"); + run(); + assertEquals(RED_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenNaN_whenRun_thenPrintIncorrectFormatMessage() { + setInput("word"); + run(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_thenPrintNegativeNumberMessage() { + setInput("-600"); + run(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenExceedLimitSeconds_whenRun_thenPrintExceedLimitMessage() { + setInput("87000"); + run(); + assertEquals(ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenExceedLimitTimeString_whenRun_thenPrintExceedLimitMessage() { + setInput("28:15:18"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenNegativeNumberTimeString_whenRun_thenPrintNegativeNumberMessage() { + setInput("-18:25:31"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenWrongFormatTimeString_whenRun_thenPrintIncorrectFormatMessage() { + setInput("29-17-16"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenTimeStringForGreen_whenRun_thenPrintGreenLight() { + setInput("13:24:12"); + runExtraMode(); + assertEquals(GREEN_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenTimeStringForYellow_whenRun_thenPrintYellowLight() { + setInput("18:37:39"); + runExtraMode(); + assertEquals(YELLOW_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenTimeStringForRed_whenRun_thenPrintRedLight() { + setInput("08:13:52"); + runExtraMode(); + assertEquals(RED_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } +} diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java deleted file mode 100644 index 339a587b..00000000 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package homework_2.traffic_light; - -import base.UnitBase; -import org.junit.jupiter.api.Test; - - -import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_INCORRECT_FORMAT; -import static homework_2.traffic_light.utils.MessageType.ERROR_MESSAGE_NEGATIVE_NUMBERS; -import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE; -import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_0; -import static homework_2.traffic_light.utils.MessageType.INFO_MESSAGE_TO_MODE_1; -import static homework_2.traffic_light.utils.MessageType.LIGHT_GREEN_MESSAGE; -import static homework_2.traffic_light.utils.MessageType.LIGHT_RED_MESSAGE; -import static homework_2.traffic_light.utils.MessageType.LIGHT_YELLOW_MESSAGE; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class TrafficLightTest extends UnitBase { - - void run() { - new TrafficLight(0).start(); - removeFromOutput(INFO_MESSAGE.getMessage()); - removeFromOutput(INFO_MESSAGE_TO_MODE_0.getMessage()); - printOut(); - } - - void runExtraMode() { - new TrafficLight(1).start(); - removeFromOutput(INFO_MESSAGE.getMessage()); - removeFromOutput(INFO_MESSAGE_TO_MODE_1.getMessage()); - printOut(); - } - - @Test - void givenSecondsRemainderFrom0To34_whenRun_thenPrintGreenLight() { - setInput("315"); - run(); - assertEquals(LIGHT_GREEN_MESSAGE.getMessage(), getOutput()); - } - - @Test - void givenSecondsRemainderFrom35To39_whenRun_thenPrintYellowLight() { - setInput("217"); - run(); - assertEquals(LIGHT_YELLOW_MESSAGE.getMessage(), getOutput()); - } - - @Test - void givenSecondsRemainderFrom40To59_whenRun_thenPrintRedLight() { - setInput("538"); - run(); - assertEquals(LIGHT_RED_MESSAGE.getMessage(), getOutput()); - } - - @Test - void givenNaN_whenRun_thenPrintIncorrectFormatMessage() { - setInput("word"); - run(); - assertEquals(ERROR_MESSAGE_INCORRECT_FORMAT.getMessage(), getOutput()); - } - - @Test - void givenNegativeNumber_whenRun_thenPrintNegativeNumberMessage() { - setInput("-600"); - run(); - assertEquals(ERROR_MESSAGE_NEGATIVE_NUMBERS.getMessage(), getOutput()); - } - - @Test - void givenExceedLimitSeconds_whenRun_thenPrintExceedLimitMessage() { - setInput("87000"); - run(); - assertEquals(ERROR_MESSAGE_EXCEED_LIMIT.getMessage(), getOutput()); - } - - @Test - void givenExceedLimitTimeString_whenRun_thenPrintExceedLimitMessage() { - setInput("28:15:18"); - runExtraMode(); - assertEquals(ERROR_MESSAGE_EXCEED_LIMIT.getMessage(), getOutput()); - } - - @Test - void givenNegativeNumberTimeString_whenRun_thenPrintNegativeNumberMessage() { - setInput("-18:25:31"); - runExtraMode(); - assertEquals(ERROR_MESSAGE_NEGATIVE_NUMBERS.getMessage(), getOutput()); - } - - @Test - void givenWrongFormatTimeString_whenRun_thenPrintIncorrectFormatMessage() { - setInput("29-17-16"); - runExtraMode(); - assertEquals(ERROR_MESSAGE_INCORRECT_FORMAT.getMessage(), getOutput()); - } - - @Test - void givenTimeStringForGreen_whenRun_thenPrintGreenLight() { - setInput("13:24:12"); - runExtraMode(); - assertEquals(LIGHT_GREEN_MESSAGE.getMessage(), getOutput()); - } - - @Test - void givenTimeStringForYellow_whenRun_thenPrintYellowLight() { - setInput("18:37:39"); - runExtraMode(); - assertEquals(LIGHT_YELLOW_MESSAGE.getMessage(), getOutput()); - } - - @Test - void givenTimeStringForRed_whenRun_thenPrintRedLight() { - setInput("08:13:52"); - runExtraMode(); - assertEquals(LIGHT_RED_MESSAGE.getMessage(), getOutput()); - } -} diff --git a/src/test/java/homework_3/ImmutableWorkerTest.java b/src/test/java/homework_3/ImmutableWorkerTest.java index 135fa33d..64f2a39a 100644 --- a/src/test/java/homework_3/ImmutableWorkerTest.java +++ b/src/test/java/homework_3/ImmutableWorkerTest.java @@ -6,15 +6,16 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; public class ImmutableWorkerTest { @Test - void testUpdateImmutable() { + void testIfImmutable() { List testList = new ArrayList<>(); Age age = new Age(13, 5, 1980); ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); - worker = worker.updateWorker(null, "Sales", 0, null, null); - assertEquals("Sales", worker.getDepartment()); + assertEquals("Sales", worker.updateWorker("null", "Sales", 0, null, null).getDepartment()); + assertNotEquals(worker, worker.updateWorker("null", "Sales", 0, null, null)); } } diff --git a/src/test/java/utils/Constants.java b/src/test/java/utils/Constants.java new file mode 100644 index 00000000..174ff202 --- /dev/null +++ b/src/test/java/utils/Constants.java @@ -0,0 +1,22 @@ +package utils; + +public class Constants { + public static final String ERROR_MESSAGE_TRAFFIC_LIGHT = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String INFO_MESSAGE_TRAFFIC_LIGHT = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + + "Please enter time in seconds. From 0 to 86399: "; + public static final String INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the extra mode. To enter the default mode you should restart the program with no arguments.\n" + + "Please enter time in format hh:mm:ss: "; + public static final String ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT = "The day is over"; + public static final String RED_MESSAGE_TRAFFIC_LIGHT = "RED"; + public static final String GREEN_MESSAGE_TRAFFIC_LIGHT = "GREEN"; + public static final String YELLOW_MESSAGE_TRAFFIC_LIGHT = "YELLOW"; + + public static final String INFO_MESSAGE_PYRAMID_PRINTER = "Please enter a positive integer for rows"; + public static final String ERROR_MESSAGE_PYRAMID_PRINTER = "Only 1 non-negative integer is allowed as passed parameter"; + + public static final String ERROR_MESSAGE_RANDOM_CHARS_TABLE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + public static final String INFO_MESSAGE_RANDOM_CHARS_TABLE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; + +} \ No newline at end of file From 8e72a9169e4e7cde9427bc039ed77cea707a54b0 Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 25 Jul 2021 17:35:48 +0400 Subject: [PATCH 30/80] refactor hw2 and hw3 --- .../random_chars_table/RandomCharsTable.java | 22 ------- src/main/java/homework_3/Age.java | 6 +- .../RandomCharsTableTest.java | 61 ++++++++++++++----- .../traffic_light/TrafficLightImplTest.java | 6 +- .../java/homework_3/ImmutableWorkerTest.java | 2 - src/test/java/utils/Constants.java | 2 + 6 files changed, 53 insertions(+), 46 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 19ead935..f2aa8b9c 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -85,26 +85,4 @@ private String getFormattedStringForPrinting(String strategy, Set let } return result.substring(0, result.toString().trim().length() - 1); } - - public void debug(String input, char[] chars) { - String[] data = input.split(" "); - int count = 0; - if (isValidData(data)) { - Set charsByStrategySet = new HashSet<>(); - for (int i = 0; i < getNumber(data[0]); i++) { - printMessage("|"); - for (int j = 0; j < getNumber(data[1]); j++) { - count = count > chars.length - 1 ? 0 : count; - char ch = chars[count]; - count++; - if (isCharFitsStrategy(ch, getStrategy(data[2]))) { - charsByStrategySet.add(ch); - } - printMessage(ch + "|"); - } - printMessage(lineSeparator()); - } - printMessage(getFormattedStringForPrinting(getStrategy(data[2]), charsByStrategySet)); - } - } } \ No newline at end of file diff --git a/src/main/java/homework_3/Age.java b/src/main/java/homework_3/Age.java index 4d8f7449..fd56e25a 100644 --- a/src/main/java/homework_3/Age.java +++ b/src/main/java/homework_3/Age.java @@ -1,9 +1,9 @@ package homework_3; public class Age { - private int day; - private int month; - private int year; + private final int day; + private final int month; + private final int year; public Age(int day, int month, int year) { this.day = day; diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index 6f5ce7dd..bab16c63 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -3,9 +3,17 @@ import base.UnitBase; import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static utils.Constants.ERROR_MESSAGE_RANDOM_CHARS_TABLE; import static utils.Constants.INFO_MESSAGE_RANDOM_CHARS_TABLE; +import static utils.Constants.MAX_CHAR; +import static utils.Constants.MIN_CHAR; public class RandomCharsTableTest extends UnitBase { @@ -17,34 +25,55 @@ void run() { } @Test - void given2Columns1Row_whenRun_thenPrintRandomCharsTable() { - setInput("2 1 odd"); + void testPrintAlphabetChars() { + setInput("1 2 odd"); run(); - assertEquals(5, getOutputLines()[0].length()); + removeFromOutput("Odd letters - "); + removeFromOutput("|"); + removeFromOutput("\n"); + getOutput().replace(",", "|"); + String[] chars = getOutput().split("|"); + assertTrue(chars[0].charAt(0) >= MIN_CHAR && chars[0].charAt(0) <= MAX_CHAR); + assertTrue(chars[1].charAt(0) >= MIN_CHAR && chars[1].charAt(0) <= MAX_CHAR); + assertTrue(chars[2].charAt(0) >= MIN_CHAR && chars[2].charAt(0) <= MAX_CHAR); } @Test - void given2Rows2ColumnsOdd_whenRun_thenPrintRandomCharsTable() { - String input = "2 2 odd"; - setInput(input); - char[] charArray = {'A', 'B', 'C', 'D'}; - new RandomCharsTable().debug(input, charArray); + void givenOddStrategy_whenRun_thenPrintOddChars() { + setInput("2 8 odd"); + run(); removeFromOutput("Odd letters - "); - assertEquals("|A|B|\n|C|D|\nA, C", getOutput()); + List letters = new ArrayList<>(); + if (getOutputLines()[getOutputLines().length - 1].contains(",")) { + letters = Arrays.asList(getOutputLines()[getOutputLines().length - 1].split(", ")); + } else { + letters.add(getOutputLines()[2]); + } + for (String s : letters) { + char ch = s.charAt(0); + assertNotEquals(ch % 2, 0); + } } @Test - void given3Rows2ColumnsEven_whenRun_thenPrintRandomCharsTable() { - String input ="3 2 even"; - setInput(input); - char[] charArray = {'A', 'B', 'C', 'D'}; - new RandomCharsTable().debug(input, charArray); + void givenEvenStrategy_whenRun_thenPrintEvenChars() { + setInput("7 5 even"); + run(); removeFromOutput("Even letters - "); - assertEquals("|A|B|\n|C|D|\n|A|B|\nB, D", getOutput()); + List letters = new ArrayList<>(); + if (getOutputLines()[getOutputLines().length - 1].contains(",")) { + letters = Arrays.asList(getOutputLines()[getOutputLines().length - 1].split(", ")); + } else { + letters.add(getOutputLines()[2]); + } + for (String s : letters) { + char ch = s.charAt(0); + assertEquals(ch % 2, 0); + } } @Test - void given1stNaN_whenRun_thenPrintNotIntegerMessage() { + void givenNaN_whenRun_thenPrintNotIntegerMessage() { setInput("word 1 even"); run(); assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); diff --git a/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java b/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java index 83fb5d64..7802adce 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java @@ -34,14 +34,14 @@ void givenSecondsRemainderFrom0To34_whenRun_thenPrintGreenLight() { } @Test - void givenSecondsRemainderFrom35To39_whenRun_thenPrintYellowLight() { - setInput("55"); + void givenSecondsRemainderFrom35To39Or55To59_whenRun_thenPrintYellowLight() { + setInput("37"); run(); assertEquals(YELLOW_MESSAGE_TRAFFIC_LIGHT, getOutput()); } @Test - void givenSecondsRemainderFrom40To59_whenRun_thenPrintRedLight() { + void givenSecondsRemainderFrom40To54_whenRun_thenPrintRedLight() { setInput("174"); run(); assertEquals(RED_MESSAGE_TRAFFIC_LIGHT, getOutput()); diff --git a/src/test/java/homework_3/ImmutableWorkerTest.java b/src/test/java/homework_3/ImmutableWorkerTest.java index 64f2a39a..c4a3a3f0 100644 --- a/src/test/java/homework_3/ImmutableWorkerTest.java +++ b/src/test/java/homework_3/ImmutableWorkerTest.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; public class ImmutableWorkerTest { @@ -15,7 +14,6 @@ void testIfImmutable() { List testList = new ArrayList<>(); Age age = new Age(13, 5, 1980); ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); - assertEquals("Sales", worker.updateWorker("null", "Sales", 0, null, null).getDepartment()); assertNotEquals(worker, worker.updateWorker("null", "Sales", 0, null, null)); } } diff --git a/src/test/java/utils/Constants.java b/src/test/java/utils/Constants.java index 174ff202..dcf3e0b7 100644 --- a/src/test/java/utils/Constants.java +++ b/src/test/java/utils/Constants.java @@ -18,5 +18,7 @@ public class Constants { public static final String ERROR_MESSAGE_RANDOM_CHARS_TABLE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; public static final String INFO_MESSAGE_RANDOM_CHARS_TABLE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; + public static final int MAX_CHAR = 90; + public static final int MIN_CHAR = 65; } \ No newline at end of file From b714726268503daff09bc421dca29208d5e0008b Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 25 Jul 2021 21:58:59 +0400 Subject: [PATCH 31/80] refactor hw2 and hw3 --- .../java/homework_2/random_chars_table/utils/Constants.java | 1 - .../homework_2/random_chars_table/RandomCharsTableTest.java | 3 +-- src/test/java/utils/Constants.java | 1 - 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/utils/Constants.java b/src/main/java/homework_2/random_chars_table/utils/Constants.java index 2fd48440..82a64dc5 100644 --- a/src/main/java/homework_2/random_chars_table/utils/Constants.java +++ b/src/main/java/homework_2/random_chars_table/utils/Constants.java @@ -1,7 +1,6 @@ package homework_2.random_chars_table.utils; public class Constants { - public static final String INFO_MESSAGE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; public static final int MAX_CHAR = 90; diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index bab16c63..7a74f092 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -15,7 +15,6 @@ import static utils.Constants.MAX_CHAR; import static utils.Constants.MIN_CHAR; - public class RandomCharsTableTest extends UnitBase { void run() { @@ -64,7 +63,7 @@ void givenEvenStrategy_whenRun_thenPrintEvenChars() { if (getOutputLines()[getOutputLines().length - 1].contains(",")) { letters = Arrays.asList(getOutputLines()[getOutputLines().length - 1].split(", ")); } else { - letters.add(getOutputLines()[2]); + letters.add(getOutputLines()[getOutputLines().length - 1]); } for (String s : letters) { char ch = s.charAt(0); diff --git a/src/test/java/utils/Constants.java b/src/test/java/utils/Constants.java index dcf3e0b7..e74a3924 100644 --- a/src/test/java/utils/Constants.java +++ b/src/test/java/utils/Constants.java @@ -20,5 +20,4 @@ public class Constants { public static final String INFO_MESSAGE_RANDOM_CHARS_TABLE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; public static final int MAX_CHAR = 90; public static final int MIN_CHAR = 65; - } \ No newline at end of file From a7c4e405e74f465b35f59b648870ad1ffa112e3f Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 25 Jul 2021 22:49:41 +0400 Subject: [PATCH 32/80] update ImmutableWorker and ImmutableWorkerTest --- src/main/java/homework_3/ImmutableWorker.java | 4 +++- src/test/java/homework_3/ImmutableWorkerTest.java | 9 ++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index ea26d133..603fe63c 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -1,6 +1,7 @@ package homework_3; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Objects; @@ -75,7 +76,8 @@ public ImmutableWorker updateWorker(String name, String department, int id, List id = this.getId(); } if (tasks == null) { - tasks = this.getTasks(); + tasks = new ArrayList<>(); + Collections.copy(tasks, this.tasks); } if (age == null) { age = this.getAge(); diff --git a/src/test/java/homework_3/ImmutableWorkerTest.java b/src/test/java/homework_3/ImmutableWorkerTest.java index c4a3a3f0..e547d824 100644 --- a/src/test/java/homework_3/ImmutableWorkerTest.java +++ b/src/test/java/homework_3/ImmutableWorkerTest.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; public class ImmutableWorkerTest { @@ -14,6 +14,9 @@ void testIfImmutable() { List testList = new ArrayList<>(); Age age = new Age(13, 5, 1980); ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); - assertNotEquals(worker, worker.updateWorker("null", "Sales", 0, null, null)); + ImmutableWorker anotherWorker = worker.updateWorker("null", "Sales", 0, null, null); + assertNotSame(worker, anotherWorker); + assertNotSame(worker.getAge(), anotherWorker.getAge()); + assertNotSame(worker.getTasks(), anotherWorker.getTasks()); } -} +} \ No newline at end of file From e4e9e1123e34f2c21c5286373921e27c1e5c9284 Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 25 Jul 2021 22:53:38 +0400 Subject: [PATCH 33/80] update RandomCharsTable and RandomCharsTableTest --- .../java/homework_2/random_chars_table/RandomCharsTable.java | 2 +- .../homework_2/random_chars_table/RandomCharsTableTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index f2aa8b9c..9c5a0ef5 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -32,7 +32,7 @@ private boolean isValidData(String[] data) { return data.length == 3; } - private void showCharsTable(int columns, int rows, String strategy) { + private void showCharsTable(int rows, int columns, String strategy) { Set charsByStrategySet = new HashSet<>(); for (int i = 0; i < rows; i++) { printMessage("|"); diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index 7a74f092..0731f31c 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -72,7 +72,7 @@ void givenEvenStrategy_whenRun_thenPrintEvenChars() { } @Test - void givenNaN_whenRun_thenPrintNotIntegerMessage() { + void given1stNaN_whenRun_thenPrintNotIntegerMessage() { setInput("word 1 even"); run(); assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); From 95aa6cee1c50242cb1b4aaec74682d2b2a47b06a Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 28 Jul 2021 22:56:14 +0400 Subject: [PATCH 34/80] update hw2 and hw3 --- .../java/homework_2/traffic_light/Main.java | 2 +- .../traffic_light/TrafficLight.java | 35 ++++++++++++++-- ...deImpl.java => TrafficLightExtraMode.java} | 2 +- .../traffic_light/TrafficLightImpl.java | 40 ------------------- ...ghtImplTest.java => TrafficLightTest.java} | 6 +-- 5 files changed, 37 insertions(+), 48 deletions(-) rename src/main/java/homework_2/traffic_light/{TrafficLightExtraModeImpl.java => TrafficLightExtraMode.java} (96%) delete mode 100644 src/main/java/homework_2/traffic_light/TrafficLightImpl.java rename src/test/java/homework_2/traffic_light/{TrafficLightImplTest.java => TrafficLightTest.java} (95%) diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index f884d000..e4b7e39f 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -4,7 +4,7 @@ public class Main { public static void main(String[] args) { - TrafficLight trafficLight = args.length > 0 && isExtraMode(args[0]) ? new TrafficLightExtraModeImpl() : new TrafficLightImpl(); + TrafficLight trafficLight = args.length > 0 && isExtraMode(args[0]) ? new TrafficLightExtraMode() : new TrafficLight(); trafficLight.run(); } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index da3ad6ba..01791d59 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -1,15 +1,43 @@ package homework_2.traffic_light; +import homework_2.traffic_light.exception.TrafficLightException; + +import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.Constants.INFO_MESSAGE; import static homework_2.traffic_light.utils.Constants.LIGHT_GREEN_MESSAGE; import static homework_2.traffic_light.utils.Constants.LIGHT_RED_MESSAGE; import static homework_2.traffic_light.utils.Constants.LIGHT_YELLOW_MESSAGE; +import static homework_2.traffic_light.utils.Constants.SECONDS_IN_DAY; import static homework_2.traffic_light.utils.Constants.SECONDS_IN_MINUTE; +import static homework_2.traffic_light.utils.Utils.getData; import static homework_2.traffic_light.utils.Utils.printMessage; -public abstract class TrafficLight { - public abstract void run(); +public class TrafficLight { - protected abstract int getSeconds(String time); + public void run() { + printMessage(INFO_MESSAGE); + try { + String data = getData(); + printLight(getSeconds(data)); + } catch (TrafficLightException e) { + printMessage(e.getMessage()); + } + } + + protected int getSeconds(String time) { + try { + int seconds = Integer.parseInt(time); + if (seconds < 0) { + throw new TrafficLightException(ERROR_MESSAGE); + } else if (seconds > SECONDS_IN_DAY) { + throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); + } + return seconds; + } catch (NumberFormatException e) { + throw new TrafficLightException(ERROR_MESSAGE); + } + } protected void printLight(int seconds) { int remainder = seconds % SECONDS_IN_MINUTE; @@ -22,3 +50,4 @@ protected void printLight(int seconds) { } } } + diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraModeImpl.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java similarity index 96% rename from src/main/java/homework_2/traffic_light/TrafficLightExtraModeImpl.java rename to src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index 4920a0ea..dbd24344 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraModeImpl.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -10,7 +10,7 @@ import static homework_2.traffic_light.utils.Utils.getData; import static homework_2.traffic_light.utils.Utils.printMessage; -public class TrafficLightExtraModeImpl extends TrafficLight { +public class TrafficLightExtraMode extends TrafficLight { @Override public void run() { diff --git a/src/main/java/homework_2/traffic_light/TrafficLightImpl.java b/src/main/java/homework_2/traffic_light/TrafficLightImpl.java deleted file mode 100644 index 577eeb8d..00000000 --- a/src/main/java/homework_2/traffic_light/TrafficLightImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -package homework_2.traffic_light; - -import homework_2.traffic_light.exception.TrafficLightException; - -import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; -import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.utils.Constants.INFO_MESSAGE; -import static homework_2.traffic_light.utils.Constants.SECONDS_IN_DAY; -import static homework_2.traffic_light.utils.Utils.getData; -import static homework_2.traffic_light.utils.Utils.printMessage; - -public class TrafficLightImpl extends TrafficLight { - - @Override - public void run() { - printMessage(INFO_MESSAGE); - try { - String data = getData(); - printLight(getSeconds(data)); - } catch (TrafficLightException e) { - printMessage(e.getMessage()); - } - } - - @Override - protected int getSeconds(String time) { - try { - int seconds = Integer.parseInt(time); - if (seconds < 0) { - throw new TrafficLightException(ERROR_MESSAGE); - } else if (seconds > SECONDS_IN_DAY) { - throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); - } - return seconds; - } catch (NumberFormatException e) { - throw new TrafficLightException(ERROR_MESSAGE); - } - } -} - diff --git a/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java similarity index 95% rename from src/test/java/homework_2/traffic_light/TrafficLightImplTest.java rename to src/test/java/homework_2/traffic_light/TrafficLightTest.java index 7802adce..46542ffd 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightImplTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -12,16 +12,16 @@ import static utils.Constants.RED_MESSAGE_TRAFFIC_LIGHT; import static utils.Constants.YELLOW_MESSAGE_TRAFFIC_LIGHT; -public class TrafficLightImplTest extends UnitBase { +public class TrafficLightTest extends UnitBase { void run() { - new TrafficLightImpl().run(); + new TrafficLight().run(); removeFromOutput(INFO_MESSAGE_TRAFFIC_LIGHT); printOut(); } void runExtraMode() { - new TrafficLightExtraModeImpl().run(); + new TrafficLightExtraMode().run(); removeFromOutput(INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT); printOut(); } From 537f80adeeb4c00343ecd7bda60d3cea3ab83379 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 28 Jul 2021 23:34:51 +0400 Subject: [PATCH 35/80] update hw2 and hw3 --- .../random_chars_table/RandomCharsTableTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index 0731f31c..b2dd2381 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -30,11 +30,11 @@ void testPrintAlphabetChars() { removeFromOutput("Odd letters - "); removeFromOutput("|"); removeFromOutput("\n"); - getOutput().replace(",", "|"); - String[] chars = getOutput().split("|"); - assertTrue(chars[0].charAt(0) >= MIN_CHAR && chars[0].charAt(0) <= MAX_CHAR); - assertTrue(chars[1].charAt(0) >= MIN_CHAR && chars[1].charAt(0) <= MAX_CHAR); - assertTrue(chars[2].charAt(0) >= MIN_CHAR && chars[2].charAt(0) <= MAX_CHAR); + removeFromOutput(", "); + char[] chars = getOutput().toCharArray(); + assertTrue(chars[0] >= MIN_CHAR && chars[0] <= MAX_CHAR); + assertTrue(chars[1] >= MIN_CHAR && chars[1] <= MAX_CHAR); + assertTrue(chars[2] >= MIN_CHAR && chars[2] <= MAX_CHAR); } @Test From 6a9320839fdee697f553fc96d11eecf087bb49f6 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 3 Aug 2021 12:02:51 +0400 Subject: [PATCH 36/80] update hw2 and hw3 --- .../pyramid_printer/PyramidPrinterTest.java | 4 ++-- .../random_chars_table/RandomCharsTableTest.java | 8 ++++---- .../homework_2/traffic_light/TrafficLightTest.java | 14 +++++++------- .../java/{ => homework_2}/utils/Constants.java | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) rename src/test/java/{ => homework_2}/utils/Constants.java (98%) diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java index cc96117d..ccec51d9 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -3,9 +3,9 @@ import base.UnitBase; import org.junit.jupiter.api.Test; +import static homework_2.utils.Constants.ERROR_MESSAGE_PYRAMID_PRINTER; +import static homework_2.utils.Constants.INFO_MESSAGE_PYRAMID_PRINTER; import static org.junit.jupiter.api.Assertions.assertEquals; -import static utils.Constants.ERROR_MESSAGE_PYRAMID_PRINTER; -import static utils.Constants.INFO_MESSAGE_PYRAMID_PRINTER; public class PyramidPrinterTest extends UnitBase { diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index b2dd2381..f958f54b 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -7,13 +7,13 @@ import java.util.Arrays; import java.util.List; +import static homework_2.utils.Constants.ERROR_MESSAGE_RANDOM_CHARS_TABLE; +import static homework_2.utils.Constants.INFO_MESSAGE_RANDOM_CHARS_TABLE; +import static homework_2.utils.Constants.MAX_CHAR; +import static homework_2.utils.Constants.MIN_CHAR; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import static utils.Constants.ERROR_MESSAGE_RANDOM_CHARS_TABLE; -import static utils.Constants.INFO_MESSAGE_RANDOM_CHARS_TABLE; -import static utils.Constants.MAX_CHAR; -import static utils.Constants.MIN_CHAR; public class RandomCharsTableTest extends UnitBase { diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java index 46542ffd..62faa79b 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -3,14 +3,14 @@ import base.UnitBase; import org.junit.jupiter.api.Test; +import static homework_2.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT; +import static homework_2.utils.Constants.ERROR_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Constants.GREEN_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Constants.INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT; +import static homework_2.utils.Constants.INFO_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Constants.RED_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Constants.YELLOW_MESSAGE_TRAFFIC_LIGHT; import static org.junit.jupiter.api.Assertions.assertEquals; -import static utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT; -import static utils.Constants.ERROR_MESSAGE_TRAFFIC_LIGHT; -import static utils.Constants.GREEN_MESSAGE_TRAFFIC_LIGHT; -import static utils.Constants.INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT; -import static utils.Constants.INFO_MESSAGE_TRAFFIC_LIGHT; -import static utils.Constants.RED_MESSAGE_TRAFFIC_LIGHT; -import static utils.Constants.YELLOW_MESSAGE_TRAFFIC_LIGHT; public class TrafficLightTest extends UnitBase { diff --git a/src/test/java/utils/Constants.java b/src/test/java/homework_2/utils/Constants.java similarity index 98% rename from src/test/java/utils/Constants.java rename to src/test/java/homework_2/utils/Constants.java index e74a3924..1ac0ee95 100644 --- a/src/test/java/utils/Constants.java +++ b/src/test/java/homework_2/utils/Constants.java @@ -1,4 +1,4 @@ -package utils; +package homework_2.utils; public class Constants { public static final String ERROR_MESSAGE_TRAFFIC_LIGHT = "Only 1 non-negative integer is allowed as passed parameter"; From 1ebba5f3036ec1acd4577ef5cd4f841ad97c33b8 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 3 Aug 2021 12:05:03 +0400 Subject: [PATCH 37/80] add hw4 --- README.md | 19 ++++--- .../homework_4/custom_annotation/Author.java | 13 +++++ .../homework_4/custom_annotation/Book.java | 25 +++++++++ .../custom_file_reader/CustomFileReader.java | 50 ++++++++++++++++++ .../homework_4/custom_file_reader/Main.java | 14 +++++ .../custom_file_reader/Runnable.java | 10 ++++ .../java/homework_4/singleton/Singleton.java | 15 ++++++ .../custom_file_reader/Shakespeare.txt | 28 ++++++++++ .../custom_annotation/BookTest.java | 27 ++++++++++ .../CustomFileReaderTest.java | 51 +++++++++++++++++++ .../homework_4/singleton/SingletonTest.java | 15 ++++++ 11 files changed, 259 insertions(+), 8 deletions(-) create mode 100644 src/main/java/homework_4/custom_annotation/Author.java create mode 100644 src/main/java/homework_4/custom_annotation/Book.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/custom_file_reader/Runnable.java create mode 100644 src/main/java/homework_4/singleton/Singleton.java create mode 100644 src/main/resources/custom_file_reader/Shakespeare.txt create mode 100644 src/test/java/homework_4/custom_annotation/BookTest.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/README.md b/README.md index a71d9ae1..361f41cc 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,16 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/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/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| -| HW2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | -| HW2 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | -| HW3 | [Traffic light test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/traffic_light) | Add unit tests for Traffic Light app | -| HW3 | [Pyramid printer test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/pyramid_printer) | Add unit tests for Print Pyramid app| -| HW3 | [Random Chars table test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/random_chars_table) | Add unit tests for Random Chars Table app | -| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3) [Immutable Class test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_3) | Add Immutable class | +| HW1 | [Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/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/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | +| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | +| HW3 | [Traffic Light Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/traffic_light) | Add unit tests for Traffic Light app | +| HW3 | [Pyramid Printer Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/pyramid_printer) | Add unit tests for Print Pyramid app| +| HW3 | [Random Chars Table Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/random_chars_table) | Add unit tests for Random Chars Table app | +| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3) [Immutable Class Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_3) | Add Immutable class | +| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_file_reader) [CustomFileReader Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_file_reader) | The app that reads data from the file and prints it to the console without dots and commas | +| HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton) [Singleton Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | +| HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation) [Custom Annotation Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file diff --git a/src/main/java/homework_4/custom_annotation/Author.java b/src/main/java/homework_4/custom_annotation/Author.java new file mode 100644 index 00000000..488410a5 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Author.java @@ -0,0 +1,13 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface Author { + String value() default "unknown"; +} diff --git a/src/main/java/homework_4/custom_annotation/Book.java b/src/main/java/homework_4/custom_annotation/Book.java new file mode 100644 index 00000000..6a709b42 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Book.java @@ -0,0 +1,25 @@ +package homework_4.custom_annotation; + +@Author +public class Book { + private String name; + private String author; + + public Book(String name, String author) { + if (author == null || author.isEmpty()) { + Author defaultAuthor = (Author) this.getClass().getDeclaredAnnotations()[0]; + this.author = defaultAuthor.value(); + } else { + this.author = author; + } + this.name = name; + } + + public String getName() { + return name; + } + + public String getAuthor() { + return author; + } +} 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..e643488d --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,50 @@ +package homework_4.custom_file_reader; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Scanner; + +public class CustomFileReader implements Runnable { + private static final String FILE_NAME = "src/main/resources/custom_file_reader/Shakespeare.txt"; + private static final File FILE = new File(FILE_NAME); + + @Override + public void run1() { + try (BufferedReader reader = new BufferedReader(new FileReader(FILE))) { + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line.replace(".", "").replace(",", "")); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void run2() { + try { + Scanner scanner = new Scanner(FILE); + while (scanner.hasNextLine()) { + System.out.println(scanner.nextLine().replace(".", "").replace(",", "")); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + @Override + public void run3() { + try { + String data = new String(Files.readAllBytes(Paths.get(FILE_NAME))); + data = data.replace(".", "").replace(",", ""); + System.out.println(data); + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file 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..fdf40d57 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,14 @@ +package homework_4.custom_file_reader; + +public class Main { + public static void main(String[] args) { + CustomFileReader reader = new CustomFileReader(); + reader.run1(); + System.out.println(); + reader.run2(); + System.out.println(); + reader.run3(); + } +} + + diff --git a/src/main/java/homework_4/custom_file_reader/Runnable.java b/src/main/java/homework_4/custom_file_reader/Runnable.java new file mode 100644 index 00000000..e4265dcb --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Runnable.java @@ -0,0 +1,10 @@ +package homework_4.custom_file_reader; + +public interface Runnable { + + void run1(); + + void run2(); + + void run3(); +} 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..35d86bd7 --- /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/Shakespeare.txt b/src/main/resources/custom_file_reader/Shakespeare.txt new file mode 100644 index 00000000..07b4889d --- /dev/null +++ b/src/main/resources/custom_file_reader/Shakespeare.txt @@ -0,0 +1,28 @@ +All the world's a stage, +And all the men and women merely players; +They have their exits and their entrances, +And one man in his time plays many parts, +His acts being seven ages. At first, the infant, +Mewling and puking in the nurse's arms. +Then the whining schoolboy, with his satchel +And shining morning face, creeping like snail +Unwillingly to school. And then the lover, +Sighing like furnace, with a woeful ballad +Made to his mistress' eyebrow. Then a soldier, +Full of strange oaths and bearded like the pard, +Jealous in honor, sudden and quick in quarrel, +Seeking the bubble reputation +Even in the cannon's mouth. And then the justice, +In fair round belly with good capon lined, +With eyes severe and beard of formal cut, +Full of wise saws and modern instances; +And so he plays his part. The sixth age shifts +Into the lean and slippered pantaloon, +With spectacles on nose and pouch on side; +His youthful hose, well saved, a world too wide +For his shrunk shank, and his big manly voice, +Turning again toward childish treble, pipes +And whistles in his sound. Last scene of all, +That ends this strange eventful history, +Is second childishness and mere oblivion, +Sans teeth, sans eyes, sans taste, sans everything. \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/BookTest.java b/src/test/java/homework_4/custom_annotation/BookTest.java new file mode 100644 index 00000000..81795743 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/BookTest.java @@ -0,0 +1,27 @@ +package homework_4.custom_annotation; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class BookTest { + private static final String DEFAULT_AUTHOR = "unknown"; + + @Test + void givenNull_getDefault() { + Book book = new Book("Harry Potter", null); + assertEquals(DEFAULT_AUTHOR, book.getAuthor()); + } + + @Test + void givenEmptyString_getDefault() { + Book book = new Book("Lord Of The Rings", ""); + assertEquals(DEFAULT_AUTHOR, book.getAuthor()); + } + + @Test + void givenAuthor_getAuthor() { + Book book = new Book("Alice's Adventures In Wonderland", "Lewis Carroll"); + assertEquals("Lewis Carroll", book.getAuthor()); + } +} 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..df716ab9 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,51 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +public class CustomFileReaderTest extends UnitBase { + private static final String FILE_NAME = "src/main/resources/custom_file_reader/Shakespeare.txt"; + + @Test + void run1() { + new CustomFileReader().run1(); + assertFalse(getOutput().contains(".")); + assertFalse(getOutput().contains(",")); + try { + assertNotEquals(Files.readAllBytes(Paths.get(FILE_NAME)), getOutput().getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + void run2() { + new CustomFileReader().run2(); + assertFalse(getOutput().contains(".")); + assertFalse(getOutput().contains(",")); + try { + assertNotEquals(Files.readAllBytes(Paths.get(FILE_NAME)), getOutput().getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + void run3() { + new CustomFileReader().run3(); + assertFalse(getOutput().contains(".")); + assertFalse(getOutput().contains(",")); + try { + assertNotEquals(Files.readAllBytes(Paths.get(FILE_NAME)), getOutput().getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } +} 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..be3de5b7 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertSame; + +public class SingletonTest { + + @Test + void testGetInstance() { + Singleton singleton = Singleton.getInstance(); + Singleton anotherSingleton = Singleton.getInstance(); + assertSame(singleton, anotherSingleton); + } +} From dab661baa41320b6d5b3fd8ef767dc26145159a3 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 3 Aug 2021 16:29:29 +0400 Subject: [PATCH 38/80] add hw4 --- .../custom_file_reader/CustomFileReader.java | 29 ++++++++++++------- .../custom_file_reader/Runnable.java | 10 ------- 2 files changed, 18 insertions(+), 21 deletions(-) delete mode 100644 src/main/java/homework_4/custom_file_reader/Runnable.java diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index e643488d..6fc0f0c9 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -9,42 +9,49 @@ import java.nio.file.Paths; import java.util.Scanner; -public class CustomFileReader implements Runnable { +import static java.lang.System.lineSeparator; + +public class CustomFileReader { private static final String FILE_NAME = "src/main/resources/custom_file_reader/Shakespeare.txt"; + private static final String ERROR_MESSAGE = "Can not read file."; private static final File FILE = new File(FILE_NAME); - @Override public void run1() { try (BufferedReader reader = new BufferedReader(new FileReader(FILE))) { String line; while ((line = reader.readLine()) != null) { - System.out.println(line.replace(".", "").replace(",", "")); + printMessage(trimDotsAndCommas(line) + lineSeparator()); } } catch (IOException e) { - e.printStackTrace(); + printMessage(ERROR_MESSAGE); } } - @Override public void run2() { try { Scanner scanner = new Scanner(FILE); while (scanner.hasNextLine()) { - System.out.println(scanner.nextLine().replace(".", "").replace(",", "")); + printMessage(trimDotsAndCommas(scanner.nextLine()) + lineSeparator()); } } catch (FileNotFoundException e) { - e.printStackTrace(); + printMessage(ERROR_MESSAGE); } } - @Override public void run3() { try { String data = new String(Files.readAllBytes(Paths.get(FILE_NAME))); - data = data.replace(".", "").replace(",", ""); - System.out.println(data); + printMessage(trimDotsAndCommas(data)); } catch (IOException e) { - e.printStackTrace(); + printMessage(ERROR_MESSAGE); } } + + private void printMessage(String message) { + System.out.print(message); + } + + private String trimDotsAndCommas(String line){ + return line.replace(".", "").replace(",", ""); + } } \ No newline at end of file diff --git a/src/main/java/homework_4/custom_file_reader/Runnable.java b/src/main/java/homework_4/custom_file_reader/Runnable.java deleted file mode 100644 index e4265dcb..00000000 --- a/src/main/java/homework_4/custom_file_reader/Runnable.java +++ /dev/null @@ -1,10 +0,0 @@ -package homework_4.custom_file_reader; - -public interface Runnable { - - void run1(); - - void run2(); - - void run3(); -} From 075565a44f4f6c7445f45bddd8d4ce0ab20f02f5 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 3 Aug 2021 16:33:06 +0400 Subject: [PATCH 39/80] add hw4 --- src/main/java/homework_4/singleton/Singleton.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java index 35d86bd7..19e0399b 100644 --- a/src/main/java/homework_4/singleton/Singleton.java +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -1,15 +1,12 @@ package homework_4.singleton; public class Singleton { - private static Singleton instance; - private Singleton() { + public static class SingletonHolder { + public static final Singleton HOLDER_INSTANCE = new Singleton(); } public static Singleton getInstance() { - if (instance == null) { - instance = new Singleton(); - } - return instance; + return SingletonHolder.HOLDER_INSTANCE; } } From 7066727170515a3610a380cf856a5a4f664d0abb Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 3 Aug 2021 16:34:42 +0400 Subject: [PATCH 40/80] add hw4 --- src/main/java/homework_4/singleton/Singleton.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java index 19e0399b..107c5f74 100644 --- a/src/main/java/homework_4/singleton/Singleton.java +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -2,7 +2,7 @@ public class Singleton { - public static class SingletonHolder { + private static class SingletonHolder { public static final Singleton HOLDER_INSTANCE = new Singleton(); } From ef2d9e81fea7e0b4933807af270a0557f87552f1 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 3 Aug 2021 16:57:50 +0400 Subject: [PATCH 41/80] add hw4 --- src/main/java/homework_4/custom_annotation/Author.java | 3 +-- src/main/java/homework_4/custom_annotation/Book.java | 8 ++++++++ src/test/java/homework_4/custom_annotation/BookTest.java | 7 +++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_4/custom_annotation/Author.java b/src/main/java/homework_4/custom_annotation/Author.java index 488410a5..5a84163c 100644 --- a/src/main/java/homework_4/custom_annotation/Author.java +++ b/src/main/java/homework_4/custom_annotation/Author.java @@ -5,9 +5,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Author { - String value() default "unknown"; + String value() default "Unknown author"; } diff --git a/src/main/java/homework_4/custom_annotation/Book.java b/src/main/java/homework_4/custom_annotation/Book.java index 6a709b42..31ea572f 100644 --- a/src/main/java/homework_4/custom_annotation/Book.java +++ b/src/main/java/homework_4/custom_annotation/Book.java @@ -22,4 +22,12 @@ public String getName() { public String getAuthor() { return author; } + + @Override + public String toString() { + return "Book{" + + "name='" + name + '\'' + + ", author='" + author + '\'' + + '}'; + } } diff --git a/src/test/java/homework_4/custom_annotation/BookTest.java b/src/test/java/homework_4/custom_annotation/BookTest.java index 81795743..a192c56e 100644 --- a/src/test/java/homework_4/custom_annotation/BookTest.java +++ b/src/test/java/homework_4/custom_annotation/BookTest.java @@ -24,4 +24,11 @@ void givenAuthor_getAuthor() { Book book = new Book("Alice's Adventures In Wonderland", "Lewis Carroll"); assertEquals("Lewis Carroll", book.getAuthor()); } + + @Test + void givenName_getName(){ + Book book = new Book("The Adventures of Tom Sawyer", "Mark Twain"); + assertEquals("Mark Twain", book.getName()); + } + } From 82fd0db37a89b98313bbbfb4a03949eaa52ff51c Mon Sep 17 00:00:00 2001 From: rlrio <69588345+rlrio@users.noreply.github.com> Date: Wed, 4 Aug 2021 02:38:25 +0400 Subject: [PATCH 42/80] add hw4 --- src/test/java/homework_4/custom_annotation/BookTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/homework_4/custom_annotation/BookTest.java b/src/test/java/homework_4/custom_annotation/BookTest.java index a192c56e..f1a5c788 100644 --- a/src/test/java/homework_4/custom_annotation/BookTest.java +++ b/src/test/java/homework_4/custom_annotation/BookTest.java @@ -5,7 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class BookTest { - private static final String DEFAULT_AUTHOR = "unknown"; + private static final String DEFAULT_AUTHOR = "Unknown author"; @Test void givenNull_getDefault() { From d5acd27075b61bb53d13646e0ad8bb84df580648 Mon Sep 17 00:00:00 2001 From: rlrio <69588345+rlrio@users.noreply.github.com> Date: Wed, 4 Aug 2021 02:40:23 +0400 Subject: [PATCH 43/80] add hw4 --- src/test/java/homework_4/custom_annotation/BookTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/homework_4/custom_annotation/BookTest.java b/src/test/java/homework_4/custom_annotation/BookTest.java index f1a5c788..d7887e57 100644 --- a/src/test/java/homework_4/custom_annotation/BookTest.java +++ b/src/test/java/homework_4/custom_annotation/BookTest.java @@ -28,7 +28,7 @@ void givenAuthor_getAuthor() { @Test void givenName_getName(){ Book book = new Book("The Adventures of Tom Sawyer", "Mark Twain"); - assertEquals("Mark Twain", book.getName()); + assertEquals("The Adventures of Tom Sawyer", book.getName()); } } From c440a4d80eaf45d72e6e286e82ecfd5858928578 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 4 Aug 2021 10:24:41 +0400 Subject: [PATCH 44/80] add hw4 --- src/test/java/homework_4/custom_annotation/BookTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/test/java/homework_4/custom_annotation/BookTest.java b/src/test/java/homework_4/custom_annotation/BookTest.java index d7887e57..638cdd32 100644 --- a/src/test/java/homework_4/custom_annotation/BookTest.java +++ b/src/test/java/homework_4/custom_annotation/BookTest.java @@ -31,4 +31,11 @@ void givenName_getName(){ assertEquals("The Adventures of Tom Sawyer", book.getName()); } + @Test + void givenNameAndNullAuthor_getNameAndDefaultAuthor(){ + Book book = new Book("The Scarlet Letter", null); + assertEquals("The Scarlet Letter", book.getName()); + assertEquals(DEFAULT_AUTHOR, book.getAuthor()); + } + } From 8f6ffa33121262943101eab2549c0120a0852065 Mon Sep 17 00:00:00 2001 From: rlrio <69588345+rlrio@users.noreply.github.com> Date: Fri, 6 Aug 2021 11:04:02 +0400 Subject: [PATCH 45/80] update hw4 Co-authored-by: ffibonacci --- .../java/homework_4/custom_file_reader/CustomFileReader.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index 6fc0f0c9..7b7e35b7 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -52,6 +52,6 @@ private void printMessage(String message) { } private String trimDotsAndCommas(String line){ - return line.replace(".", "").replace(",", ""); + return line.replaceAll("[,.]", ""); } -} \ No newline at end of file +} From 080c768a2b718cea15636323f829b3664097e650 Mon Sep 17 00:00:00 2001 From: rlrio Date: Sat, 7 Aug 2021 20:15:36 +0400 Subject: [PATCH 46/80] update hw4 --- .../java/homework_4/custom_file_reader/CustomFileReader.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java index 7b7e35b7..03a78ce8 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -28,8 +28,7 @@ public void run1() { } public void run2() { - try { - Scanner scanner = new Scanner(FILE); + try (Scanner scanner = new Scanner(FILE)){ while (scanner.hasNextLine()) { printMessage(trimDotsAndCommas(scanner.nextLine()) + lineSeparator()); } From 5adc35d673e4ae3be598d212537e6036ca6b902c Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 18 Aug 2021 13:02:23 +0300 Subject: [PATCH 47/80] add hw5 math_power --- .../java/homework_5/math_power/MathPower.java | 11 ++++++ .../homework_5/math_power/MathPowerTest.java | 39 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/main/java/homework_5/math_power/MathPower.java create mode 100644 src/test/java/homework_5/math_power/MathPowerTest.java diff --git a/src/main/java/homework_5/math_power/MathPower.java b/src/main/java/homework_5/math_power/MathPower.java new file mode 100644 index 00000000..821cdb49 --- /dev/null +++ b/src/main/java/homework_5/math_power/MathPower.java @@ -0,0 +1,11 @@ +package homework_5.math_power; + +public class MathPower { + + public static double pow(double value, int powValue) { + if (powValue < 0) { + return 1 / pow(value, - powValue); + } + return powValue == 1 ? value : value * pow(value, powValue - 1); + } +} diff --git a/src/test/java/homework_5/math_power/MathPowerTest.java b/src/test/java/homework_5/math_power/MathPowerTest.java new file mode 100644 index 00000000..64a828d8 --- /dev/null +++ b/src/test/java/homework_5/math_power/MathPowerTest.java @@ -0,0 +1,39 @@ +package homework_5.math_power; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MathPowerTest { + + @Test + void test_value2_toPowOf_5() { + assertEquals(Math.pow(2, 5), MathPower.pow(2, 5)); + } + + @Test + void test_value18_toPowOf_7() { + assertEquals(Math.pow(18, 7), MathPower.pow(18, 7)); + } + + @Test + void test_value21_toPowOf_10() { + assertEquals(Math.pow(21, 10), MathPower.pow(21, 10)); + } + + @Test + void test_valueNegative4_toPowOf_5() { + assertEquals(Math.pow(-4, 5), MathPower.pow(-4, 5)); + } + + @Test + void test_value1d3_toPowOf_8() { + assertEquals(Math.pow(2.3, 8), MathPower.pow(2.3, 8)); + } + + @Test + void test_value2d3_toPowOf_negative7() { + assertEquals(Math.pow(2.3, -7), MathPower.pow(2.3, -7)); + } + +} From 38245c28dbcd86f6cd5550ad58783188dd98bfa5 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 18 Aug 2021 13:39:15 +0300 Subject: [PATCH 48/80] update README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 361f41cc..a604d23e 100644 --- a/README.md +++ b/README.md @@ -15,5 +15,5 @@ | HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_file_reader) [CustomFileReader Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_file_reader) | The app that reads data from the file and prints it to the console without dots and commas | | HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton) [Singleton Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | | HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation) [Custom Annotation Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | - +| HW5 | [Math Power Recursion](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [MathPowerTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | Class MathPow with method pow implemented via recursion | [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file From dfa292038073a2d497579ed32750ab2273930add Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 18 Aug 2021 13:40:17 +0300 Subject: [PATCH 49/80] update README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a604d23e..69bb85fa 100644 --- a/README.md +++ b/README.md @@ -16,4 +16,6 @@ | HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton) [Singleton Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | | HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation) [Custom Annotation Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | | HW5 | [Math Power Recursion](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [MathPowerTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | Class MathPow with method pow implemented via recursion | + + [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file From ddd9c88e6ce867d0d893120e1b1993e7aeb506d4 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 18 Aug 2021 14:32:10 +0300 Subject: [PATCH 50/80] update hw5 --- src/test/java/homework_5/math_power/MathPowerTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/homework_5/math_power/MathPowerTest.java b/src/test/java/homework_5/math_power/MathPowerTest.java index 64a828d8..6dc8c4e6 100644 --- a/src/test/java/homework_5/math_power/MathPowerTest.java +++ b/src/test/java/homework_5/math_power/MathPowerTest.java @@ -36,4 +36,9 @@ void test_value2d3_toPowOf_negative7() { assertEquals(Math.pow(2.3, -7), MathPower.pow(2.3, -7)); } + @Test + void test_value5_toPowOf_0() { + assertEquals(Math.pow(5, 0), MathPower.pow(5, 0)); + } + } From b4a218995fb648d32718507f6856cc019ed62796 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 19 Aug 2021 14:22:40 +0300 Subject: [PATCH 51/80] update hw5 --- src/main/java/homework_5/math_power/Main.java | 8 ++ .../java/homework_5/math_power/MathPower.java | 11 --- .../homework_5/math_power/PowerOfNumber.java | 23 ++++++ .../math_power/utils/Constants.java | 5 ++ .../homework_5/math_power/utils/Utils.java | 16 ++++ .../homework_5/math_power/MathPowerTest.java | 44 ---------- .../math_power/PowerOfNumberTest.java | 82 +++++++++++++++++++ .../math_power/utils/Constants.java | 5 ++ 8 files changed, 139 insertions(+), 55 deletions(-) create mode 100644 src/main/java/homework_5/math_power/Main.java delete mode 100644 src/main/java/homework_5/math_power/MathPower.java create mode 100644 src/main/java/homework_5/math_power/PowerOfNumber.java create mode 100644 src/main/java/homework_5/math_power/utils/Constants.java create mode 100644 src/main/java/homework_5/math_power/utils/Utils.java delete mode 100644 src/test/java/homework_5/math_power/MathPowerTest.java create mode 100644 src/test/java/homework_5/math_power/PowerOfNumberTest.java create mode 100644 src/test/java/homework_5/math_power/utils/Constants.java diff --git a/src/main/java/homework_5/math_power/Main.java b/src/main/java/homework_5/math_power/Main.java new file mode 100644 index 00000000..01b02e57 --- /dev/null +++ b/src/main/java/homework_5/math_power/Main.java @@ -0,0 +1,8 @@ +package homework_5.math_power; + +public class Main { + + public static void main(String[] args) { + new PowerOfNumber().run(args); + } +} diff --git a/src/main/java/homework_5/math_power/MathPower.java b/src/main/java/homework_5/math_power/MathPower.java deleted file mode 100644 index 821cdb49..00000000 --- a/src/main/java/homework_5/math_power/MathPower.java +++ /dev/null @@ -1,11 +0,0 @@ -package homework_5.math_power; - -public class MathPower { - - public static double pow(double value, int powValue) { - if (powValue < 0) { - return 1 / pow(value, - powValue); - } - return powValue == 1 ? value : value * pow(value, powValue - 1); - } -} diff --git a/src/main/java/homework_5/math_power/PowerOfNumber.java b/src/main/java/homework_5/math_power/PowerOfNumber.java new file mode 100644 index 00000000..b1d8b963 --- /dev/null +++ b/src/main/java/homework_5/math_power/PowerOfNumber.java @@ -0,0 +1,23 @@ +package homework_5.math_power; + +import static homework_5.math_power.utils.Constants.ERROR_MESSAGE; +import static homework_5.math_power.utils.Utils.isValid; +import static homework_5.math_power.utils.Utils.printMessage; + +public class PowerOfNumber { + + public void run(String[] args) { + if (isValid(args)) { + printMessage(String.valueOf(pow(Integer.parseInt(args[0]), Integer.parseInt(args[1])))); + } else { + printMessage(ERROR_MESSAGE); + } + } + + private long pow(int value, int powValue) { + if (powValue == 0) { + return 1; + } + return powValue == 1 ? value : value * pow(value, powValue - 1); + } +} diff --git a/src/main/java/homework_5/math_power/utils/Constants.java b/src/main/java/homework_5/math_power/utils/Constants.java new file mode 100644 index 00000000..403f03fa --- /dev/null +++ b/src/main/java/homework_5/math_power/utils/Constants.java @@ -0,0 +1,5 @@ +package homework_5.math_power.utils; + +public class Constants { + public static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; +} diff --git a/src/main/java/homework_5/math_power/utils/Utils.java b/src/main/java/homework_5/math_power/utils/Utils.java new file mode 100644 index 00000000..6b9df232 --- /dev/null +++ b/src/main/java/homework_5/math_power/utils/Utils.java @@ -0,0 +1,16 @@ +package homework_5.math_power.utils; + +public class Utils { + + public static boolean isValid(String[] args) throws NumberFormatException { + try { + return args.length == 2 && Integer.parseInt(args[0]) >= 0 && Integer.parseInt(args[1]) >= 0; + } catch (NumberFormatException e) { + return false; + } + } + + public static void printMessage(String text) { + System.out.print(text); + } +} diff --git a/src/test/java/homework_5/math_power/MathPowerTest.java b/src/test/java/homework_5/math_power/MathPowerTest.java deleted file mode 100644 index 6dc8c4e6..00000000 --- a/src/test/java/homework_5/math_power/MathPowerTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package homework_5.math_power; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class MathPowerTest { - - @Test - void test_value2_toPowOf_5() { - assertEquals(Math.pow(2, 5), MathPower.pow(2, 5)); - } - - @Test - void test_value18_toPowOf_7() { - assertEquals(Math.pow(18, 7), MathPower.pow(18, 7)); - } - - @Test - void test_value21_toPowOf_10() { - assertEquals(Math.pow(21, 10), MathPower.pow(21, 10)); - } - - @Test - void test_valueNegative4_toPowOf_5() { - assertEquals(Math.pow(-4, 5), MathPower.pow(-4, 5)); - } - - @Test - void test_value1d3_toPowOf_8() { - assertEquals(Math.pow(2.3, 8), MathPower.pow(2.3, 8)); - } - - @Test - void test_value2d3_toPowOf_negative7() { - assertEquals(Math.pow(2.3, -7), MathPower.pow(2.3, -7)); - } - - @Test - void test_value5_toPowOf_0() { - assertEquals(Math.pow(5, 0), MathPower.pow(5, 0)); - } - -} diff --git a/src/test/java/homework_5/math_power/PowerOfNumberTest.java b/src/test/java/homework_5/math_power/PowerOfNumberTest.java new file mode 100644 index 00000000..639a259d --- /dev/null +++ b/src/test/java/homework_5/math_power/PowerOfNumberTest.java @@ -0,0 +1,82 @@ +package homework_5.math_power; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_5.math_power.utils.Constants.ERROR_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PowerOfNumberTest extends UnitBase { + private final PowerOfNumber powerOfNumber = new PowerOfNumber(); + + @Test + void test_valuesInvalidAmount_thenGetErrorMessage() { + String[] args = {"2", "1", "4"}; + powerOfNumber.run(args); + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void test_valuesNotNumber_thenGetErrorMessage() { + String[] args = {"2", "s"}; + powerOfNumber.run(args); + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void test_valuesNegativeNumber_thenGetErrorMessage() { + String[] args = {"-2", "5"}; + powerOfNumber.run(args); + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void test_valuesDoubleNumber_thenGetErrorMessage() { + String[] args = {"2.5", "5"}; + powerOfNumber.run(args); + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void test_values2_2_thenGet4() { + String[] args = {"2", "2"}; + powerOfNumber.run(args); + assertEquals("4", getOutput()); + } + + @Test + void test_values2_1_thenGet2() { + String[] args = {"2", "1"}; + powerOfNumber.run(args); + assertEquals("2", getOutput()); + } + + @Test + void test_values2_0_thenGet1() { + String[] args = {"2", "0"}; + powerOfNumber.run(args); + assertEquals("1", getOutput()); + } + + @Test + void test_values0_2_thenGet0() { + String[] args = {"0", "2"}; + powerOfNumber.run(args); + assertEquals("0", getOutput()); + } + + @Test + void test_values13_18_thenEqualsMathPow13_18() { + String[] args = {"10", "18"}; + powerOfNumber.run(args); + assertEquals(String.valueOf((long) Math.pow(10, 18)), getOutput()); + } + + @Test + void test_values5_0_thenEqualsMathPow5_0() { + String[] args = {"5", "0"}; + powerOfNumber.run(args); + assertEquals(String.valueOf((int) Math.pow(5, 0)), getOutput()); + } + +} diff --git a/src/test/java/homework_5/math_power/utils/Constants.java b/src/test/java/homework_5/math_power/utils/Constants.java new file mode 100644 index 00000000..403f03fa --- /dev/null +++ b/src/test/java/homework_5/math_power/utils/Constants.java @@ -0,0 +1,5 @@ +package homework_5.math_power.utils; + +public class Constants { + public static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; +} From 5de585ebbe3fe4f5e8e21ae1b0fca41fc7cc8fda Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 19 Aug 2021 14:24:30 +0300 Subject: [PATCH 52/80] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 69bb85fa..08e3d6ba 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ | HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_file_reader) [CustomFileReader Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_file_reader) | The app that reads data from the file and prints it to the console without dots and commas | | HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton) [Singleton Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | | HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation) [Custom Annotation Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | -| HW5 | [Math Power Recursion](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [MathPowerTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | Class MathPow with method pow implemented via recursion | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [PowerOfNumberTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | PowerOfNumber App with method pow implemented via recursion | [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file From 22cf66f819ca9dfcd275435a44ea0adcc0654935 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 19 Aug 2021 15:50:18 +0300 Subject: [PATCH 53/80] add hw5 custom_regex_matcher --- .../CustomRegexMatcher.java | 27 ++++++++++ .../homework_5/custom_regex_matcher/Main.java | 9 ++++ .../CustomRegexMatcherTest.java | 53 +++++++++++++++++++ .../custom_regex_matcher/utils/Constants.java | 5 ++ 4 files changed, 94 insertions(+) create mode 100644 src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java create mode 100644 src/main/java/homework_5/custom_regex_matcher/Main.java create mode 100644 src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java create mode 100644 src/test/java/homework_5/custom_regex_matcher/utils/Constants.java diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..66ff171f --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,27 @@ +package homework_5.custom_regex_matcher; + +import java.util.regex.Pattern; + +import static java.lang.System.lineSeparator; + +public class CustomRegexMatcher { + private static final String CUSTOM_REGEX = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}:\\d+?[zZ]\\s*–\\s*\\[.*]\\s*-\\s*.*"; + public static final String ERROR_MESSAGE = "No arguments have been found"; + + public void run(String[] args) { + if (args.length < 1) { + printMessage(ERROR_MESSAGE); + } + for (String s : args) { + printMessage(isMatching(s) + lineSeparator()); + } + } + + private boolean isMatching(String str) { + return Pattern.matches(CUSTOM_REGEX, str); + } + + private void printMessage(String text) { + System.out.print(text); + } +} \ No newline at end of file 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..5462ced7 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,9 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + //The example of an argument matching hardcoded regex: "2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l" + new CustomRegexMatcher().run(args); + } +} 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..76a3a6f7 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,53 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_5.custom_regex_matcher.utils.Constants.ERROR_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomRegexMatcherTest extends UnitBase { + private final CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); + + @Test + void test_noArgs_thenGetErrorMessage() { + String[] args = {}; + customRegexMatcher.run(args); + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void test_ValidArg_thenGetTrue() { + String[] args = {"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l"}; + customRegexMatcher.run(args); + assertEquals("true", getOutput()); + } + + @Test + void test_ValidArgs_thenGetTrue() { + String[] args = {"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l", + "2021-02-09T18:18:23:081Z – [username10] - wanna top up 66l", + "2021-02-09T18:18:27:941Z – [username7] - wanna top up 148l"}; + customRegexMatcher.run(args); + assertEquals("true\ntrue\ntrue", getOutput()); + } + + @Test + void test_ValidArgsAndInvalidArgs_thenGetTrueFalseTrue() { + String[] args = {"2021-02-09T18:18:30:557Z – [username7] - wanna top up 173l", + "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", + "2021-02-09T18:20:27:448Z – [username6] - wanna scoop 21l"}; + customRegexMatcher.run(args); + assertEquals("true\nfalse\ntrue", getOutput()); + } + + @Test + void test_InvalidArgs_thenGetFalse() { + String[] args = {"2021-0209T18:18:30:557Z – [username7] - wanna top up 173l", + "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", + "Just a string"}; + customRegexMatcher.run(args); + assertEquals("false\nfalse\nfalse", getOutput()); + } + +} diff --git a/src/test/java/homework_5/custom_regex_matcher/utils/Constants.java b/src/test/java/homework_5/custom_regex_matcher/utils/Constants.java new file mode 100644 index 00000000..ad9c5947 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/utils/Constants.java @@ -0,0 +1,5 @@ +package homework_5.custom_regex_matcher.utils; + +public class Constants { + public static final String ERROR_MESSAGE = "No arguments have been found"; +} From 6d6b1e017ab636c8ea1ebda0a518208f59d11467 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 19 Aug 2021 15:54:09 +0300 Subject: [PATCH 54/80] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 08e3d6ba..c3f0b79f 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,6 @@ | HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton) [Singleton Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | | HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation) [Custom Annotation Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [PowerOfNumberTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | PowerOfNumber App with method pow implemented via recursion | - +| HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/custom_regex_matcher) [CustomRegexMatcherTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/custom_regex_matcher) | The App checks whether the arguments match the hardcoded regex | [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file From dd2cc57f17bb217e53a00e765c3d86f23e7c987b Mon Sep 17 00:00:00 2001 From: rlrio Date: Fri, 20 Aug 2021 22:58:31 +0300 Subject: [PATCH 55/80] refactor hw2 and hw5 --- build.gradle | 1 + .../pyramid_printer/PyramidPrinter.java | 6 +- ...ants.java => PyramidPrinterConstants.java} | 2 +- .../random_chars_table/RandomCharsTable.java | 10 +- ...ts.java => RandomCharsTableConstants.java} | 2 +- ...{Utils.java => RandomCharsTableUtils.java} | 4 +- .../java/homework_2/traffic_light/Main.java | 2 +- .../traffic_light/TrafficLight.java | 20 ++-- .../traffic_light/TrafficLightExtraMode.java | 14 +-- ...stants.java => TrafficLightConstants.java} | 2 +- .../{Utils.java => TrafficLightUtils.java} | 4 +- .../homework_5/math_power/PowerOfNumber.java | 9 +- ...tants.java => PowerOfNumberConstants.java} | 2 +- ...Utils.java => PowerOfNumberValidator.java} | 6 +- .../pyramid_printer/PyramidPrinterTest.java | 4 +- .../RandomCharsTableTest.java | 8 +- .../traffic_light/TrafficLightTest.java | 14 +-- ...Constants.java => Homework2Constants.java} | 2 +- .../CustomRegexMatcherTest.java | 64 ++++------- ....java => CustomRegexMatcherConstants.java} | 2 +- .../math_power/PowerOfNumberTest.java | 108 ++++++------------ ...tants.java => PowerOfNumberConstants.java} | 2 +- 22 files changed, 121 insertions(+), 167 deletions(-) rename src/main/java/homework_2/pyramid_printer/utils/{Constants.java => PyramidPrinterConstants.java} (86%) rename src/main/java/homework_2/random_chars_table/utils/{Constants.java => RandomCharsTableConstants.java} (90%) rename src/main/java/homework_2/random_chars_table/utils/{Utils.java => RandomCharsTableUtils.java} (82%) rename src/main/java/homework_2/traffic_light/utils/{Constants.java => TrafficLightConstants.java} (96%) rename src/main/java/homework_2/traffic_light/utils/{Utils.java => TrafficLightUtils.java} (84%) rename src/main/java/homework_5/math_power/utils/{Constants.java => PowerOfNumberConstants.java} (74%) rename src/main/java/homework_5/math_power/utils/{Utils.java => PowerOfNumberValidator.java} (74%) rename src/test/java/homework_2/utils/{Constants.java => Homework2Constants.java} (97%) rename src/test/java/homework_5/custom_regex_matcher/utils/{Constants.java => CustomRegexMatcherConstants.java} (72%) rename src/test/java/homework_5/math_power/utils/{Constants.java => PowerOfNumberConstants.java} (74%) diff --git a/build.gradle b/build.gradle index b91dc843..522c2e14 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testCompile 'org.junit.jupiter:junit-jupiter-params:5.7.0' } test { diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index f9eea6b9..3026e9a1 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -6,9 +6,9 @@ import java.io.IOException; import java.io.InputStreamReader; -import static homework_2.pyramid_printer.utils.Constants.ERROR_MESSAGE; -import static homework_2.pyramid_printer.utils.Constants.INFO_MESSAGE; -import static homework_2.pyramid_printer.utils.Constants.LETTER; +import static homework_2.pyramid_printer.utils.PyramidPrinterConstants.ERROR_MESSAGE; +import static homework_2.pyramid_printer.utils.PyramidPrinterConstants.INFO_MESSAGE; +import static homework_2.pyramid_printer.utils.PyramidPrinterConstants.LETTER; public class PyramidPrinter { diff --git a/src/main/java/homework_2/pyramid_printer/utils/Constants.java b/src/main/java/homework_2/pyramid_printer/utils/PyramidPrinterConstants.java similarity index 86% rename from src/main/java/homework_2/pyramid_printer/utils/Constants.java rename to src/main/java/homework_2/pyramid_printer/utils/PyramidPrinterConstants.java index 80a0f5b2..0ac0db19 100644 --- a/src/main/java/homework_2/pyramid_printer/utils/Constants.java +++ b/src/main/java/homework_2/pyramid_printer/utils/PyramidPrinterConstants.java @@ -1,6 +1,6 @@ package homework_2.pyramid_printer.utils; -public class Constants { +public final class PyramidPrinterConstants { public static final String INFO_MESSAGE = "Please enter a positive integer for rows"; public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; public static final String LETTER = "x"; diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java index 9c5a0ef5..aac2cd8c 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -6,11 +6,11 @@ import java.util.Set; import java.util.concurrent.ThreadLocalRandom; -import static homework_2.random_chars_table.utils.Constants.ERROR_MESSAGE; -import static homework_2.random_chars_table.utils.Constants.MAX_CHAR; -import static homework_2.random_chars_table.utils.Constants.MIN_CHAR; -import static homework_2.random_chars_table.utils.Utils.getData; -import static homework_2.random_chars_table.utils.Utils.printMessage; +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.MAX_CHAR; +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.MIN_CHAR; +import static homework_2.random_chars_table.utils.RandomCharsTableUtils.getData; +import static homework_2.random_chars_table.utils.RandomCharsTableUtils.printMessage; import static java.lang.System.lineSeparator; public class RandomCharsTable { diff --git a/src/main/java/homework_2/random_chars_table/utils/Constants.java b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableConstants.java similarity index 90% rename from src/main/java/homework_2/random_chars_table/utils/Constants.java rename to src/main/java/homework_2/random_chars_table/utils/RandomCharsTableConstants.java index 82a64dc5..cc58d02a 100644 --- a/src/main/java/homework_2/random_chars_table/utils/Constants.java +++ b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableConstants.java @@ -1,6 +1,6 @@ package homework_2.random_chars_table.utils; -public class Constants { +public final class RandomCharsTableConstants { public static final String INFO_MESSAGE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; public static final int MAX_CHAR = 90; diff --git a/src/main/java/homework_2/random_chars_table/utils/Utils.java b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableUtils.java similarity index 82% rename from src/main/java/homework_2/random_chars_table/utils/Utils.java rename to src/main/java/homework_2/random_chars_table/utils/RandomCharsTableUtils.java index 5f3a1422..843d9d2b 100644 --- a/src/main/java/homework_2/random_chars_table/utils/Utils.java +++ b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableUtils.java @@ -6,10 +6,10 @@ import java.io.IOException; import java.io.InputStreamReader; -import static homework_2.random_chars_table.utils.Constants.INFO_MESSAGE; +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.INFO_MESSAGE; -public class Utils { +public final class RandomCharsTableUtils { public static void printMessage(String text) { System.out.print(text); } diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index e4b7e39f..bee35a2c 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -1,6 +1,6 @@ package homework_2.traffic_light; -import static homework_2.traffic_light.utils.Utils.isExtraMode; +import static homework_2.traffic_light.utils.TrafficLightUtils.isExtraMode; public class Main { public static void main(String[] args) { diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index 01791d59..76b3c9de 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -2,16 +2,16 @@ import homework_2.traffic_light.exception.TrafficLightException; -import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; -import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.utils.Constants.INFO_MESSAGE; -import static homework_2.traffic_light.utils.Constants.LIGHT_GREEN_MESSAGE; -import static homework_2.traffic_light.utils.Constants.LIGHT_RED_MESSAGE; -import static homework_2.traffic_light.utils.Constants.LIGHT_YELLOW_MESSAGE; -import static homework_2.traffic_light.utils.Constants.SECONDS_IN_DAY; -import static homework_2.traffic_light.utils.Constants.SECONDS_IN_MINUTE; -import static homework_2.traffic_light.utils.Utils.getData; -import static homework_2.traffic_light.utils.Utils.printMessage; +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.TrafficLightConstants.INFO_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.LIGHT_GREEN_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.LIGHT_RED_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.LIGHT_YELLOW_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_DAY; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_MINUTE; +import static homework_2.traffic_light.utils.TrafficLightUtils.getData; +import static homework_2.traffic_light.utils.TrafficLightUtils.printMessage; public class TrafficLight { diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java index dbd24344..438f1202 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -2,13 +2,13 @@ import homework_2.traffic_light.exception.TrafficLightException; -import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; -import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT; -import static homework_2.traffic_light.utils.Constants.INFO_MESSAGE_TO_EXTRA_MODE; -import static homework_2.traffic_light.utils.Constants.SECONDS_IN_HOUR; -import static homework_2.traffic_light.utils.Constants.SECONDS_IN_MINUTE; -import static homework_2.traffic_light.utils.Utils.getData; -import static homework_2.traffic_light.utils.Utils.printMessage; +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.TrafficLightConstants.INFO_MESSAGE_TO_EXTRA_MODE; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_HOUR; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_MINUTE; +import static homework_2.traffic_light.utils.TrafficLightUtils.getData; +import static homework_2.traffic_light.utils.TrafficLightUtils.printMessage; public class TrafficLightExtraMode extends TrafficLight { diff --git a/src/main/java/homework_2/traffic_light/utils/Constants.java b/src/main/java/homework_2/traffic_light/utils/TrafficLightConstants.java similarity index 96% rename from src/main/java/homework_2/traffic_light/utils/Constants.java rename to src/main/java/homework_2/traffic_light/utils/TrafficLightConstants.java index b38137ee..8c490f51 100644 --- a/src/main/java/homework_2/traffic_light/utils/Constants.java +++ b/src/main/java/homework_2/traffic_light/utils/TrafficLightConstants.java @@ -1,6 +1,6 @@ package homework_2.traffic_light.utils; -public class Constants { +public final class TrafficLightConstants { public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; public static final String INFO_MESSAGE = "Hi! This is your guide to cross the road blindly!\n" + "You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + diff --git a/src/main/java/homework_2/traffic_light/utils/Utils.java b/src/main/java/homework_2/traffic_light/utils/TrafficLightUtils.java similarity index 84% rename from src/main/java/homework_2/traffic_light/utils/Utils.java rename to src/main/java/homework_2/traffic_light/utils/TrafficLightUtils.java index 8ecb2c0f..22435021 100644 --- a/src/main/java/homework_2/traffic_light/utils/Utils.java +++ b/src/main/java/homework_2/traffic_light/utils/TrafficLightUtils.java @@ -6,9 +6,9 @@ import java.io.IOException; import java.io.InputStreamReader; -import static homework_2.traffic_light.utils.Constants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE; -public class Utils { +public final class TrafficLightUtils { public static void printMessage(String text) { System.out.print(text); diff --git a/src/main/java/homework_5/math_power/PowerOfNumber.java b/src/main/java/homework_5/math_power/PowerOfNumber.java index b1d8b963..e0a531c7 100644 --- a/src/main/java/homework_5/math_power/PowerOfNumber.java +++ b/src/main/java/homework_5/math_power/PowerOfNumber.java @@ -1,8 +1,7 @@ package homework_5.math_power; -import static homework_5.math_power.utils.Constants.ERROR_MESSAGE; -import static homework_5.math_power.utils.Utils.isValid; -import static homework_5.math_power.utils.Utils.printMessage; +import static homework_5.math_power.utils.PowerOfNumberConstants.ERROR_MESSAGE; +import static homework_5.math_power.utils.PowerOfNumberValidator.isValid; public class PowerOfNumber { @@ -20,4 +19,8 @@ private long pow(int value, int powValue) { } return powValue == 1 ? value : value * pow(value, powValue - 1); } + + public static void printMessage(String text) { + System.out.print(text); + } } diff --git a/src/main/java/homework_5/math_power/utils/Constants.java b/src/main/java/homework_5/math_power/utils/PowerOfNumberConstants.java similarity index 74% rename from src/main/java/homework_5/math_power/utils/Constants.java rename to src/main/java/homework_5/math_power/utils/PowerOfNumberConstants.java index 403f03fa..4e9e570c 100644 --- a/src/main/java/homework_5/math_power/utils/Constants.java +++ b/src/main/java/homework_5/math_power/utils/PowerOfNumberConstants.java @@ -1,5 +1,5 @@ package homework_5.math_power.utils; -public class Constants { +public final class PowerOfNumberConstants { public static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; } diff --git a/src/main/java/homework_5/math_power/utils/Utils.java b/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java similarity index 74% rename from src/main/java/homework_5/math_power/utils/Utils.java rename to src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java index 6b9df232..5c04af1e 100644 --- a/src/main/java/homework_5/math_power/utils/Utils.java +++ b/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java @@ -1,6 +1,6 @@ package homework_5.math_power.utils; -public class Utils { +public final class PowerOfNumberValidator { public static boolean isValid(String[] args) throws NumberFormatException { try { @@ -9,8 +9,4 @@ public static boolean isValid(String[] args) throws NumberFormatException { return false; } } - - public static void printMessage(String text) { - System.out.print(text); - } } diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java index ccec51d9..4b25c514 100644 --- a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -3,8 +3,8 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static homework_2.utils.Constants.ERROR_MESSAGE_PYRAMID_PRINTER; -import static homework_2.utils.Constants.INFO_MESSAGE_PYRAMID_PRINTER; +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_PYRAMID_PRINTER; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_PYRAMID_PRINTER; import static org.junit.jupiter.api.Assertions.assertEquals; public class PyramidPrinterTest extends UnitBase { diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java index f958f54b..c13ec7c6 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -7,10 +7,10 @@ import java.util.Arrays; import java.util.List; -import static homework_2.utils.Constants.ERROR_MESSAGE_RANDOM_CHARS_TABLE; -import static homework_2.utils.Constants.INFO_MESSAGE_RANDOM_CHARS_TABLE; -import static homework_2.utils.Constants.MAX_CHAR; -import static homework_2.utils.Constants.MIN_CHAR; +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_RANDOM_CHARS_TABLE; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_RANDOM_CHARS_TABLE; +import static homework_2.utils.Homework2Constants.MAX_CHAR; +import static homework_2.utils.Homework2Constants.MIN_CHAR; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java index 62faa79b..6665f714 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -3,13 +3,13 @@ import base.UnitBase; import org.junit.jupiter.api.Test; -import static homework_2.utils.Constants.ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT; -import static homework_2.utils.Constants.ERROR_MESSAGE_TRAFFIC_LIGHT; -import static homework_2.utils.Constants.GREEN_MESSAGE_TRAFFIC_LIGHT; -import static homework_2.utils.Constants.INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT; -import static homework_2.utils.Constants.INFO_MESSAGE_TRAFFIC_LIGHT; -import static homework_2.utils.Constants.RED_MESSAGE_TRAFFIC_LIGHT; -import static homework_2.utils.Constants.YELLOW_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.GREEN_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.RED_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.YELLOW_MESSAGE_TRAFFIC_LIGHT; import static org.junit.jupiter.api.Assertions.assertEquals; public class TrafficLightTest extends UnitBase { diff --git a/src/test/java/homework_2/utils/Constants.java b/src/test/java/homework_2/utils/Homework2Constants.java similarity index 97% rename from src/test/java/homework_2/utils/Constants.java rename to src/test/java/homework_2/utils/Homework2Constants.java index 1ac0ee95..c77ed643 100644 --- a/src/test/java/homework_2/utils/Constants.java +++ b/src/test/java/homework_2/utils/Homework2Constants.java @@ -1,6 +1,6 @@ package homework_2.utils; -public class Constants { +public final class Homework2Constants { public static final String ERROR_MESSAGE_TRAFFIC_LIGHT = "Only 1 non-negative integer is allowed as passed parameter"; public static final String INFO_MESSAGE_TRAFFIC_LIGHT = "Hi! This is your guide to cross the road blindly!\n" + "You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java index 76a3a6f7..834037a2 100644 --- a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -1,53 +1,39 @@ package homework_5.custom_regex_matcher; import base.UnitBase; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -import static homework_5.custom_regex_matcher.utils.Constants.ERROR_MESSAGE; +import java.util.stream.Stream; + +import static homework_5.custom_regex_matcher.utils.CustomRegexMatcherConstants.ERROR_MESSAGE; import static org.junit.jupiter.api.Assertions.assertEquals; public class CustomRegexMatcherTest extends UnitBase { private final CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); - @Test - void test_noArgs_thenGetErrorMessage() { - String[] args = {}; - customRegexMatcher.run(args); - assertEquals(ERROR_MESSAGE, getOutput()); - } - - @Test - void test_ValidArg_thenGetTrue() { - String[] args = {"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l"}; - customRegexMatcher.run(args); - assertEquals("true", getOutput()); - } - - @Test - void test_ValidArgs_thenGetTrue() { - String[] args = {"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l", - "2021-02-09T18:18:23:081Z – [username10] - wanna top up 66l", - "2021-02-09T18:18:27:941Z – [username7] - wanna top up 148l"}; - customRegexMatcher.run(args); - assertEquals("true\ntrue\ntrue", getOutput()); - } - - @Test - void test_ValidArgsAndInvalidArgs_thenGetTrueFalseTrue() { - String[] args = {"2021-02-09T18:18:30:557Z – [username7] - wanna top up 173l", - "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", - "2021-02-09T18:20:27:448Z – [username6] - wanna scoop 21l"}; - customRegexMatcher.run(args); - assertEquals("true\nfalse\ntrue", getOutput()); + @ParameterizedTest + @MethodSource("testCases") + void test(final String[] input, final String expected) { + customRegexMatcher.run(input); + assertEquals(expected, getOutput()); } - @Test - void test_InvalidArgs_thenGetFalse() { - String[] args = {"2021-0209T18:18:30:557Z – [username7] - wanna top up 173l", - "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", - "Just a string"}; - customRegexMatcher.run(args); - assertEquals("false\nfalse\nfalse", getOutput()); + static Stream testCases() { + return Stream.of( + Arguments.of(new String[]{}, ERROR_MESSAGE), + Arguments.of(new String[]{"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l"}, "true"), + Arguments.of(new String[]{"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l", + "2021-02-09T18:18:23:081Z – [username10] - wanna top up 66l", + "2021-02-09T18:18:27:941Z – [username7] - wanna top up 148l"}, "true\ntrue\ntrue"), + Arguments.of(new String[]{"2021-02-09T18:18:30:557Z – [username7] - wanna top up 173l", + "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", + "2021-02-09T18:20:27:448Z – [username6] - wanna scoop 21l"}, "true\nfalse\ntrue"), + Arguments.of(new String[]{"2021-0209T18:18:30:557Z – [username7] - wanna top up 173l", + "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", + "Just a string"}, "false\nfalse\nfalse") + ); } } diff --git a/src/test/java/homework_5/custom_regex_matcher/utils/Constants.java b/src/test/java/homework_5/custom_regex_matcher/utils/CustomRegexMatcherConstants.java similarity index 72% rename from src/test/java/homework_5/custom_regex_matcher/utils/Constants.java rename to src/test/java/homework_5/custom_regex_matcher/utils/CustomRegexMatcherConstants.java index ad9c5947..0190c38b 100644 --- a/src/test/java/homework_5/custom_regex_matcher/utils/Constants.java +++ b/src/test/java/homework_5/custom_regex_matcher/utils/CustomRegexMatcherConstants.java @@ -1,5 +1,5 @@ package homework_5.custom_regex_matcher.utils; -public class Constants { +public final class CustomRegexMatcherConstants { public static final String ERROR_MESSAGE = "No arguments have been found"; } diff --git a/src/test/java/homework_5/math_power/PowerOfNumberTest.java b/src/test/java/homework_5/math_power/PowerOfNumberTest.java index 639a259d..fa2b23dd 100644 --- a/src/test/java/homework_5/math_power/PowerOfNumberTest.java +++ b/src/test/java/homework_5/math_power/PowerOfNumberTest.java @@ -1,82 +1,50 @@ package homework_5.math_power; import base.UnitBase; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -import static homework_5.math_power.utils.Constants.ERROR_MESSAGE; +import java.util.stream.Stream; + +import static homework_5.math_power.utils.PowerOfNumberConstants.ERROR_MESSAGE; import static org.junit.jupiter.api.Assertions.assertEquals; public class PowerOfNumberTest extends UnitBase { private final PowerOfNumber powerOfNumber = new PowerOfNumber(); - @Test - void test_valuesInvalidAmount_thenGetErrorMessage() { - String[] args = {"2", "1", "4"}; - powerOfNumber.run(args); - assertEquals(ERROR_MESSAGE, getOutput()); - } - - @Test - void test_valuesNotNumber_thenGetErrorMessage() { - String[] args = {"2", "s"}; - powerOfNumber.run(args); - assertEquals(ERROR_MESSAGE, getOutput()); - } - - @Test - void test_valuesNegativeNumber_thenGetErrorMessage() { - String[] args = {"-2", "5"}; - powerOfNumber.run(args); - assertEquals(ERROR_MESSAGE, getOutput()); - } - - @Test - void test_valuesDoubleNumber_thenGetErrorMessage() { - String[] args = {"2.5", "5"}; - powerOfNumber.run(args); - assertEquals(ERROR_MESSAGE, getOutput()); - } - - @Test - void test_values2_2_thenGet4() { - String[] args = {"2", "2"}; - powerOfNumber.run(args); - assertEquals("4", getOutput()); - } - - @Test - void test_values2_1_thenGet2() { - String[] args = {"2", "1"}; - powerOfNumber.run(args); - assertEquals("2", getOutput()); - } - - @Test - void test_values2_0_thenGet1() { - String[] args = {"2", "0"}; - powerOfNumber.run(args); - assertEquals("1", getOutput()); - } - - @Test - void test_values0_2_thenGet0() { - String[] args = {"0", "2"}; - powerOfNumber.run(args); - assertEquals("0", getOutput()); - } - - @Test - void test_values13_18_thenEqualsMathPow13_18() { - String[] args = {"10", "18"}; - powerOfNumber.run(args); - assertEquals(String.valueOf((long) Math.pow(10, 18)), getOutput()); - } - - @Test - void test_values5_0_thenEqualsMathPow5_0() { - String[] args = {"5", "0"}; - powerOfNumber.run(args); - assertEquals(String.valueOf((int) Math.pow(5, 0)), getOutput()); + @ParameterizedTest + @MethodSource("testCasesGetErrorMessage") + void testGetErrorMessage(final String[] input, final String expected) { + powerOfNumber.run(input); + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCasesGetSuccessResult") + void testGetSuccessResult(final String[] input, final String expected) { + powerOfNumber.run(input); + assertEquals(expected, getOutput()); + } + + static Stream testCasesGetErrorMessage() { + return Stream.of( + Arguments.of(new String[]{"2", "1", "4"}, ERROR_MESSAGE), + Arguments.of(new String[]{"2", "s"}, ERROR_MESSAGE), + Arguments.of(new String[]{"-2", "5"}, ERROR_MESSAGE), + Arguments.of(new String[]{"2.5", "5"}, ERROR_MESSAGE) + ); + } + + static Stream testCasesGetSuccessResult() { + return Stream.of( + Arguments.of(new String[]{"2", "2"}, "4"), + Arguments.of(new String[]{"2", "1"}, "2"), + Arguments.of(new String[]{"2", "0"}, "1"), + Arguments.of(new String[]{"0", "2"}, "0"), + Arguments.of(new String[]{"10", "18"}, String.valueOf((long) Math.pow(10, 18))), + Arguments.of(new String[]{"5", "0"}, String.valueOf((long) Math.pow(5, 0))) + ); } } diff --git a/src/test/java/homework_5/math_power/utils/Constants.java b/src/test/java/homework_5/math_power/utils/PowerOfNumberConstants.java similarity index 74% rename from src/test/java/homework_5/math_power/utils/Constants.java rename to src/test/java/homework_5/math_power/utils/PowerOfNumberConstants.java index 403f03fa..4e9e570c 100644 --- a/src/test/java/homework_5/math_power/utils/Constants.java +++ b/src/test/java/homework_5/math_power/utils/PowerOfNumberConstants.java @@ -1,5 +1,5 @@ package homework_5.math_power.utils; -public class Constants { +public final class PowerOfNumberConstants { public static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; } From 7a70ee156474fefce55bebeefc4c636735dd4304 Mon Sep 17 00:00:00 2001 From: rlrio Date: Fri, 20 Aug 2021 23:01:10 +0300 Subject: [PATCH 56/80] refactor hw2 and hw5 --- src/main/java/homework_5/math_power/PowerOfNumber.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_5/math_power/PowerOfNumber.java b/src/main/java/homework_5/math_power/PowerOfNumber.java index e0a531c7..803dadcf 100644 --- a/src/main/java/homework_5/math_power/PowerOfNumber.java +++ b/src/main/java/homework_5/math_power/PowerOfNumber.java @@ -20,7 +20,7 @@ private long pow(int value, int powValue) { return powValue == 1 ? value : value * pow(value, powValue - 1); } - public static void printMessage(String text) { + private static void printMessage(String text) { System.out.print(text); } } From aa15994d1dea0767286c08c5f0e4b09d0dbb93e4 Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 26 Aug 2021 16:34:35 +0300 Subject: [PATCH 57/80] refactor hw5 --- .../homework_5/custom_regex_matcher/CustomRegexMatcher.java | 3 +-- .../custom_regex_matcher/CustomRegexMatcherTest.java | 3 +-- .../utils/CustomRegexMatcherConstants.java | 5 ----- 3 files changed, 2 insertions(+), 9 deletions(-) delete mode 100644 src/test/java/homework_5/custom_regex_matcher/utils/CustomRegexMatcherConstants.java diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java index 66ff171f..4cbd5879 100644 --- a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -6,11 +6,10 @@ public class CustomRegexMatcher { private static final String CUSTOM_REGEX = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}:\\d+?[zZ]\\s*–\\s*\\[.*]\\s*-\\s*.*"; - public static final String ERROR_MESSAGE = "No arguments have been found"; public void run(String[] args) { if (args.length < 1) { - printMessage(ERROR_MESSAGE); + printMessage("false"); } for (String s : args) { printMessage(isMatching(s) + lineSeparator()); diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java index 834037a2..14ccc6a1 100644 --- a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -7,7 +7,6 @@ import java.util.stream.Stream; -import static homework_5.custom_regex_matcher.utils.CustomRegexMatcherConstants.ERROR_MESSAGE; import static org.junit.jupiter.api.Assertions.assertEquals; public class CustomRegexMatcherTest extends UnitBase { @@ -22,7 +21,7 @@ void test(final String[] input, final String expected) { static Stream testCases() { return Stream.of( - Arguments.of(new String[]{}, ERROR_MESSAGE), + Arguments.of(new String[]{}, "false"), Arguments.of(new String[]{"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l"}, "true"), Arguments.of(new String[]{"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l", "2021-02-09T18:18:23:081Z – [username10] - wanna top up 66l", diff --git a/src/test/java/homework_5/custom_regex_matcher/utils/CustomRegexMatcherConstants.java b/src/test/java/homework_5/custom_regex_matcher/utils/CustomRegexMatcherConstants.java deleted file mode 100644 index 0190c38b..00000000 --- a/src/test/java/homework_5/custom_regex_matcher/utils/CustomRegexMatcherConstants.java +++ /dev/null @@ -1,5 +0,0 @@ -package homework_5.custom_regex_matcher.utils; - -public final class CustomRegexMatcherConstants { - public static final String ERROR_MESSAGE = "No arguments have been found"; -} From 2c194d30635db33a1fd33f2d3bd71db211613da3 Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 31 Aug 2021 22:28:35 +0300 Subject: [PATCH 58/80] add homework_6 --- README.md | 23 +++++++------ .../map_problems_generator/Main.java | 34 +++++++++++++++++++ .../MapProblemsGenerator.java | 5 +++ .../impl/AbstractMapProblemsGenerator.java | 30 ++++++++++++++++ .../CollidingMapProblemsGeneratorKey.java | 17 ++++++++++ .../impl/MutableMapProblemsGeneratorKey.java | 19 +++++++++++ 6 files changed, 117 insertions(+), 11 deletions(-) create mode 100644 src/main/java/homework_6/map_problems_generator/Main.java create mode 100644 src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java create mode 100644 src/main/java/homework_6/map_problems_generator/impl/AbstractMapProblemsGenerator.java create mode 100644 src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java create mode 100644 src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java diff --git a/README.md b/README.md index c3f0b79f..de65d15c 100644 --- a/README.md +++ b/README.md @@ -4,18 +4,19 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/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/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| -| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | -| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | -| HW3 | [Traffic Light Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/traffic_light) | Add unit tests for Traffic Light app | -| HW3 | [Pyramid Printer Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/pyramid_printer) | Add unit tests for Print Pyramid app| -| HW3 | [Random Chars Table Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/random_chars_table) | Add unit tests for Random Chars Table app | -| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3) [Immutable Class Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_3) | Add Immutable class | -| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_file_reader) [CustomFileReader Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_file_reader) | The app that reads data from the file and prints it to the console without dots and commas | -| HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton) [Singleton Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | -| HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation) [Custom Annotation Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | +| HW1 | [ConsolePrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [TrafficLight](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| +| HW2 | [PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | +| HW2 | [RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | +| HW3 | [TrafficLightTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/traffic_light) | Add unit tests for Traffic Light app | +| HW3 | [PyramidPrinterTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/pyramid_printer) | Add unit tests for Print Pyramid app| +| HW3 | [RandomCharsTableTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/random_chars_table) | Add unit tests for Random Chars Table app | +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3)
[ImmutableClassTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_3) | Add Immutable class | +| HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_file_reader) [CustomFileReaderTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_file_reader) | The app that reads data from the file and prints it to the console without dots and commas | +| HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton)
[SingletonTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | +| HW4 | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation)
[CustomAnnotationTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [PowerOfNumberTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | PowerOfNumber App with method pow implemented via recursion | | HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/custom_regex_matcher) [CustomRegexMatcherTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/custom_regex_matcher) | The App checks whether the arguments match the hardcoded regex | +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_6/map_problems_generator) | 1)CollidingMapProblemsGeneratorKey is the class that always creates collisions in the HashMap.
2)MutableMapProblemsGeneratorKey is the class with HashCode method that returns random value. | [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java new file mode 100644 index 00000000..b2ab05ff --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,34 @@ +package homework_6.map_problems_generator; + +import homework_6.map_problems_generator.impl.CollidingMapProblemsGeneratorKey; +import homework_6.map_problems_generator.impl.MutableMapProblemsGeneratorKey; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + + public static void main(String[] args) { + System.out.println("Testing CollidingMapProblemsGeneratorKey:"); + Map, Integer> mapWithCollidingKeys = new HashMap<>(); + MapProblemsGenerator myObject1 = new CollidingMapProblemsGeneratorKey<>(); + MapProblemsGenerator myObject2 = new CollidingMapProblemsGeneratorKey<>("2"); + System.out.println("myObject1 == myObject2 = " + (myObject1 == myObject2)); + System.out.println("myObject1.hashCode() == myObject2.hashCode() = " + (myObject1.hashCode() == myObject2.hashCode())); + mapWithCollidingKeys.put(myObject1, 1); + mapWithCollidingKeys.put(myObject2, 1); + System.out.println("mapWithCollidingKeys.size() = " + mapWithCollidingKeys.size()); + + System.out.println("\n----\n"); + + System.out.println("Testing MutableMapProblemsGeneratorKey:"); + Map, Integer> map = new HashMap<>(); + MapProblemsGenerator myObject = new MutableMapProblemsGeneratorKey<>(); + System.out.println("myObject = " + myObject); + map.put(myObject, 1); + System.out.println("map.containsKey(myObject) = " + map.containsKey(myObject)); + System.out.println("map.size() = " + map.size()); + System.out.println("Map keys:"); + map.keySet().forEach(System.out::println); + } +} 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..465170fa --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,5 @@ +package homework_6.map_problems_generator; + +public interface MapProblemsGenerator { + +} diff --git a/src/main/java/homework_6/map_problems_generator/impl/AbstractMapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/impl/AbstractMapProblemsGenerator.java new file mode 100644 index 00000000..90274fb8 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/impl/AbstractMapProblemsGenerator.java @@ -0,0 +1,30 @@ +package homework_6.map_problems_generator.impl; + +import homework_6.map_problems_generator.MapProblemsGenerator; + +import java.util.Objects; + +public abstract class AbstractMapProblemsGenerator implements MapProblemsGenerator { + private final T value; + + public AbstractMapProblemsGenerator(T value) { + this.value = value; + } + + public T getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AbstractMapProblemsGenerator that = (AbstractMapProblemsGenerator) o; + return Objects.equals(getValue(), that.getValue()); + } + + @Override + public int hashCode() { + return Objects.hash(getValue()); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java b/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java new file mode 100644 index 00000000..b751bf0d --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java @@ -0,0 +1,17 @@ +package homework_6.map_problems_generator.impl; + +public class CollidingMapProblemsGeneratorKey extends AbstractMapProblemsGenerator { + + public CollidingMapProblemsGeneratorKey() { + super(null); + } + + public CollidingMapProblemsGeneratorKey(T value) { + super(value); + } + + @Override + public int hashCode() { + return 31; + } +} diff --git a/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java b/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java new file mode 100644 index 00000000..d33c827b --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java @@ -0,0 +1,19 @@ +package homework_6.map_problems_generator.impl; + +import java.util.Random; + +public class MutableMapProblemsGeneratorKey extends AbstractMapProblemsGenerator { + + public MutableMapProblemsGeneratorKey() { + super(null); + } + + public MutableMapProblemsGeneratorKey(T value) { + super(value); + } + + @Override + public int hashCode() { + return new Random().nextInt(); + } +} \ No newline at end of file From 45bbdbe9c6d93e511c2b63f55e9bc2bcb4ccef7f Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 1 Sep 2021 08:39:27 +0300 Subject: [PATCH 59/80] add homework_6 --- src/main/java/homework_6/map_problems_generator/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java index b2ab05ff..c25dbe70 100644 --- a/src/main/java/homework_6/map_problems_generator/Main.java +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -13,8 +13,8 @@ public static void main(String[] args) { Map, Integer> mapWithCollidingKeys = new HashMap<>(); MapProblemsGenerator myObject1 = new CollidingMapProblemsGeneratorKey<>(); MapProblemsGenerator myObject2 = new CollidingMapProblemsGeneratorKey<>("2"); - System.out.println("myObject1 == myObject2 = " + (myObject1 == myObject2)); System.out.println("myObject1.hashCode() == myObject2.hashCode() = " + (myObject1.hashCode() == myObject2.hashCode())); + System.out.println("myObject1.equals(myObject2) = " + myObject1.equals(myObject2)); mapWithCollidingKeys.put(myObject1, 1); mapWithCollidingKeys.put(myObject2, 1); System.out.println("mapWithCollidingKeys.size() = " + mapWithCollidingKeys.size()); From b5cd1be4667ee09de59c87e6ee2076cac10a0bab Mon Sep 17 00:00:00 2001 From: rlrio Date: Thu, 9 Sep 2021 21:50:57 +0300 Subject: [PATCH 60/80] add homework_7 --- README.md | 1 + .../java/homework_7/KittenToCatFunction.java | 9 +++++ src/main/java/homework_7/Main.java | 13 ++++++ src/main/java/homework_7/entity/Cat.java | 34 ++++++++++++++++ src/main/java/homework_7/entity/Kitten.java | 40 +++++++++++++++++++ 5 files changed, 97 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/entity/Cat.java create mode 100644 src/main/java/homework_7/entity/Kitten.java diff --git a/README.md b/README.md index de65d15c..1ee4549b 100644 --- a/README.md +++ b/README.md @@ -18,5 +18,6 @@ | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [PowerOfNumberTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | PowerOfNumber App with method pow implemented via recursion | | HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/custom_regex_matcher) [CustomRegexMatcherTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/custom_regex_matcher) | The App checks whether the arguments match the hardcoded regex | | HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_6/map_problems_generator) | 1)CollidingMapProblemsGeneratorKey is the class that always creates collisions in the HashMap.
2)MutableMapProblemsGeneratorKey is the class with HashCode method that returns random value. | +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_7) | Custom Functional Interface KittenToCatFunction with abstract method grow(). [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..951f6092 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,9 @@ +package homework_7; + +import homework_7.entity.Cat; +import homework_7.entity.Kitten; + +@FunctionalInterface +public interface KittenToCatFunction { + C grow(K kitten); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..dc6ba0ce --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,13 @@ +package homework_7; + +import homework_7.entity.Cat; +import homework_7.entity.Kitten; + +public class Main { + + public static void main(String[] args) { + Kitten kitten = new Kitten("Kitty Tom", 1, 2); + Cat grownUpCat = kitten.grow(k -> new Cat(k.getName().replace("Kitty", "Big"), k.getAge() + 1, k.getWeight() * 2)); + System.out.println(grownUpCat); + } +} diff --git a/src/main/java/homework_7/entity/Cat.java b/src/main/java/homework_7/entity/Cat.java new file mode 100644 index 00000000..c8ae3eed --- /dev/null +++ b/src/main/java/homework_7/entity/Cat.java @@ -0,0 +1,34 @@ +package homework_7.entity; + +public class Cat { + private final String name; + private final int age; + private final int weight; + + public Cat(String name, int age, int weight) { + this.name = name; + this.age = age; + this.weight = weight; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public int getWeight() { + return weight; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + ", weight=" + weight + + '}'; + } +} diff --git a/src/main/java/homework_7/entity/Kitten.java b/src/main/java/homework_7/entity/Kitten.java new file mode 100644 index 00000000..303416bd --- /dev/null +++ b/src/main/java/homework_7/entity/Kitten.java @@ -0,0 +1,40 @@ +package homework_7.entity; + +import homework_7.KittenToCatFunction; + +public class Kitten { + private final String name; + private final int age; + private final int weight; + + public Kitten(String name, int age, int weight) { + this.name = name; + this.age = age; + this.weight = weight; + } + + public Cat grow(KittenToCatFunction function) { + return function.grow(this); + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public int getWeight() { + return weight; + } + + @Override + public String toString() { + return "Kitten{" + + "name='" + name + '\'' + + ", age=" + age + + ", weight=" + weight + + '}'; + } +} From be9b160e80ee93c09235d76be6692576bff0e864 Mon Sep 17 00:00:00 2001 From: rlrio Date: Fri, 10 Sep 2021 15:12:00 +0300 Subject: [PATCH 61/80] add raw course_project realization --- .../course_project/battleship_game/Main.java | 12 ++ .../battleship_game/model/Board.java | 136 ++++++++++++++++++ .../battleship_game/model/Cell.java | 62 ++++++++ .../battleship_game/model/CellStatus.java | 19 +++ .../battleship_game/model/Game.java | 5 + .../battleship_game/model/GameImpl.java | 88 ++++++++++++ .../battleship_game/model/GameMode.java | 7 + .../battleship_game/model/Player.java | 122 ++++++++++++++++ .../battleship_game/model/Ship.java | 59 ++++++++ .../battleship_game/model/ShipType.java | 31 ++++ .../battleship_game/utils/Constants.java | 32 +++++ .../battleship_game/utils/Validator.java | 28 ++++ .../battleship_game/view/View.java | 117 +++++++++++++++ 13 files changed, 718 insertions(+) create mode 100644 src/main/java/course_project/battleship_game/Main.java create mode 100644 src/main/java/course_project/battleship_game/model/Board.java create mode 100644 src/main/java/course_project/battleship_game/model/Cell.java create mode 100644 src/main/java/course_project/battleship_game/model/CellStatus.java create mode 100644 src/main/java/course_project/battleship_game/model/Game.java create mode 100644 src/main/java/course_project/battleship_game/model/GameImpl.java create mode 100644 src/main/java/course_project/battleship_game/model/GameMode.java create mode 100644 src/main/java/course_project/battleship_game/model/Player.java create mode 100644 src/main/java/course_project/battleship_game/model/Ship.java create mode 100644 src/main/java/course_project/battleship_game/model/ShipType.java create mode 100644 src/main/java/course_project/battleship_game/utils/Constants.java create mode 100644 src/main/java/course_project/battleship_game/utils/Validator.java create mode 100644 src/main/java/course_project/battleship_game/view/View.java diff --git a/src/main/java/course_project/battleship_game/Main.java b/src/main/java/course_project/battleship_game/Main.java new file mode 100644 index 00000000..c6cfb971 --- /dev/null +++ b/src/main/java/course_project/battleship_game/Main.java @@ -0,0 +1,12 @@ +package course_project.battleship_game; + +import course_project.battleship_game.model.Game; +import course_project.battleship_game.model.GameImpl; + +public class Main { + + public static void main(String[] args) { + Game game = new GameImpl(); + game.run(); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/battleship_game/model/Board.java b/src/main/java/course_project/battleship_game/model/Board.java new file mode 100644 index 00000000..0f240947 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Board.java @@ -0,0 +1,136 @@ +package course_project.battleship_game.model; + +import java.util.ArrayList; +import java.util.List; + +public class Board { + private static final int BOARD_SIZE = 10; + private final Cell[][] boardMatrix; + private final List shipList; + + public Board() { + this.boardMatrix = createBoard(); + this.shipList = new ArrayList<>(); + } + + public Cell[][] getBoardMatrix() { + return boardMatrix; + } + + public boolean isNoMoreAliveShipsForBoard() { + return shipList.stream().allMatch(Ship::isNotAlive); + } + + public long countRemainedShips() { + return shipList.stream().filter(ship -> !ship.isNotAlive()).count(); + } + + public boolean isCreatingShipSuccessful(Cell start, ShipType type, int direction) { + if (isShipValidForBoard(start, type, direction)) { + Ship ship = new Ship(start, type, direction); + shipList.add(ship); + addShipToBoardMatrix(ship); + markAreaAroundShip(ship); + return true; + } + return false; + } + + public boolean isMoveSuccessful(Cell cell) { + Ship shipResult = shipList.stream() + .filter(ship -> + ship.getCellsList().stream() + .anyMatch(cell1 -> cell1.equals(cell))).findFirst().orElse(null); + boolean hit = shipResult != null && shipResult.isHit(cell); + if (!hit) { + boardMatrix[cell.getY()][cell.getX()].setCellStatus(CellStatus.MISSED); + } + return hit; + } + + private Cell[][] createBoard() { + Cell[][] boardMatrix = new Cell[BOARD_SIZE][BOARD_SIZE]; + for (int y = 0; y < BOARD_SIZE; y++) { + for (int x = 0; x < BOARD_SIZE; x++) { + boardMatrix[y][x] = new Cell(x, y, CellStatus.EMPTY); + } + } + return boardMatrix; + } + + private void addShipToBoardMatrix(Ship ship) { + for (Cell cell : ship.getCellsList()) { + int x = cell.getX(); + int y = cell.getY(); + boardMatrix[y][x] = cell; + } + } + + private void markAreaAroundShip(Ship ship) { + List cells = ship.getCellsList(); + for (Cell cell : cells) { + int x = cell.getX(); + int y = cell.getY(); + if (x + 1 < BOARD_SIZE && + boardMatrix[y][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x + 1 < BOARD_SIZE && y - 1 >= 0 && + boardMatrix[y - 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y - 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x + 1 < BOARD_SIZE && y + 1 < BOARD_SIZE && + boardMatrix[y + 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y + 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && + boardMatrix[y][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && y - 1 >= 0 && + boardMatrix[y - 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y - 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && y + 1 < BOARD_SIZE && + boardMatrix[y + 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y + 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (y + 1 < BOARD_SIZE && + boardMatrix[y + 1][x].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y + 1][x].setCellStatus(CellStatus.SHIP_BORDER); + } + if (y - 1 >= 0 && + boardMatrix[y - 1][x].getCellStatus().equals(CellStatus.EMPTY)) { + boardMatrix[y - 1][x].setCellStatus(CellStatus.SHIP_BORDER); + } + } + } + + private boolean isShipValidForBoard(Cell start, ShipType type, int direction) { + if (isTypeNotEnoughInShipList(type) && isShipCellsFitBoard(start, type, direction)) { + Ship ship = new Ship(start, type, direction); + return !shipList.contains(ship); + } + return false; + } + + private boolean isShipCellsFitBoard(Cell start, ShipType type, int direction) { + Ship ship = new Ship(start, type, direction); + List cells = ship.getCellsList(); + for (Cell cell : cells) { + if (cell.getX() < 0 || cell.getY() < 0 || cell.getX() >= boardMatrix.length || + cell.getY() >= boardMatrix.length) { + return false; + } + if (!(boardMatrix[cell.getY()][cell.getX()]).getCellStatus().equals(CellStatus.EMPTY)) { + return false; + } + } + return true; + } + + private boolean isTypeNotEnoughInShipList(ShipType type) { + int count = (int) shipList.stream().filter(ship -> ship.getType().equals(type)).count(); + return count < type.getAmount(); + } +} diff --git a/src/main/java/course_project/battleship_game/model/Cell.java b/src/main/java/course_project/battleship_game/model/Cell.java new file mode 100644 index 00000000..f7e8ebc9 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Cell.java @@ -0,0 +1,62 @@ +package course_project.battleship_game.model; + +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +public class Cell { + private final int x; + private final int y; + private CellStatus status; + + public Cell(int x, int y, CellStatus status) { //change in controller + this.x = x; + this.y = y; + this.status = status; + } + + public Cell(int x, int y) { + this.x = x; + this.y = y; + } + + public static Cell generateRandomCell() { + int x = ThreadLocalRandom.current().nextInt(0, 10); + int y = ThreadLocalRandom.current().nextInt(0, 10); + return new Cell(x, y); + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public CellStatus getCellStatus() { + return status; + } + + public void setCellStatus(CellStatus status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Cell cell = (Cell) o; + return getX() == cell.getX() && + getY() == cell.getY(); + } + + @Override + public int hashCode() { + return Objects.hash(getX(), getY()); + } + + @Override + public String toString() { + return String.valueOf((char) (y + 65)) + (x + 1); + } +} diff --git a/src/main/java/course_project/battleship_game/model/CellStatus.java b/src/main/java/course_project/battleship_game/model/CellStatus.java new file mode 100644 index 00000000..bcef00f0 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/CellStatus.java @@ -0,0 +1,19 @@ +package course_project.battleship_game.model; + +public enum CellStatus { + EMPTY("\uD83C\uDF0A"), + SHIP("\uD83D\uDEA2"), + HIT("\u274C"), + SHIP_BORDER("\uD83C\uDF0A"), + MISSED("\uD83D\uDD18"); + + private final String character; + + CellStatus(String character) { + this.character = character; + } + + public String getCharacter() { + return character; + } +} \ No newline at end of file diff --git a/src/main/java/course_project/battleship_game/model/Game.java b/src/main/java/course_project/battleship_game/model/Game.java new file mode 100644 index 00000000..44a36350 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Game.java @@ -0,0 +1,5 @@ +package course_project.battleship_game.model; + +public interface Game { + void run(); +} diff --git a/src/main/java/course_project/battleship_game/model/GameImpl.java b/src/main/java/course_project/battleship_game/model/GameImpl.java new file mode 100644 index 00000000..652bdbd0 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/GameImpl.java @@ -0,0 +1,88 @@ +package course_project.battleship_game.model; + +import course_project.battleship_game.view.View; + +import java.util.concurrent.ThreadLocalRandom; + +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; +import static course_project.battleship_game.utils.Constants.PLAYER_TURN_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.PLAYER_WINNER_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.ROLLING_DICE_MESSAGE; +import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; + +public class GameImpl implements Game { + private final View view = new View(); + + @Override + public void run() { + view.printMessage(WELCOME_MESSAGE); + GameMode gameMode = view.getGameMode(); + Player[] players = createPlayers(gameMode); + rollingDiceToChooseWhoStarts(players); + Player player1 = players[0]; + Player player2 = players[1]; + player1.createFleet(view); + player2.createFleet(view); + view.printMessage(FLEETS_CREATED_MESSAGE); + boolean isGameOver = false; + while (!isGameOver) { + isGameOver = isGameOver(player1, player2, gameMode); + if (!isGameOver) { + isGameOver = isGameOver(player2, player1, gameMode); + } + } + determineWinner(player1, player2); + } + + private boolean isGameOver(Player player1, Player player2, GameMode gameMode) { + boolean isMoveSuccessful = true; + view.printMessage(String.format(PLAYER_TURN_MESSAGE_FORMAT, player1.getName())); + while (isMoveSuccessful && !isNoMoreAliveShips(player1, player2)) { + isMoveSuccessful = player1.isMoveSuccessful(player2, view); + printBoard(gameMode, player1, player2); + } + return isNoMoreAliveShips(player1, player2); + } + + private void printBoard(GameMode mode, Player player1, Player player2) { + if (mode.equals(GameMode.CVC) || !player1.getName().contains(DEFAULT_COMPUTER_NAME)) { + view.printBoardForPlayer(player1, false); + view.printBoardForPlayer(player2, true); + } + } + + private Player[] createPlayers(GameMode mode) { + Player[] players = new Player[2]; + players[0] = mode.equals(GameMode.CVC) ? new Player(DEFAULT_COMPUTER_NAME + " Mimi", 0) : + new Player(view.getPlayerName(), view.getModeToCreateFleet()); + players[1] = !mode.equals(GameMode.PVP) ? new Player(DEFAULT_COMPUTER_NAME + " Navi", 0) : + new Player(view.getPlayerName(), view.getModeToCreateFleet()); + return players; + } + + private void rollingDiceToChooseWhoStarts(Player[] players) { + view.printMessage(ROLLING_DICE_MESSAGE); + int dice = ThreadLocalRandom.current().nextInt(0, 2); + if (dice == 1) { + Player temp = players[0]; + players[0] = players[1]; + players[1] = temp; + } + view.printMessage(players[0].getName() + " will go first\n"); + } + + private boolean isNoMoreAliveShips(Player player1, Player player2) { + return player1.getBoard().isNoMoreAliveShipsForBoard() || player2.getBoard().isNoMoreAliveShipsForBoard(); + } + + private void determineWinner(Player player1, Player player2) { + if (isNoMoreAliveShips(player1, player2)) { + long player1Fleet = player1.getBoard().countRemainedShips(); + long player2Fleet = player2.getBoard().countRemainedShips(); + Player winner = player1Fleet > player2Fleet ? player1 : player2; + view.printMessage(String.format(PLAYER_WINNER_MESSAGE_FORMAT, winner.getName())); + } + } + +} diff --git a/src/main/java/course_project/battleship_game/model/GameMode.java b/src/main/java/course_project/battleship_game/model/GameMode.java new file mode 100644 index 00000000..c75bd971 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/GameMode.java @@ -0,0 +1,7 @@ +package course_project.battleship_game.model; + +public enum GameMode { + CVC, + PVC, + PVP +} diff --git a/src/main/java/course_project/battleship_game/model/Player.java b/src/main/java/course_project/battleship_game/model/Player.java new file mode 100644 index 00000000..7d368b88 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Player.java @@ -0,0 +1,122 @@ +package course_project.battleship_game.model; + +import course_project.battleship_game.view.View; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import static course_project.battleship_game.utils.Constants.CREATING_FLEET_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.CREATING_SHIP_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.FLEET_CREATED_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.HIT_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.MISSED_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.PLAYER_MOVE_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.REMAINING_AMOUNT_OF_TYPE_TO_CREATE; +import static course_project.battleship_game.utils.Constants.SAME_COORDINATE_ERROR_MESSAGE; +import static course_project.battleship_game.utils.Constants.SHIP_CREATED_MESSAGE_FORMAT; + +public class Player { + private final String name; + private final Board board; + private final int modeToCreateFleet; + private final List logOfMoves; + + public Player(String name, int modeToCreateFleet) { + this.name = name; + this.modeToCreateFleet = modeToCreateFleet; + this.board = new Board(); + this.logOfMoves = new ArrayList<>(); + } + + public Board getBoard() { + return board; + } + + public String getName() { + return name; + } + + public boolean isMoveSuccessful(Player player, View view) { + Cell cell = null; + while (cell == null || !logOfMoves.contains(cell)) { + if (this.name.contains(DEFAULT_COMPUTER_NAME)) { + cell = Cell.generateRandomCell(); + } else { + cell = view.getCell(); + } + if (!logOfMoves.contains(cell)) { + logOfMoves.add(cell); + } else { + if (!this.name.contains(DEFAULT_COMPUTER_NAME)) { + view.printMessage(SAME_COORDINATE_ERROR_MESSAGE); + } + } + } + view.printMessage(String.format(PLAYER_MOVE_MESSAGE_FORMAT, name, cell.toString())); + boolean hit = player.board.isMoveSuccessful(cell); + if (hit) { + view.printMessage(String.format(HIT_MESSAGE_FORMAT, name, player.name, cell.toString())); + } else { + view.printMessage(String.format(MISSED_MESSAGE_FORMAT, name, cell.toString())); + } + return hit; + } + + public void createFleet(View view) { + view.printMessage(String.format(CREATING_FLEET_MESSAGE_FORMAT, name)); + if (modeToCreateFleet == 0) { + createRightAmountOfTypeRandomly(view, ShipType.BATTLESHIP); + createRightAmountOfTypeRandomly(view, ShipType.CRUISER); + createRightAmountOfTypeRandomly(view, ShipType.DESTROYER); + createRightAmountOfTypeRandomly(view, ShipType.TORPEDO_BOAT); + } else { + createRightAmountOfTypeManually(view, ShipType.BATTLESHIP); + createRightAmountOfTypeManually(view, ShipType.CRUISER); + createRightAmountOfTypeManually(view, ShipType.DESTROYER); + createRightAmountOfTypeManually(view, ShipType.TORPEDO_BOAT); + } + view.printMessage(String.format(FLEET_CREATED_MESSAGE_FORMAT, name)); + } + + private void createRightAmountOfTypeManually(View view, ShipType type) { + view.printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = view.getCell(); + int direction = view.getDirection(); + start.setCellStatus(CellStatus.SHIP); + boolean created = board.isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + if (type.getAmount() - count != 0) { + view.printMessage(String.format(REMAINING_AMOUNT_OF_TYPE_TO_CREATE, + type.name().replace("_", " ").toLowerCase(), type.getAmount() - count)); + } + view.printBoardForPlayer(this, false); + } else { + view.printMessage(ERROR_INPUT_MESSAGE); + } + } + view.printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + "You", type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } + + private void createRightAmountOfTypeRandomly(View view, ShipType type) { + view.printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = Cell.generateRandomCell(); + int direction = ThreadLocalRandom.current().nextInt(0, 2); + boolean created = board.isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + } + } + view.printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + this.getName(), type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } + +} diff --git a/src/main/java/course_project/battleship_game/model/Ship.java b/src/main/java/course_project/battleship_game/model/Ship.java new file mode 100644 index 00000000..cfe52159 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Ship.java @@ -0,0 +1,59 @@ +package course_project.battleship_game.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class Ship { + private final ShipType type; + private final List cellsList; + + public Ship(Cell start, ShipType type, int direction) { + this.type = type; + this.cellsList = generateShipCells(start, type, direction); + } + + public ShipType getType() { + return type; + } + + public List getCellsList() { + return cellsList; + } + + public boolean isHit(Cell cell) { + if (cellsList.contains(cell)) { + cellsList.get(cellsList.indexOf(cell)).setCellStatus(CellStatus.HIT); + return true; + } + return false; + } + + public boolean isNotAlive() { + return cellsList.stream().allMatch(c -> c.getCellStatus().equals(CellStatus.HIT)); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Ship ship = (Ship) o; + return getType() == ship.getType() && + getCellsList().equals(ship.getCellsList()); + } + + @Override + public int hashCode() { + return Objects.hash(getType(), getCellsList()); + } + + private List generateShipCells(Cell start, ShipType type, int direction) { + List cells = new ArrayList<>(); + for (int i = 0; i < type.getLength(); i++) { + int x = direction == 1 ? start.getX() : start.getX() + i; + int y = direction == 1 ? start.getY() + i : start.getY(); + cells.add(new Cell(x, y, CellStatus.SHIP)); + } + return cells; + } +} diff --git a/src/main/java/course_project/battleship_game/model/ShipType.java b/src/main/java/course_project/battleship_game/model/ShipType.java new file mode 100644 index 00000000..b23df332 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/ShipType.java @@ -0,0 +1,31 @@ +package course_project.battleship_game.model; + +public enum ShipType { + BATTLESHIP(4, 1), + CRUISER(3, 2), + DESTROYER(2, 3), + TORPEDO_BOAT(1, 4); + + private final int length; + private final int amount; + + ShipType(int length, int amount) { + this.length = length; + this.amount = amount; + } + + public int getLength() { + return length; + } + + public int getAmount() { + return amount; + } + + @Override + public String toString() { + return this.name() + + " with length of " + length + " cells." + + " The amount of " + this.name().replace("_", " ").toLowerCase() + "s should be " + amount + "."; + } +} diff --git a/src/main/java/course_project/battleship_game/utils/Constants.java b/src/main/java/course_project/battleship_game/utils/Constants.java new file mode 100644 index 00000000..9b8b5577 --- /dev/null +++ b/src/main/java/course_project/battleship_game/utils/Constants.java @@ -0,0 +1,32 @@ +package course_project.battleship_game.utils; + +public class Constants { + public static final String DEFAULT_PLAYER_NAME = "Player"; + public static final String DEFAULT_COMPUTER_NAME = "Computer"; + public static final String WELCOME_MESSAGE = "Welcome to the Battleship game!\n"; + public static final String CHOOSE_GAME_MODE_MESSAGE = "Choose game mode:\n" + + "0 - Computer vs Computer\n" + + "1 - Computer vs Player\n" + + "2 - Player vs Player\n"; + public static final String GET_PLAYER_NAME_MESSAGE = "Enter your name:\n"; + public static final String ROLLING_DICE_MESSAGE = "We are rolling dice to choose who will go first.\n"; + public static final String FLEETS_CREATED_MESSAGE = "\nFleets have been successfully created! Let's the battle begin!\n"; + public static final String CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE = "\nChoose mode:\n" + + "0 - place your ships randomly\n" + + "1 - place your ships by yourself.\n"; + public static final String CHOOSE_SHIP_DIRECTION_MESSAGE = "Put 0 - for horizontal placement or 1 - for vertical placement\n"; + public static final String GET_CELL_COORDINATE_MESSAGE = "Type coordinate in format (Letters from A to J, numbers from 1 to 10)\n"; + public static final String ERROR_INPUT_MESSAGE = "Wrong input.\n"; + public static final String SAME_COORDINATE_ERROR_MESSAGE = "You have already done this move. Please try again!\n"; + public static final String PLAYER_BOARD_MESSAGE_FORMAT = "\nThis is %s's board\n"; + public static final String PLAYER_TURN_MESSAGE_FORMAT = "\nNow it is %s's turn\n"; + public static final String PLAYER_MOVE_MESSAGE_FORMAT = "%s made move on %s.\n"; + public static final String HIT_MESSAGE_FORMAT = "%s has just hit the ship of %s located on %s!\n"; + public static final String PLAYER_WINNER_MESSAGE_FORMAT = "Congratulations %s! You won the game!"; + public static final String MISSED_MESSAGE_FORMAT = "%s missed on %s.\n"; + public static final String CREATING_FLEET_MESSAGE_FORMAT = "\nCreating fleet for %s\n"; + public static final String FLEET_CREATED_MESSAGE_FORMAT = "The fleet for %s has been created!\n"; + public static final String CREATING_SHIP_MESSAGE_FORMAT = "Creating %s\n"; + public static final String SHIP_CREATED_MESSAGE_FORMAT = "%s successfully created %d %s(s).\n"; + public static final String REMAINING_AMOUNT_OF_TYPE_TO_CREATE = "Remaining amount of %ss is %d\n"; +} diff --git a/src/main/java/course_project/battleship_game/utils/Validator.java b/src/main/java/course_project/battleship_game/utils/Validator.java new file mode 100644 index 00000000..ef5f603a --- /dev/null +++ b/src/main/java/course_project/battleship_game/utils/Validator.java @@ -0,0 +1,28 @@ +package course_project.battleship_game.utils; + +public class Validator { + + public static boolean isCoordinate(String coordinate) { + if (coordinate.length() > 3) { + return false; + } + boolean isFirstLetter = coordinate.toUpperCase().charAt(0) > 64 && + coordinate.toUpperCase().charAt(0) < 75; + boolean isNumber = isSuitableForCellCoordinate(coordinate.substring(1)); + return isFirstLetter && isNumber; + } + + private static boolean isSuitableForCellCoordinate(String str) { + int count = 0; + for (int ch : str.toCharArray()) { + if (48 <= ch && ch < 58) { + count++; + } + } + if (count == str.length()) { + int i = Integer.parseInt(str); + return 0 < i && i < 11; + } + return false; + } +} diff --git a/src/main/java/course_project/battleship_game/view/View.java b/src/main/java/course_project/battleship_game/view/View.java new file mode 100644 index 00000000..63cc2cf2 --- /dev/null +++ b/src/main/java/course_project/battleship_game/view/View.java @@ -0,0 +1,117 @@ +package course_project.battleship_game.view; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.utils.Validator; + +import java.util.Scanner; + +import static course_project.battleship_game.utils.Constants.CHOOSE_GAME_MODE_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_SHIP_DIRECTION_MESSAGE; +import static course_project.battleship_game.utils.Constants.DEFAULT_PLAYER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.GET_CELL_COORDINATE_MESSAGE; +import static course_project.battleship_game.utils.Constants.GET_PLAYER_NAME_MESSAGE; +import static course_project.battleship_game.utils.Constants.PLAYER_BOARD_MESSAGE_FORMAT; +import static java.lang.System.lineSeparator; + +public class View { + private static final Scanner scanner = new Scanner(System.in); + + public String getPlayerName() { + printMessage(GET_PLAYER_NAME_MESSAGE); + String line = readLine(); + return line == null || line.isEmpty() ? DEFAULT_PLAYER_NAME : line; + } + + public GameMode getGameMode() { + printMessage(CHOOSE_GAME_MODE_MESSAGE); + String mode = readLine(); + while (true) { + if (mode.equals("0")) { + return GameMode.CVC; + } else if (mode.equals("1")) { + return GameMode.PVC; + } else if (mode.equals("2")) { + return GameMode.PVP; + } else { + printMessage(ERROR_INPUT_MESSAGE); + mode = readLine(); + } + } + } + + public int getModeToCreateFleet() { + printMessage(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE); + return getZeroOrOne(); + } + + public int getDirection() { + printMessage(CHOOSE_SHIP_DIRECTION_MESSAGE); + return getZeroOrOne(); + } + + public Cell getCell() { + printMessage(GET_CELL_COORDINATE_MESSAGE); + String coordinate = readLine(); + while (!Validator.isCoordinate(coordinate)) { + printMessage(ERROR_INPUT_MESSAGE); + coordinate = readLine(); + } + int x = Integer.parseInt(coordinate.substring(1)) - 1; + int y = ((int) coordinate.toUpperCase().charAt(0)) - 65; + return new Cell(x, y); + } + + public void printBoardForPlayer(Player player, boolean isEnemy) { + printMessage(String.format(PLAYER_BOARD_MESSAGE_FORMAT, player.getName())); + printHeader(); + Cell[][] boardMatrix = player.getBoard().getBoardMatrix(); + for (int y = 0; y < boardMatrix.length; y++) { + printMessage((char) (65 + y) + " "); + for (int x = 0; x < boardMatrix.length; x++) { + printCell(isEnemy, boardMatrix[y][x]); + } + printMessage(lineSeparator()); + } + } + + public void printMessage(String message) { + System.out.print(message); + } + + private void printCell(boolean isEnemy, Cell cell) { + if (isEnemy && cell.getCellStatus().equals(CellStatus.SHIP)) { + printMessage(CellStatus.EMPTY.getCharacter()); + } else { + printMessage(cell.getCellStatus().getCharacter()); + } + } + + public String readLine() { + return scanner.nextLine(); + } + + private int getZeroOrOne() { + String mode = readLine(); + while (true) { + if (mode.equals("0") || mode.equals("1")) { + return Integer.parseInt(mode); + } + printMessage(ERROR_INPUT_MESSAGE); + mode = readLine(); + } + } + + private void printHeader() { + printMessage(" "); + for (int i = 1; i < 11; i++) { + printMessage(i + " "); + } + printMessage(lineSeparator()); + } + +} From 4636cecf533906213d1c025b272eba2d2aec8b45 Mon Sep 17 00:00:00 2001 From: rlrio Date: Fri, 10 Sep 2021 15:17:14 +0300 Subject: [PATCH 62/80] add raw course_project realization --- src/main/java/course_project/battleship_game/view/View.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/course_project/battleship_game/view/View.java b/src/main/java/course_project/battleship_game/view/View.java index 63cc2cf2..53eb3da8 100644 --- a/src/main/java/course_project/battleship_game/view/View.java +++ b/src/main/java/course_project/battleship_game/view/View.java @@ -91,7 +91,7 @@ private void printCell(boolean isEnemy, Cell cell) { } } - public String readLine() { + private String readLine() { return scanner.nextLine(); } From c0c4f6b8b9aff5dfdea21b880da1fdb22b7b833f Mon Sep 17 00:00:00 2001 From: rlrio Date: Fri, 10 Sep 2021 23:56:40 +0300 Subject: [PATCH 63/80] add raw course_project realization --- .../course_project/battleship_game/view/View.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/course_project/battleship_game/view/View.java b/src/main/java/course_project/battleship_game/view/View.java index 53eb3da8..c420f5f8 100644 --- a/src/main/java/course_project/battleship_game/view/View.java +++ b/src/main/java/course_project/battleship_game/view/View.java @@ -6,7 +6,9 @@ import course_project.battleship_game.model.Player; import course_project.battleship_game.utils.Validator; -import java.util.Scanner; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; import static course_project.battleship_game.utils.Constants.CHOOSE_GAME_MODE_MESSAGE; import static course_project.battleship_game.utils.Constants.CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE; @@ -19,7 +21,7 @@ import static java.lang.System.lineSeparator; public class View { - private static final Scanner scanner = new Scanner(System.in); + private static final BufferedReader READER = new BufferedReader(new InputStreamReader(System.in)); public String getPlayerName() { printMessage(GET_PLAYER_NAME_MESSAGE); @@ -92,7 +94,11 @@ private void printCell(boolean isEnemy, Cell cell) { } private String readLine() { - return scanner.nextLine(); + try { + return READER.readLine(); + } catch (IOException e) { + return ""; + } } private int getZeroOrOne() { From 6fc2987b95d35cb3d16d996fad4464395b79fcf6 Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 12 Sep 2021 17:18:09 +0300 Subject: [PATCH 64/80] bug unit test --- .../battleship_game/ViewTest.java | 54 +++++++++++++++++++ .../battleship_game/utils/Constants.java | 6 +++ 2 files changed, 60 insertions(+) create mode 100644 src/test/java/course_project/battleship_game/ViewTest.java create mode 100644 src/test/java/course_project/battleship_game/utils/Constants.java diff --git a/src/test/java/course_project/battleship_game/ViewTest.java b/src/test/java/course_project/battleship_game/ViewTest.java new file mode 100644 index 00000000..e3d4bb41 --- /dev/null +++ b/src/test/java/course_project/battleship_game/ViewTest.java @@ -0,0 +1,54 @@ +package course_project.battleship_game; + +import base.UnitBase; + +public class ViewTest extends UnitBase { +// private final View view = new View(); +// +// @ParameterizedTest +// @MethodSource("testCasesForGetPlayerName") +// void testGetPlayerName(final String input, final String expected) { +// setInput(input); +// String playerName = view.getPlayerName(); +// assertEquals(expected, playerName); +// } +// +// @ParameterizedTest +// @MethodSource("testCasesToGetGameModeSuccess") +// void testGetGameModeSuccess(final String input, final GameMode expected) { +// setInput(input); +// GameMode gameMode = view.getGameMode(); +// assertEquals(expected, gameMode); +// } +// +// @ParameterizedTest +// @MethodSource("testCasesToGetGameModeError") +// void testGetGameModeError(final String input, final String expected) { +// setInput("input"); +// view.getGameMode(); +// assertEquals(expected, getOutput()); +// } +// +// static Stream testCasesForGetPlayerName() { +// return Stream.of( +// Arguments.of("", DEFAULT_PLAYER_NAME), +// Arguments.of("PlayerName", "PlayerName") +// ); +// } +// +// static Stream testCasesToGetGameModeSuccess() { +// return Stream.of( +// Arguments.of("0", GameMode.CVC), +// Arguments.of("1", GameMode.PVC), +// Arguments.of("2", GameMode.PVP) +// ); +// } +// +// static Stream testCasesToGetGameModeError() { +// return Stream.of( +// Arguments.of("String", ERROR_INPUT_MESSAGE), +// Arguments.of("10", ERROR_INPUT_MESSAGE) +// ); +// } +} + diff --git a/src/test/java/course_project/battleship_game/utils/Constants.java b/src/test/java/course_project/battleship_game/utils/Constants.java new file mode 100644 index 00000000..e5b210df --- /dev/null +++ b/src/test/java/course_project/battleship_game/utils/Constants.java @@ -0,0 +1,6 @@ +package course_project.battleship_game.utils; + +public class Constants { + public static final String DEFAULT_PLAYER_NAME = "Player"; + public static final String ERROR_INPUT_MESSAGE = "Wrong input.\n"; +} From c7acea343acd489a49dcae6ddc81a8985d8c299d Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 15 Sep 2021 20:30:28 +0300 Subject: [PATCH 65/80] refactoring course_project --- build.gradle | 3 + .../course_project/battleship_game/Main.java | 5 +- .../battleship_game/model/Board.java | 121 +----------------- .../battleship_game/model/Cell.java | 7 - .../battleship_game/model/Game.java | 5 - .../battleship_game/model/GameImpl.java | 88 ------------- .../battleship_game/model/Player.java | 95 +------------- .../battleship_game/model/Ship.java | 27 +--- .../battleship_game/service/BoardService.java | 110 ++++++++++++++++ .../service/CreateService.java | 118 +++++++++++++++++ .../battleship_game/service/Game.java | 74 +++++++++++ .../service/PlayerService.java | 68 ++++++++++ .../battleship_game/service/ShipService.java | 26 ++++ .../battleship_game/utils/Constants.java | 1 + ...alidator.java => CoordinateValidator.java} | 4 +- .../battleship_game/utils/PrintUtils.java | 53 ++++++++ .../battleship_game/ViewTest.java | 54 -------- 17 files changed, 469 insertions(+), 390 deletions(-) delete mode 100644 src/main/java/course_project/battleship_game/model/Game.java delete mode 100644 src/main/java/course_project/battleship_game/model/GameImpl.java create mode 100644 src/main/java/course_project/battleship_game/service/BoardService.java create mode 100644 src/main/java/course_project/battleship_game/service/CreateService.java create mode 100644 src/main/java/course_project/battleship_game/service/Game.java create mode 100644 src/main/java/course_project/battleship_game/service/PlayerService.java create mode 100644 src/main/java/course_project/battleship_game/service/ShipService.java rename src/main/java/course_project/battleship_game/utils/{Validator.java => CoordinateValidator.java} (83%) create mode 100644 src/main/java/course_project/battleship_game/utils/PrintUtils.java delete mode 100644 src/test/java/course_project/battleship_game/ViewTest.java diff --git a/build.gradle b/build.gradle index 522c2e14..490be6e3 100644 --- a/build.gradle +++ b/build.gradle @@ -13,6 +13,9 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' testCompile 'org.junit.jupiter:junit-jupiter-params:5.7.0' + + testImplementation group: 'org.mockito', name: 'mockito-all', version: '1.10.19' + } test { diff --git a/src/main/java/course_project/battleship_game/Main.java b/src/main/java/course_project/battleship_game/Main.java index c6cfb971..74f47f5c 100644 --- a/src/main/java/course_project/battleship_game/Main.java +++ b/src/main/java/course_project/battleship_game/Main.java @@ -1,12 +1,11 @@ package course_project.battleship_game; -import course_project.battleship_game.model.Game; -import course_project.battleship_game.model.GameImpl; +import course_project.battleship_game.service.Game; public class Main { public static void main(String[] args) { - Game game = new GameImpl(); + Game game = new Game(); game.run(); } } \ No newline at end of file diff --git a/src/main/java/course_project/battleship_game/model/Board.java b/src/main/java/course_project/battleship_game/model/Board.java index 0f240947..93b48e62 100644 --- a/src/main/java/course_project/battleship_game/model/Board.java +++ b/src/main/java/course_project/battleship_game/model/Board.java @@ -1,15 +1,16 @@ package course_project.battleship_game.model; +import course_project.battleship_game.service.CreateService; + import java.util.ArrayList; import java.util.List; public class Board { - private static final int BOARD_SIZE = 10; private final Cell[][] boardMatrix; private final List shipList; public Board() { - this.boardMatrix = createBoard(); + this.boardMatrix = new CreateService().createBoard(); this.shipList = new ArrayList<>(); } @@ -17,120 +18,8 @@ public Cell[][] getBoardMatrix() { return boardMatrix; } - public boolean isNoMoreAliveShipsForBoard() { - return shipList.stream().allMatch(Ship::isNotAlive); - } - - public long countRemainedShips() { - return shipList.stream().filter(ship -> !ship.isNotAlive()).count(); - } - - public boolean isCreatingShipSuccessful(Cell start, ShipType type, int direction) { - if (isShipValidForBoard(start, type, direction)) { - Ship ship = new Ship(start, type, direction); - shipList.add(ship); - addShipToBoardMatrix(ship); - markAreaAroundShip(ship); - return true; - } - return false; - } - - public boolean isMoveSuccessful(Cell cell) { - Ship shipResult = shipList.stream() - .filter(ship -> - ship.getCellsList().stream() - .anyMatch(cell1 -> cell1.equals(cell))).findFirst().orElse(null); - boolean hit = shipResult != null && shipResult.isHit(cell); - if (!hit) { - boardMatrix[cell.getY()][cell.getX()].setCellStatus(CellStatus.MISSED); - } - return hit; - } - - private Cell[][] createBoard() { - Cell[][] boardMatrix = new Cell[BOARD_SIZE][BOARD_SIZE]; - for (int y = 0; y < BOARD_SIZE; y++) { - for (int x = 0; x < BOARD_SIZE; x++) { - boardMatrix[y][x] = new Cell(x, y, CellStatus.EMPTY); - } - } - return boardMatrix; + public List getShipList() { + return shipList; } - private void addShipToBoardMatrix(Ship ship) { - for (Cell cell : ship.getCellsList()) { - int x = cell.getX(); - int y = cell.getY(); - boardMatrix[y][x] = cell; - } - } - - private void markAreaAroundShip(Ship ship) { - List cells = ship.getCellsList(); - for (Cell cell : cells) { - int x = cell.getX(); - int y = cell.getY(); - if (x + 1 < BOARD_SIZE && - boardMatrix[y][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y][x + 1].setCellStatus(CellStatus.SHIP_BORDER); - } - if (x + 1 < BOARD_SIZE && y - 1 >= 0 && - boardMatrix[y - 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y - 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); - } - if (x + 1 < BOARD_SIZE && y + 1 < BOARD_SIZE && - boardMatrix[y + 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y + 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); - } - if (x - 1 >= 0 && - boardMatrix[y][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y][x - 1].setCellStatus(CellStatus.SHIP_BORDER); - } - if (x - 1 >= 0 && y - 1 >= 0 && - boardMatrix[y - 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y - 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); - } - if (x - 1 >= 0 && y + 1 < BOARD_SIZE && - boardMatrix[y + 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y + 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); - } - if (y + 1 < BOARD_SIZE && - boardMatrix[y + 1][x].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y + 1][x].setCellStatus(CellStatus.SHIP_BORDER); - } - if (y - 1 >= 0 && - boardMatrix[y - 1][x].getCellStatus().equals(CellStatus.EMPTY)) { - boardMatrix[y - 1][x].setCellStatus(CellStatus.SHIP_BORDER); - } - } - } - - private boolean isShipValidForBoard(Cell start, ShipType type, int direction) { - if (isTypeNotEnoughInShipList(type) && isShipCellsFitBoard(start, type, direction)) { - Ship ship = new Ship(start, type, direction); - return !shipList.contains(ship); - } - return false; - } - - private boolean isShipCellsFitBoard(Cell start, ShipType type, int direction) { - Ship ship = new Ship(start, type, direction); - List cells = ship.getCellsList(); - for (Cell cell : cells) { - if (cell.getX() < 0 || cell.getY() < 0 || cell.getX() >= boardMatrix.length || - cell.getY() >= boardMatrix.length) { - return false; - } - if (!(boardMatrix[cell.getY()][cell.getX()]).getCellStatus().equals(CellStatus.EMPTY)) { - return false; - } - } - return true; - } - - private boolean isTypeNotEnoughInShipList(ShipType type) { - int count = (int) shipList.stream().filter(ship -> ship.getType().equals(type)).count(); - return count < type.getAmount(); - } } diff --git a/src/main/java/course_project/battleship_game/model/Cell.java b/src/main/java/course_project/battleship_game/model/Cell.java index f7e8ebc9..7e0ab5b3 100644 --- a/src/main/java/course_project/battleship_game/model/Cell.java +++ b/src/main/java/course_project/battleship_game/model/Cell.java @@ -1,7 +1,6 @@ package course_project.battleship_game.model; import java.util.Objects; -import java.util.concurrent.ThreadLocalRandom; public class Cell { private final int x; @@ -19,12 +18,6 @@ public Cell(int x, int y) { this.y = y; } - public static Cell generateRandomCell() { - int x = ThreadLocalRandom.current().nextInt(0, 10); - int y = ThreadLocalRandom.current().nextInt(0, 10); - return new Cell(x, y); - } - public int getX() { return x; } diff --git a/src/main/java/course_project/battleship_game/model/Game.java b/src/main/java/course_project/battleship_game/model/Game.java deleted file mode 100644 index 44a36350..00000000 --- a/src/main/java/course_project/battleship_game/model/Game.java +++ /dev/null @@ -1,5 +0,0 @@ -package course_project.battleship_game.model; - -public interface Game { - void run(); -} diff --git a/src/main/java/course_project/battleship_game/model/GameImpl.java b/src/main/java/course_project/battleship_game/model/GameImpl.java deleted file mode 100644 index 652bdbd0..00000000 --- a/src/main/java/course_project/battleship_game/model/GameImpl.java +++ /dev/null @@ -1,88 +0,0 @@ -package course_project.battleship_game.model; - -import course_project.battleship_game.view.View; - -import java.util.concurrent.ThreadLocalRandom; - -import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; -import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; -import static course_project.battleship_game.utils.Constants.PLAYER_TURN_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.PLAYER_WINNER_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.ROLLING_DICE_MESSAGE; -import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; - -public class GameImpl implements Game { - private final View view = new View(); - - @Override - public void run() { - view.printMessage(WELCOME_MESSAGE); - GameMode gameMode = view.getGameMode(); - Player[] players = createPlayers(gameMode); - rollingDiceToChooseWhoStarts(players); - Player player1 = players[0]; - Player player2 = players[1]; - player1.createFleet(view); - player2.createFleet(view); - view.printMessage(FLEETS_CREATED_MESSAGE); - boolean isGameOver = false; - while (!isGameOver) { - isGameOver = isGameOver(player1, player2, gameMode); - if (!isGameOver) { - isGameOver = isGameOver(player2, player1, gameMode); - } - } - determineWinner(player1, player2); - } - - private boolean isGameOver(Player player1, Player player2, GameMode gameMode) { - boolean isMoveSuccessful = true; - view.printMessage(String.format(PLAYER_TURN_MESSAGE_FORMAT, player1.getName())); - while (isMoveSuccessful && !isNoMoreAliveShips(player1, player2)) { - isMoveSuccessful = player1.isMoveSuccessful(player2, view); - printBoard(gameMode, player1, player2); - } - return isNoMoreAliveShips(player1, player2); - } - - private void printBoard(GameMode mode, Player player1, Player player2) { - if (mode.equals(GameMode.CVC) || !player1.getName().contains(DEFAULT_COMPUTER_NAME)) { - view.printBoardForPlayer(player1, false); - view.printBoardForPlayer(player2, true); - } - } - - private Player[] createPlayers(GameMode mode) { - Player[] players = new Player[2]; - players[0] = mode.equals(GameMode.CVC) ? new Player(DEFAULT_COMPUTER_NAME + " Mimi", 0) : - new Player(view.getPlayerName(), view.getModeToCreateFleet()); - players[1] = !mode.equals(GameMode.PVP) ? new Player(DEFAULT_COMPUTER_NAME + " Navi", 0) : - new Player(view.getPlayerName(), view.getModeToCreateFleet()); - return players; - } - - private void rollingDiceToChooseWhoStarts(Player[] players) { - view.printMessage(ROLLING_DICE_MESSAGE); - int dice = ThreadLocalRandom.current().nextInt(0, 2); - if (dice == 1) { - Player temp = players[0]; - players[0] = players[1]; - players[1] = temp; - } - view.printMessage(players[0].getName() + " will go first\n"); - } - - private boolean isNoMoreAliveShips(Player player1, Player player2) { - return player1.getBoard().isNoMoreAliveShipsForBoard() || player2.getBoard().isNoMoreAliveShipsForBoard(); - } - - private void determineWinner(Player player1, Player player2) { - if (isNoMoreAliveShips(player1, player2)) { - long player1Fleet = player1.getBoard().countRemainedShips(); - long player2Fleet = player2.getBoard().countRemainedShips(); - Player winner = player1Fleet > player2Fleet ? player1 : player2; - view.printMessage(String.format(PLAYER_WINNER_MESSAGE_FORMAT, winner.getName())); - } - } - -} diff --git a/src/main/java/course_project/battleship_game/model/Player.java b/src/main/java/course_project/battleship_game/model/Player.java index 7d368b88..a8307762 100644 --- a/src/main/java/course_project/battleship_game/model/Player.java +++ b/src/main/java/course_project/battleship_game/model/Player.java @@ -1,22 +1,7 @@ package course_project.battleship_game.model; -import course_project.battleship_game.view.View; - import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -import static course_project.battleship_game.utils.Constants.CREATING_FLEET_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.CREATING_SHIP_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; -import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; -import static course_project.battleship_game.utils.Constants.FLEET_CREATED_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.HIT_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.MISSED_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.PLAYER_MOVE_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.REMAINING_AMOUNT_OF_TYPE_TO_CREATE; -import static course_project.battleship_game.utils.Constants.SAME_COORDINATE_ERROR_MESSAGE; -import static course_project.battleship_game.utils.Constants.SHIP_CREATED_MESSAGE_FORMAT; public class Player { private final String name; @@ -39,84 +24,12 @@ public String getName() { return name; } - public boolean isMoveSuccessful(Player player, View view) { - Cell cell = null; - while (cell == null || !logOfMoves.contains(cell)) { - if (this.name.contains(DEFAULT_COMPUTER_NAME)) { - cell = Cell.generateRandomCell(); - } else { - cell = view.getCell(); - } - if (!logOfMoves.contains(cell)) { - logOfMoves.add(cell); - } else { - if (!this.name.contains(DEFAULT_COMPUTER_NAME)) { - view.printMessage(SAME_COORDINATE_ERROR_MESSAGE); - } - } - } - view.printMessage(String.format(PLAYER_MOVE_MESSAGE_FORMAT, name, cell.toString())); - boolean hit = player.board.isMoveSuccessful(cell); - if (hit) { - view.printMessage(String.format(HIT_MESSAGE_FORMAT, name, player.name, cell.toString())); - } else { - view.printMessage(String.format(MISSED_MESSAGE_FORMAT, name, cell.toString())); - } - return hit; - } - - public void createFleet(View view) { - view.printMessage(String.format(CREATING_FLEET_MESSAGE_FORMAT, name)); - if (modeToCreateFleet == 0) { - createRightAmountOfTypeRandomly(view, ShipType.BATTLESHIP); - createRightAmountOfTypeRandomly(view, ShipType.CRUISER); - createRightAmountOfTypeRandomly(view, ShipType.DESTROYER); - createRightAmountOfTypeRandomly(view, ShipType.TORPEDO_BOAT); - } else { - createRightAmountOfTypeManually(view, ShipType.BATTLESHIP); - createRightAmountOfTypeManually(view, ShipType.CRUISER); - createRightAmountOfTypeManually(view, ShipType.DESTROYER); - createRightAmountOfTypeManually(view, ShipType.TORPEDO_BOAT); - } - view.printMessage(String.format(FLEET_CREATED_MESSAGE_FORMAT, name)); - } - - private void createRightAmountOfTypeManually(View view, ShipType type) { - view.printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); - int count = 0; - while (count != type.getAmount()) { - Cell start = view.getCell(); - int direction = view.getDirection(); - start.setCellStatus(CellStatus.SHIP); - boolean created = board.isCreatingShipSuccessful(start, type, direction); - if (created) { - count++; - if (type.getAmount() - count != 0) { - view.printMessage(String.format(REMAINING_AMOUNT_OF_TYPE_TO_CREATE, - type.name().replace("_", " ").toLowerCase(), type.getAmount() - count)); - } - view.printBoardForPlayer(this, false); - } else { - view.printMessage(ERROR_INPUT_MESSAGE); - } - } - view.printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, - "You", type.getAmount(), type.name().replace("_", " ").toLowerCase())); + public List getLogOfMoves() { + return logOfMoves; } - private void createRightAmountOfTypeRandomly(View view, ShipType type) { - view.printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); - int count = 0; - while (count != type.getAmount()) { - Cell start = Cell.generateRandomCell(); - int direction = ThreadLocalRandom.current().nextInt(0, 2); - boolean created = board.isCreatingShipSuccessful(start, type, direction); - if (created) { - count++; - } - } - view.printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, - this.getName(), type.getAmount(), type.name().replace("_", " ").toLowerCase())); + public int getModeToCreateFleet() { + return modeToCreateFleet; } } diff --git a/src/main/java/course_project/battleship_game/model/Ship.java b/src/main/java/course_project/battleship_game/model/Ship.java index cfe52159..5efb49f7 100644 --- a/src/main/java/course_project/battleship_game/model/Ship.java +++ b/src/main/java/course_project/battleship_game/model/Ship.java @@ -1,6 +1,7 @@ package course_project.battleship_game.model; -import java.util.ArrayList; +import course_project.battleship_game.service.CreateService; + import java.util.List; import java.util.Objects; @@ -10,7 +11,7 @@ public class Ship { public Ship(Cell start, ShipType type, int direction) { this.type = type; - this.cellsList = generateShipCells(start, type, direction); + this.cellsList = new CreateService().createShipCells(start, type, direction); } public ShipType getType() { @@ -21,18 +22,6 @@ public List getCellsList() { return cellsList; } - public boolean isHit(Cell cell) { - if (cellsList.contains(cell)) { - cellsList.get(cellsList.indexOf(cell)).setCellStatus(CellStatus.HIT); - return true; - } - return false; - } - - public boolean isNotAlive() { - return cellsList.stream().allMatch(c -> c.getCellStatus().equals(CellStatus.HIT)); - } - @Override public boolean equals(Object o) { if (this == o) return true; @@ -46,14 +35,4 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(getType(), getCellsList()); } - - private List generateShipCells(Cell start, ShipType type, int direction) { - List cells = new ArrayList<>(); - for (int i = 0; i < type.getLength(); i++) { - int x = direction == 1 ? start.getX() : start.getX() + i; - int y = direction == 1 ? start.getY() + i : start.getY(); - cells.add(new Cell(x, y, CellStatus.SHIP)); - } - return cells; - } } diff --git a/src/main/java/course_project/battleship_game/service/BoardService.java b/src/main/java/course_project/battleship_game/service/BoardService.java new file mode 100644 index 00000000..9d8987a5 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/BoardService.java @@ -0,0 +1,110 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Board; +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; +import course_project.battleship_game.model.ShipType; + +import java.util.List; + +import static course_project.battleship_game.utils.Constants.BOARD_SIZE; + +public class BoardService { + private final Board board; + + public BoardService(Board board) { + this.board = board; + } + + public long countRemainedShipsForBoard() { + return board.getShipList().stream().filter(ship -> !new ShipService(ship).isNotAlive()).count(); + } + + public boolean isCreatingShipSuccessful(Cell start, ShipType type, int direction) { + if (isShipValidForBoard(start, type, direction)) { + Ship ship = new Ship(start, type, direction); + board.getShipList().add(ship); + addShipToBoardMatrix(ship); + markBoardCellsAroundShip(ship); + return true; + } + return false; + } + + private void addShipToBoardMatrix(Ship ship) { + for (Cell cell : ship.getCellsList()) { + int x = cell.getX(); + int y = cell.getY(); + board.getBoardMatrix()[y][x] = cell; + } + } + + private void markBoardCellsAroundShip(Ship ship) { + List cells = ship.getCellsList(); + for (Cell cell : cells) { + int x = cell.getX(); + int y = cell.getY(); + if (x + 1 < BOARD_SIZE && + board.getBoardMatrix()[y][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x + 1 < BOARD_SIZE && y - 1 >= 0 && + board.getBoardMatrix()[y - 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y - 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x + 1 < BOARD_SIZE && y + 1 < BOARD_SIZE && + board.getBoardMatrix()[y + 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y + 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && + board.getBoardMatrix()[y][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && y - 1 >= 0 && + board.getBoardMatrix()[y - 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y - 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && y + 1 < BOARD_SIZE && + board.getBoardMatrix()[y + 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y + 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (y + 1 < BOARD_SIZE && + board.getBoardMatrix()[y + 1][x].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y + 1][x].setCellStatus(CellStatus.SHIP_BORDER); + } + if (y - 1 >= 0 && + board.getBoardMatrix()[y - 1][x].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y - 1][x].setCellStatus(CellStatus.SHIP_BORDER); + } + } + } + + private boolean isShipValidForBoard(Cell start, ShipType type, int direction) { + if (isTypeNotEnoughInBoardShipList(type) && isShipCellsFitBoard(start, type, direction)) { + Ship ship = new Ship(start, type, direction); + return !board.getShipList().contains(ship); + } + return false; + } + + private boolean isShipCellsFitBoard(Cell start, ShipType type, int direction) { + Ship ship = new Ship(start, type, direction); + List cells = ship.getCellsList(); + for (Cell cell : cells) { + if (cell.getX() < 0 || cell.getY() < 0 || cell.getX() >= board.getBoardMatrix().length || + cell.getY() >= board.getBoardMatrix().length) { + return false; + } + if (!(board.getBoardMatrix()[cell.getY()][cell.getX()]).getCellStatus().equals(CellStatus.EMPTY)) { + return false; + } + } + return true; + } + + private boolean isTypeNotEnoughInBoardShipList(ShipType type) { + int count = (int) board.getShipList().stream().filter(ship -> ship.getType().equals(type)).count(); + return count < type.getAmount(); + } +} diff --git a/src/main/java/course_project/battleship_game/service/CreateService.java b/src/main/java/course_project/battleship_game/service/CreateService.java new file mode 100644 index 00000000..a96bcfd0 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/CreateService.java @@ -0,0 +1,118 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.model.ShipType; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import static course_project.battleship_game.utils.Constants.BOARD_SIZE; +import static course_project.battleship_game.utils.Constants.CREATING_FLEET_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.CREATING_SHIP_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.FLEET_CREATED_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.REMAINING_AMOUNT_OF_TYPE_TO_CREATE; +import static course_project.battleship_game.utils.Constants.SHIP_CREATED_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.InputUtils.getCell; +import static course_project.battleship_game.utils.InputUtils.getDirection; +import static course_project.battleship_game.utils.InputUtils.getModeToCreateFleet; +import static course_project.battleship_game.utils.InputUtils.getPlayerName; +import static course_project.battleship_game.utils.PrintUtils.printBoardForPlayer; +import static course_project.battleship_game.utils.PrintUtils.printMessage; + +public class CreateService { + + public Cell[][] createBoard() { + Cell[][] boardMatrix = new Cell[BOARD_SIZE][BOARD_SIZE]; + for (int y = 0; y < BOARD_SIZE; y++) { + for (int x = 0; x < BOARD_SIZE; x++) { + boardMatrix[y][x] = new Cell(x, y, CellStatus.EMPTY); + } + } + return boardMatrix; + } + + public Player[] createPlayers(GameMode mode) { + Player[] players = new Player[2]; + players[0] = mode.equals(GameMode.CVC) ? new Player(DEFAULT_COMPUTER_NAME + " Mimi", 0) : + new Player(getPlayerName(), getModeToCreateFleet()); + players[1] = !mode.equals(GameMode.PVP) ? new Player(DEFAULT_COMPUTER_NAME + " Navi", 0) : + new Player(getPlayerName(), getModeToCreateFleet()); + return players; + } + + public void createFleet(Player player) { + printMessage(String.format(CREATING_FLEET_MESSAGE_FORMAT, player.getName())); + if (player.getModeToCreateFleet() == 0) { + createRightAmountOfTypeRandomly(player, ShipType.BATTLESHIP); + createRightAmountOfTypeRandomly(player, ShipType.CRUISER); + createRightAmountOfTypeRandomly(player, ShipType.DESTROYER); + createRightAmountOfTypeRandomly(player, ShipType.TORPEDO_BOAT); + } else { + createRightAmountOfTypeManually(player, ShipType.BATTLESHIP); + createRightAmountOfTypeManually(player, ShipType.CRUISER); + createRightAmountOfTypeManually(player, ShipType.DESTROYER); + createRightAmountOfTypeManually(player, ShipType.TORPEDO_BOAT); + } + printMessage(String.format(FLEET_CREATED_MESSAGE_FORMAT, player.getName())); + } + + public Cell createRandomCell() { + int x = ThreadLocalRandom.current().nextInt(0, 10); + int y = ThreadLocalRandom.current().nextInt(0, 10); + return new Cell(x, y); + } + + public List createShipCells(Cell start, ShipType type, int direction) { + List cells = new ArrayList<>(); + for (int i = 0; i < type.getLength(); i++) { + int x = direction == 1 ? start.getX() : start.getX() + i; + int y = direction == 1 ? start.getY() + i : start.getY(); + cells.add(new Cell(x, y, CellStatus.SHIP)); + } + return cells; + } + + private void createRightAmountOfTypeManually(Player player, ShipType type) { + printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = getCell(); + int direction = getDirection(); + start.setCellStatus(CellStatus.SHIP); + boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + if (type.getAmount() - count != 0) { + printMessage(String.format(REMAINING_AMOUNT_OF_TYPE_TO_CREATE, + type.name().replace("_", " ").toLowerCase(), type.getAmount() - count)); + } + printBoardForPlayer(player, false); + } else { + printMessage(ERROR_INPUT_MESSAGE); + } + } + printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + "You", type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } + + private void createRightAmountOfTypeRandomly(Player player, ShipType type) { + printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = createRandomCell(); + int direction = ThreadLocalRandom.current().nextInt(0, 2); + boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + } + } + printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + player.getName(), type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } +} diff --git a/src/main/java/course_project/battleship_game/service/Game.java b/src/main/java/course_project/battleship_game/service/Game.java new file mode 100644 index 00000000..da115cb6 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/Game.java @@ -0,0 +1,74 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; + +import java.util.concurrent.ThreadLocalRandom; + +import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; +import static course_project.battleship_game.utils.Constants.PLAYER_TURN_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.PLAYER_WINNER_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.ROLLING_DICE_MESSAGE; +import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; +import static course_project.battleship_game.utils.InputUtils.getGameMode; +import static course_project.battleship_game.utils.PrintUtils.printBoards; +import static course_project.battleship_game.utils.PrintUtils.printMessage; + +public class Game { + + public void run() { + printMessage(WELCOME_MESSAGE); + GameMode gameMode = getGameMode(); + CreateService createService = new CreateService(); + Player[] players = createService.createPlayers(gameMode); + rollingDiceToChooseWhoStarts(players); + Player player1 = players[0]; + Player player2 = players[1]; + createService.createFleet(player1); + createService.createFleet(player2); + printMessage(FLEETS_CREATED_MESSAGE); + boolean isGameOver = false; + while (!isGameOver) { + isGameOver = isGameOver(player1, player2, gameMode); + if (!isGameOver) { + isGameOver = isGameOver(player2, player1, gameMode); + } + } + determineWinner(player1, player2); + } + + private boolean isGameOver(Player player1, Player player2, GameMode gameMode) { + boolean isMoveSuccessful = true; + printMessage(String.format(PLAYER_TURN_MESSAGE_FORMAT, player1.getName())); + while (isMoveSuccessful && !isNoMoreAliveShips(player1, player2)) { + isMoveSuccessful = new PlayerService(player1).isMoveSuccessful(player2); + printBoards(gameMode, player1, player2); + } + return isNoMoreAliveShips(player1, player2); + } + + private void rollingDiceToChooseWhoStarts(Player[] players) { + printMessage(ROLLING_DICE_MESSAGE); + int dice = ThreadLocalRandom.current().nextInt(0, 2); + if (dice == 1) { + Player temp = players[0]; + players[0] = players[1]; + players[1] = temp; + } + printMessage(players[0].getName() + " will go first\n"); + } + + private boolean isNoMoreAliveShips(Player player1, Player player2) { + return new PlayerService(player1).isNoMoreAliveShipsForBoard() || new PlayerService(player2).isNoMoreAliveShipsForBoard(); + } + + private void determineWinner(Player player1, Player player2) { + if (isNoMoreAliveShips(player1, player2)) { + long player1Fleet = new BoardService(player1.getBoard()).countRemainedShipsForBoard(); + long player2Fleet = new BoardService(player2.getBoard()).countRemainedShipsForBoard(); + Player winner = player1Fleet > player2Fleet ? player1 : player2; + printMessage(String.format(PLAYER_WINNER_MESSAGE_FORMAT, winner.getName())); + } + } + +} diff --git a/src/main/java/course_project/battleship_game/service/PlayerService.java b/src/main/java/course_project/battleship_game/service/PlayerService.java new file mode 100644 index 00000000..f18d85d6 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/PlayerService.java @@ -0,0 +1,68 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Board; +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.model.Ship; + +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.HIT_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.MISSED_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.PLAYER_MOVE_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.SAME_COORDINATE_ERROR_MESSAGE; +import static course_project.battleship_game.utils.InputUtils.getCell; +import static course_project.battleship_game.utils.PrintUtils.printMessage; + +public class PlayerService { + private final Player player; + + public PlayerService(Player player) { + this.player = player; + } + + public boolean isMoveSuccessful(Player enemy) { + Cell cell = null; + while (cell == null || !player.getLogOfMoves().contains(cell)) { + if (player.getName().contains(DEFAULT_COMPUTER_NAME)) { + cell = new CreateService().createRandomCell(); + } else { + cell = getCell(); + } + + if (!player.getLogOfMoves().contains(cell)) { + player.getLogOfMoves().add(cell); + } else { + if (!player.getName().contains(DEFAULT_COMPUTER_NAME)) { + printMessage(SAME_COORDINATE_ERROR_MESSAGE); + cell = null; + } + } + } + printMessage(String.format(PLAYER_MOVE_MESSAGE_FORMAT, player.getName(), cell.toString())); + boolean hit = isHitCellOnBoard(enemy.getBoard(), cell); //new BoardService(enemy.getBoard()).isHitCellOnBoard(cell); + if (hit) { + printMessage(String.format(HIT_MESSAGE_FORMAT, player.getName(), enemy.getName(), cell.toString())); + } else { + printMessage(String.format(MISSED_MESSAGE_FORMAT, player.getName(), cell.toString())); + } + return hit; + } + + + public boolean isNoMoreAliveShipsForBoard() { + return player.getBoard().getShipList().stream().allMatch(ship -> new ShipService(ship).isNotAlive()); + } + + private boolean isHitCellOnBoard(Board board, Cell cell) { + Ship shipResult = board.getShipList().stream() + .filter(ship -> + ship.getCellsList().stream() + .anyMatch(cell1 -> cell1.equals(cell))).findFirst().orElse(null); + boolean hit = shipResult != null && new ShipService(shipResult).isHit(cell); + if (!hit) { + board.getBoardMatrix()[cell.getY()][cell.getX()].setCellStatus(CellStatus.MISSED); + } + return hit; + } +} diff --git a/src/main/java/course_project/battleship_game/service/ShipService.java b/src/main/java/course_project/battleship_game/service/ShipService.java new file mode 100644 index 00000000..14557cb5 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/ShipService.java @@ -0,0 +1,26 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; + +public class ShipService { + private final Ship ship; + + public ShipService(Ship ship) { + this.ship = ship; + } + + public boolean isHit(Cell cell) { + if (ship.getCellsList().contains(cell)) { + ship.getCellsList().get(ship.getCellsList().indexOf(cell)).setCellStatus(CellStatus.HIT); + return true; + } + return false; + } + + public boolean isNotAlive() { + return ship.getCellsList().stream().allMatch(c -> c.getCellStatus().equals(CellStatus.HIT)); + } + +} diff --git a/src/main/java/course_project/battleship_game/utils/Constants.java b/src/main/java/course_project/battleship_game/utils/Constants.java index 9b8b5577..62f5fbdd 100644 --- a/src/main/java/course_project/battleship_game/utils/Constants.java +++ b/src/main/java/course_project/battleship_game/utils/Constants.java @@ -1,6 +1,7 @@ package course_project.battleship_game.utils; public class Constants { + public static final int BOARD_SIZE = 10; public static final String DEFAULT_PLAYER_NAME = "Player"; public static final String DEFAULT_COMPUTER_NAME = "Computer"; public static final String WELCOME_MESSAGE = "Welcome to the Battleship game!\n"; diff --git a/src/main/java/course_project/battleship_game/utils/Validator.java b/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java similarity index 83% rename from src/main/java/course_project/battleship_game/utils/Validator.java rename to src/main/java/course_project/battleship_game/utils/CoordinateValidator.java index ef5f603a..56cffc5e 100644 --- a/src/main/java/course_project/battleship_game/utils/Validator.java +++ b/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java @@ -1,6 +1,6 @@ package course_project.battleship_game.utils; -public class Validator { +public class CoordinateValidator { public static boolean isCoordinate(String coordinate) { if (coordinate.length() > 3) { @@ -8,7 +8,7 @@ public static boolean isCoordinate(String coordinate) { } boolean isFirstLetter = coordinate.toUpperCase().charAt(0) > 64 && coordinate.toUpperCase().charAt(0) < 75; - boolean isNumber = isSuitableForCellCoordinate(coordinate.substring(1)); + boolean isNumber = coordinate.length() > 1 && isSuitableForCellCoordinate(coordinate.substring(1)); return isFirstLetter && isNumber; } diff --git a/src/main/java/course_project/battleship_game/utils/PrintUtils.java b/src/main/java/course_project/battleship_game/utils/PrintUtils.java new file mode 100644 index 00000000..81c66e22 --- /dev/null +++ b/src/main/java/course_project/battleship_game/utils/PrintUtils.java @@ -0,0 +1,53 @@ +package course_project.battleship_game.utils; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; + +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.PLAYER_BOARD_MESSAGE_FORMAT; +import static java.lang.System.lineSeparator; + +public class PrintUtils { + + public static void printMessage(String message) { + System.out.print(message); + } + + public static void printBoards(GameMode mode, Player player1, Player player2) { + if (mode.equals(GameMode.CVC) || !player1.getName().contains(DEFAULT_COMPUTER_NAME)) { + printBoardForPlayer(player1, false); + printBoardForPlayer(player2, true); + } + } + + public static void printBoardForPlayer(Player player, boolean isEnemy) { + printMessage(String.format(PLAYER_BOARD_MESSAGE_FORMAT, player.getName())); + printHeader(); + Cell[][] boardMatrix = player.getBoard().getBoardMatrix(); + for (int y = 0; y < boardMatrix.length; y++) { + printMessage((char) (65 + y) + " "); + for (int x = 0; x < boardMatrix.length; x++) { + printCell(isEnemy, boardMatrix[y][x]); + } + printMessage(lineSeparator()); + } + } + + private static void printCell(boolean isEnemy, Cell cell) { + if (isEnemy && cell.getCellStatus().equals(CellStatus.SHIP)) { + printMessage(CellStatus.EMPTY.getCharacter()); + } else { + printMessage(cell.getCellStatus().getCharacter()); + } + } + + private static void printHeader() { + printMessage(" "); + for (int i = 1; i < 11; i++) { + printMessage(i + " "); + } + printMessage(lineSeparator()); + } +} diff --git a/src/test/java/course_project/battleship_game/ViewTest.java b/src/test/java/course_project/battleship_game/ViewTest.java deleted file mode 100644 index e3d4bb41..00000000 --- a/src/test/java/course_project/battleship_game/ViewTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package course_project.battleship_game; - -import base.UnitBase; - -public class ViewTest extends UnitBase { -// private final View view = new View(); -// -// @ParameterizedTest -// @MethodSource("testCasesForGetPlayerName") -// void testGetPlayerName(final String input, final String expected) { -// setInput(input); -// String playerName = view.getPlayerName(); -// assertEquals(expected, playerName); -// } -// -// @ParameterizedTest -// @MethodSource("testCasesToGetGameModeSuccess") -// void testGetGameModeSuccess(final String input, final GameMode expected) { -// setInput(input); -// GameMode gameMode = view.getGameMode(); -// assertEquals(expected, gameMode); -// } -// -// @ParameterizedTest -// @MethodSource("testCasesToGetGameModeError") -// void testGetGameModeError(final String input, final String expected) { -// setInput("input"); -// view.getGameMode(); -// assertEquals(expected, getOutput()); -// } -// -// static Stream testCasesForGetPlayerName() { -// return Stream.of( -// Arguments.of("", DEFAULT_PLAYER_NAME), -// Arguments.of("PlayerName", "PlayerName") -// ); -// } -// -// static Stream testCasesToGetGameModeSuccess() { -// return Stream.of( -// Arguments.of("0", GameMode.CVC), -// Arguments.of("1", GameMode.PVC), -// Arguments.of("2", GameMode.PVP) -// ); -// } -// -// static Stream testCasesToGetGameModeError() { -// return Stream.of( -// Arguments.of("String", ERROR_INPUT_MESSAGE), -// Arguments.of("10", ERROR_INPUT_MESSAGE) -// ); -// } -} - From e159e8b538831ad66a291e1e5b999dc1a349f983 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 15 Sep 2021 20:31:03 +0300 Subject: [PATCH 66/80] refactoring course_project --- .../{view/View.java => utils/InputUtils.java} | 59 ++++--------------- 1 file changed, 11 insertions(+), 48 deletions(-) rename src/main/java/course_project/battleship_game/{view/View.java => utils/InputUtils.java} (58%) diff --git a/src/main/java/course_project/battleship_game/view/View.java b/src/main/java/course_project/battleship_game/utils/InputUtils.java similarity index 58% rename from src/main/java/course_project/battleship_game/view/View.java rename to src/main/java/course_project/battleship_game/utils/InputUtils.java index c420f5f8..8105eb44 100644 --- a/src/main/java/course_project/battleship_game/view/View.java +++ b/src/main/java/course_project/battleship_game/utils/InputUtils.java @@ -1,10 +1,7 @@ -package course_project.battleship_game.view; +package course_project.battleship_game.utils; import course_project.battleship_game.model.Cell; -import course_project.battleship_game.model.CellStatus; import course_project.battleship_game.model.GameMode; -import course_project.battleship_game.model.Player; -import course_project.battleship_game.utils.Validator; import java.io.BufferedReader; import java.io.IOException; @@ -17,19 +14,18 @@ import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; import static course_project.battleship_game.utils.Constants.GET_CELL_COORDINATE_MESSAGE; import static course_project.battleship_game.utils.Constants.GET_PLAYER_NAME_MESSAGE; -import static course_project.battleship_game.utils.Constants.PLAYER_BOARD_MESSAGE_FORMAT; -import static java.lang.System.lineSeparator; +import static course_project.battleship_game.utils.PrintUtils.printMessage; -public class View { +public class InputUtils { private static final BufferedReader READER = new BufferedReader(new InputStreamReader(System.in)); - public String getPlayerName() { + public static String getPlayerName() { printMessage(GET_PLAYER_NAME_MESSAGE); String line = readLine(); return line == null || line.isEmpty() ? DEFAULT_PLAYER_NAME : line; } - public GameMode getGameMode() { + public static GameMode getGameMode() { printMessage(CHOOSE_GAME_MODE_MESSAGE); String mode = readLine(); while (true) { @@ -46,20 +42,20 @@ public GameMode getGameMode() { } } - public int getModeToCreateFleet() { + public static int getModeToCreateFleet() { printMessage(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE); return getZeroOrOne(); } - public int getDirection() { + public static int getDirection() { printMessage(CHOOSE_SHIP_DIRECTION_MESSAGE); return getZeroOrOne(); } - public Cell getCell() { + public static Cell getCell() { printMessage(GET_CELL_COORDINATE_MESSAGE); String coordinate = readLine(); - while (!Validator.isCoordinate(coordinate)) { + while (!CoordinateValidator.isCoordinate(coordinate)) { printMessage(ERROR_INPUT_MESSAGE); coordinate = readLine(); } @@ -68,32 +64,7 @@ public Cell getCell() { return new Cell(x, y); } - public void printBoardForPlayer(Player player, boolean isEnemy) { - printMessage(String.format(PLAYER_BOARD_MESSAGE_FORMAT, player.getName())); - printHeader(); - Cell[][] boardMatrix = player.getBoard().getBoardMatrix(); - for (int y = 0; y < boardMatrix.length; y++) { - printMessage((char) (65 + y) + " "); - for (int x = 0; x < boardMatrix.length; x++) { - printCell(isEnemy, boardMatrix[y][x]); - } - printMessage(lineSeparator()); - } - } - - public void printMessage(String message) { - System.out.print(message); - } - - private void printCell(boolean isEnemy, Cell cell) { - if (isEnemy && cell.getCellStatus().equals(CellStatus.SHIP)) { - printMessage(CellStatus.EMPTY.getCharacter()); - } else { - printMessage(cell.getCellStatus().getCharacter()); - } - } - - private String readLine() { + private static String readLine() { try { return READER.readLine(); } catch (IOException e) { @@ -101,7 +72,7 @@ private String readLine() { } } - private int getZeroOrOne() { + private static int getZeroOrOne() { String mode = readLine(); while (true) { if (mode.equals("0") || mode.equals("1")) { @@ -112,12 +83,4 @@ private int getZeroOrOne() { } } - private void printHeader() { - printMessage(" "); - for (int i = 1; i < 11; i++) { - printMessage(i + " "); - } - printMessage(lineSeparator()); - } - } From 77ddf7147b9888b5f25194ce3e7e4cf4979dad0c Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 15 Sep 2021 20:33:29 +0300 Subject: [PATCH 67/80] add Mockito dependency --- build.gradle | 2 -- 1 file changed, 2 deletions(-) diff --git a/build.gradle b/build.gradle index 490be6e3..6bc2a810 100644 --- a/build.gradle +++ b/build.gradle @@ -13,9 +13,7 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' testCompile 'org.junit.jupiter:junit-jupiter-params:5.7.0' - testImplementation group: 'org.mockito', name: 'mockito-all', version: '1.10.19' - } test { From 7c3c5406eb42727348b184480f0ed9a6066c1bb9 Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 19 Sep 2021 21:04:21 +0300 Subject: [PATCH 68/80] refactor course_project --- .../course_project/battleship_game/Main.java | 7 +- .../controller/GameController.java | 5 + .../controller/GameControllerImpl.java | 41 ++++++ .../exception/GameException.java | 6 + .../battleship_game/model/Board.java | 16 ++- .../battleship_game/model/Ship.java | 15 ++- .../battleship_game/service/BoardService.java | 16 ++- .../service/CreateService.java | 118 ------------------ .../service/{Game.java => GameService.java} | 82 ++++++------ .../service/PlayerService.java | 86 ++++++++++--- .../battleship_game/utils/Constants.java | 2 + .../utils/RandomCellGenerator.java | 13 ++ .../battleship_game/BoardServiceTest.java | 74 +++++++++++ .../battleship_game/GameServiceTest.java | 90 +++++++++++++ .../battleship_game/PlayerServiceTest.java | 41 ++++++ .../battleship_game/ShipServiceTest.java | 58 +++++++++ .../battleship_game/utils/Constants.java | 11 +- .../utils/CoordinateValidatorTest.java | 35 ++++++ .../battleship_game/utils/InputUtilsTest.java | 94 ++++++++++++++ .../utils/RandomGenerator.java | 9 ++ 20 files changed, 633 insertions(+), 186 deletions(-) create mode 100644 src/main/java/course_project/battleship_game/controller/GameController.java create mode 100644 src/main/java/course_project/battleship_game/controller/GameControllerImpl.java create mode 100644 src/main/java/course_project/battleship_game/exception/GameException.java delete mode 100644 src/main/java/course_project/battleship_game/service/CreateService.java rename src/main/java/course_project/battleship_game/service/{Game.java => GameService.java} (52%) create mode 100644 src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java create mode 100644 src/test/java/course_project/battleship_game/BoardServiceTest.java create mode 100644 src/test/java/course_project/battleship_game/GameServiceTest.java create mode 100644 src/test/java/course_project/battleship_game/PlayerServiceTest.java create mode 100644 src/test/java/course_project/battleship_game/ShipServiceTest.java create mode 100644 src/test/java/course_project/battleship_game/utils/CoordinateValidatorTest.java create mode 100644 src/test/java/course_project/battleship_game/utils/InputUtilsTest.java create mode 100644 src/test/java/course_project/battleship_game/utils/RandomGenerator.java diff --git a/src/main/java/course_project/battleship_game/Main.java b/src/main/java/course_project/battleship_game/Main.java index 74f47f5c..3e38eb8d 100644 --- a/src/main/java/course_project/battleship_game/Main.java +++ b/src/main/java/course_project/battleship_game/Main.java @@ -1,11 +1,12 @@ package course_project.battleship_game; -import course_project.battleship_game.service.Game; +import course_project.battleship_game.controller.GameController; +import course_project.battleship_game.controller.GameControllerImpl; public class Main { public static void main(String[] args) { - Game game = new Game(); - game.run(); + GameController controller = new GameControllerImpl(); + controller.run(); } } \ No newline at end of file diff --git a/src/main/java/course_project/battleship_game/controller/GameController.java b/src/main/java/course_project/battleship_game/controller/GameController.java new file mode 100644 index 00000000..e57054da --- /dev/null +++ b/src/main/java/course_project/battleship_game/controller/GameController.java @@ -0,0 +1,5 @@ +package course_project.battleship_game.controller; + +public interface GameController { + void run(); +} diff --git a/src/main/java/course_project/battleship_game/controller/GameControllerImpl.java b/src/main/java/course_project/battleship_game/controller/GameControllerImpl.java new file mode 100644 index 00000000..92b2bb30 --- /dev/null +++ b/src/main/java/course_project/battleship_game/controller/GameControllerImpl.java @@ -0,0 +1,41 @@ +package course_project.battleship_game.controller; + +import course_project.battleship_game.exception.GameException; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.service.GameService; + +import static course_project.battleship_game.utils.Constants.EXCEPTION_MESSAGE; +import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; +import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; +import static course_project.battleship_game.utils.InputUtils.getGameMode; +import static course_project.battleship_game.utils.PrintUtils.printMessage; + +public class GameControllerImpl implements GameController { + private GameService service = new GameService(); + + @Override + public void run() { + printMessage(WELCOME_MESSAGE); + GameMode gameMode = getGameMode(); + Player[] players = service.createPlayers(gameMode); + service.rollingDiceToChooseWhoStarts(players); + try { + service.createFleet(players); + } catch (GameException e) { + printMessage(EXCEPTION_MESSAGE); + } + printMessage(FLEETS_CREATED_MESSAGE); + Player player1 = players[0]; + Player player2 = players[1]; + boolean isGameOver = false; + while (!isGameOver) { + isGameOver = service.isGameOver(player1, player2, gameMode); + if (!isGameOver) { + isGameOver = service.isGameOver(player2, player1, gameMode); + } + } + service.determineWinner(players); + } + +} diff --git a/src/main/java/course_project/battleship_game/exception/GameException.java b/src/main/java/course_project/battleship_game/exception/GameException.java new file mode 100644 index 00000000..47f20cfc --- /dev/null +++ b/src/main/java/course_project/battleship_game/exception/GameException.java @@ -0,0 +1,6 @@ +package course_project.battleship_game.exception; + +public class GameException extends RuntimeException { + public GameException() { + } +} diff --git a/src/main/java/course_project/battleship_game/model/Board.java b/src/main/java/course_project/battleship_game/model/Board.java index 93b48e62..6f08f3be 100644 --- a/src/main/java/course_project/battleship_game/model/Board.java +++ b/src/main/java/course_project/battleship_game/model/Board.java @@ -1,16 +1,16 @@ package course_project.battleship_game.model; -import course_project.battleship_game.service.CreateService; - import java.util.ArrayList; import java.util.List; +import static course_project.battleship_game.utils.Constants.BOARD_SIZE; + public class Board { private final Cell[][] boardMatrix; private final List shipList; public Board() { - this.boardMatrix = new CreateService().createBoard(); + this.boardMatrix = createBoard(); this.shipList = new ArrayList<>(); } @@ -22,4 +22,14 @@ public List getShipList() { return shipList; } + private Cell[][] createBoard() { + Cell[][] boardMatrix = new Cell[BOARD_SIZE][BOARD_SIZE]; + for (int y = 0; y < BOARD_SIZE; y++) { + for (int x = 0; x < BOARD_SIZE; x++) { + boardMatrix[y][x] = new Cell(x, y, CellStatus.EMPTY); + } + } + return boardMatrix; + } + } diff --git a/src/main/java/course_project/battleship_game/model/Ship.java b/src/main/java/course_project/battleship_game/model/Ship.java index 5efb49f7..40f15485 100644 --- a/src/main/java/course_project/battleship_game/model/Ship.java +++ b/src/main/java/course_project/battleship_game/model/Ship.java @@ -1,7 +1,6 @@ package course_project.battleship_game.model; -import course_project.battleship_game.service.CreateService; - +import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -11,7 +10,7 @@ public class Ship { public Ship(Cell start, ShipType type, int direction) { this.type = type; - this.cellsList = new CreateService().createShipCells(start, type, direction); + this.cellsList = generateShipCells(start, type, direction); } public ShipType getType() { @@ -35,4 +34,14 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(getType(), getCellsList()); } + + private static List generateShipCells(Cell start, ShipType type, int direction) { + List cells = new ArrayList<>(); + for (int i = 0; i < type.getLength(); i++) { + int x = direction == 1 ? start.getX() : start.getX() + i; + int y = direction == 1 ? start.getY() + i : start.getY(); + cells.add(new Cell(x, y, CellStatus.SHIP)); + } + return cells; + } } diff --git a/src/main/java/course_project/battleship_game/service/BoardService.java b/src/main/java/course_project/battleship_game/service/BoardService.java index 9d8987a5..f08d3ad6 100644 --- a/src/main/java/course_project/battleship_game/service/BoardService.java +++ b/src/main/java/course_project/battleship_game/service/BoardService.java @@ -17,8 +17,19 @@ public BoardService(Board board) { this.board = board; } - public long countRemainedShipsForBoard() { - return board.getShipList().stream().filter(ship -> !new ShipService(ship).isNotAlive()).count(); + public boolean isHitCellOnBoard(Cell cell) { + Ship shipResult = board.getShipList().stream() + .filter(ship -> + ship.getCellsList().stream() + .anyMatch(cell1 -> cell1.equals(cell))).findFirst().orElse(null); + boolean hit = false; + if (shipResult != null) { + hit = new ShipService(shipResult).isHit(cell); + } + if (!hit) { + board.getBoardMatrix()[cell.getY()][cell.getX()].setCellStatus(CellStatus.MISSED); + } + return hit; } public boolean isCreatingShipSuccessful(Cell start, ShipType type, int direction) { @@ -107,4 +118,5 @@ private boolean isTypeNotEnoughInBoardShipList(ShipType type) { int count = (int) board.getShipList().stream().filter(ship -> ship.getType().equals(type)).count(); return count < type.getAmount(); } + } diff --git a/src/main/java/course_project/battleship_game/service/CreateService.java b/src/main/java/course_project/battleship_game/service/CreateService.java deleted file mode 100644 index a96bcfd0..00000000 --- a/src/main/java/course_project/battleship_game/service/CreateService.java +++ /dev/null @@ -1,118 +0,0 @@ -package course_project.battleship_game.service; - -import course_project.battleship_game.model.Cell; -import course_project.battleship_game.model.CellStatus; -import course_project.battleship_game.model.GameMode; -import course_project.battleship_game.model.Player; -import course_project.battleship_game.model.ShipType; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -import static course_project.battleship_game.utils.Constants.BOARD_SIZE; -import static course_project.battleship_game.utils.Constants.CREATING_FLEET_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.CREATING_SHIP_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; -import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; -import static course_project.battleship_game.utils.Constants.FLEET_CREATED_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.Constants.REMAINING_AMOUNT_OF_TYPE_TO_CREATE; -import static course_project.battleship_game.utils.Constants.SHIP_CREATED_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.InputUtils.getCell; -import static course_project.battleship_game.utils.InputUtils.getDirection; -import static course_project.battleship_game.utils.InputUtils.getModeToCreateFleet; -import static course_project.battleship_game.utils.InputUtils.getPlayerName; -import static course_project.battleship_game.utils.PrintUtils.printBoardForPlayer; -import static course_project.battleship_game.utils.PrintUtils.printMessage; - -public class CreateService { - - public Cell[][] createBoard() { - Cell[][] boardMatrix = new Cell[BOARD_SIZE][BOARD_SIZE]; - for (int y = 0; y < BOARD_SIZE; y++) { - for (int x = 0; x < BOARD_SIZE; x++) { - boardMatrix[y][x] = new Cell(x, y, CellStatus.EMPTY); - } - } - return boardMatrix; - } - - public Player[] createPlayers(GameMode mode) { - Player[] players = new Player[2]; - players[0] = mode.equals(GameMode.CVC) ? new Player(DEFAULT_COMPUTER_NAME + " Mimi", 0) : - new Player(getPlayerName(), getModeToCreateFleet()); - players[1] = !mode.equals(GameMode.PVP) ? new Player(DEFAULT_COMPUTER_NAME + " Navi", 0) : - new Player(getPlayerName(), getModeToCreateFleet()); - return players; - } - - public void createFleet(Player player) { - printMessage(String.format(CREATING_FLEET_MESSAGE_FORMAT, player.getName())); - if (player.getModeToCreateFleet() == 0) { - createRightAmountOfTypeRandomly(player, ShipType.BATTLESHIP); - createRightAmountOfTypeRandomly(player, ShipType.CRUISER); - createRightAmountOfTypeRandomly(player, ShipType.DESTROYER); - createRightAmountOfTypeRandomly(player, ShipType.TORPEDO_BOAT); - } else { - createRightAmountOfTypeManually(player, ShipType.BATTLESHIP); - createRightAmountOfTypeManually(player, ShipType.CRUISER); - createRightAmountOfTypeManually(player, ShipType.DESTROYER); - createRightAmountOfTypeManually(player, ShipType.TORPEDO_BOAT); - } - printMessage(String.format(FLEET_CREATED_MESSAGE_FORMAT, player.getName())); - } - - public Cell createRandomCell() { - int x = ThreadLocalRandom.current().nextInt(0, 10); - int y = ThreadLocalRandom.current().nextInt(0, 10); - return new Cell(x, y); - } - - public List createShipCells(Cell start, ShipType type, int direction) { - List cells = new ArrayList<>(); - for (int i = 0; i < type.getLength(); i++) { - int x = direction == 1 ? start.getX() : start.getX() + i; - int y = direction == 1 ? start.getY() + i : start.getY(); - cells.add(new Cell(x, y, CellStatus.SHIP)); - } - return cells; - } - - private void createRightAmountOfTypeManually(Player player, ShipType type) { - printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); - int count = 0; - while (count != type.getAmount()) { - Cell start = getCell(); - int direction = getDirection(); - start.setCellStatus(CellStatus.SHIP); - boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); - if (created) { - count++; - if (type.getAmount() - count != 0) { - printMessage(String.format(REMAINING_AMOUNT_OF_TYPE_TO_CREATE, - type.name().replace("_", " ").toLowerCase(), type.getAmount() - count)); - } - printBoardForPlayer(player, false); - } else { - printMessage(ERROR_INPUT_MESSAGE); - } - } - printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, - "You", type.getAmount(), type.name().replace("_", " ").toLowerCase())); - } - - private void createRightAmountOfTypeRandomly(Player player, ShipType type) { - printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); - int count = 0; - while (count != type.getAmount()) { - Cell start = createRandomCell(); - int direction = ThreadLocalRandom.current().nextInt(0, 2); - boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); - if (created) { - count++; - } - } - printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, - player.getName(), type.getAmount(), type.name().replace("_", " ").toLowerCase())); - } -} diff --git a/src/main/java/course_project/battleship_game/service/Game.java b/src/main/java/course_project/battleship_game/service/GameService.java similarity index 52% rename from src/main/java/course_project/battleship_game/service/Game.java rename to src/main/java/course_project/battleship_game/service/GameService.java index da115cb6..1758c838 100644 --- a/src/main/java/course_project/battleship_game/service/Game.java +++ b/src/main/java/course_project/battleship_game/service/GameService.java @@ -1,56 +1,36 @@ package course_project.battleship_game.service; +import course_project.battleship_game.exception.GameException; import course_project.battleship_game.model.GameMode; import course_project.battleship_game.model.Player; import java.util.concurrent.ThreadLocalRandom; -import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; import static course_project.battleship_game.utils.Constants.PLAYER_TURN_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.PLAYER_WINNER_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.ROLLING_DICE_MESSAGE; -import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; -import static course_project.battleship_game.utils.InputUtils.getGameMode; +import static course_project.battleship_game.utils.InputUtils.getModeToCreateFleet; +import static course_project.battleship_game.utils.InputUtils.getPlayerName; import static course_project.battleship_game.utils.PrintUtils.printBoards; import static course_project.battleship_game.utils.PrintUtils.printMessage; -public class Game { +public class GameService { - public void run() { - printMessage(WELCOME_MESSAGE); - GameMode gameMode = getGameMode(); - CreateService createService = new CreateService(); - Player[] players = createService.createPlayers(gameMode); - rollingDiceToChooseWhoStarts(players); - Player player1 = players[0]; - Player player2 = players[1]; - createService.createFleet(player1); - createService.createFleet(player2); - printMessage(FLEETS_CREATED_MESSAGE); - boolean isGameOver = false; - while (!isGameOver) { - isGameOver = isGameOver(player1, player2, gameMode); - if (!isGameOver) { - isGameOver = isGameOver(player2, player1, gameMode); - } - } - determineWinner(player1, player2); - } - - private boolean isGameOver(Player player1, Player player2, GameMode gameMode) { - boolean isMoveSuccessful = true; - printMessage(String.format(PLAYER_TURN_MESSAGE_FORMAT, player1.getName())); - while (isMoveSuccessful && !isNoMoreAliveShips(player1, player2)) { - isMoveSuccessful = new PlayerService(player1).isMoveSuccessful(player2); - printBoards(gameMode, player1, player2); - } - return isNoMoreAliveShips(player1, player2); + public Player[] createPlayers(GameMode mode) { + Player[] players = new Player[2]; + players[0] = mode.equals(GameMode.CVC) ? new Player(DEFAULT_COMPUTER_NAME + " Mimi", 0) : + new Player(getPlayerName(), getModeToCreateFleet()); + players[1] = !mode.equals(GameMode.PVP) ? new Player(DEFAULT_COMPUTER_NAME + " Navi", 0) : + new Player(getPlayerName(), getModeToCreateFleet()); + return players; } - private void rollingDiceToChooseWhoStarts(Player[] players) { + public void rollingDiceToChooseWhoStarts(Player[] players) { printMessage(ROLLING_DICE_MESSAGE); - int dice = ThreadLocalRandom.current().nextInt(0, 2); - if (dice == 1) { + int dice = ThreadLocalRandom.current().nextInt(1, 3); + printMessage("Dice is " + dice + "\n"); + if (dice == 2) { Player temp = players[0]; players[0] = players[1]; players[1] = temp; @@ -58,17 +38,37 @@ private void rollingDiceToChooseWhoStarts(Player[] players) { printMessage(players[0].getName() + " will go first\n"); } - private boolean isNoMoreAliveShips(Player player1, Player player2) { - return new PlayerService(player1).isNoMoreAliveShipsForBoard() || new PlayerService(player2).isNoMoreAliveShipsForBoard(); + public void createFleet(Player[] players) { + if (players.length != 2) { + throw new GameException(); + } + new PlayerService(players[0]).createFleetForPlayer(); + new PlayerService(players[1]).createFleetForPlayer(); } - private void determineWinner(Player player1, Player player2) { + public boolean isGameOver(Player player1, Player player2, GameMode gameMode) { + boolean isMoveSuccessful = true; + printMessage(String.format(PLAYER_TURN_MESSAGE_FORMAT, player1.getName())); + while (isMoveSuccessful && !isNoMoreAliveShips(player1, player2)) { + isMoveSuccessful = new PlayerService(player1).isMoveSuccessful(player2); + printBoards(gameMode, player1, player2); + } + return isNoMoreAliveShips(player1, player2); + } + + public void determineWinner(Player[] players) { + Player player1 = players[0]; + Player player2 = players[1]; if (isNoMoreAliveShips(player1, player2)) { - long player1Fleet = new BoardService(player1.getBoard()).countRemainedShipsForBoard(); - long player2Fleet = new BoardService(player2.getBoard()).countRemainedShipsForBoard(); + long player1Fleet = new PlayerService(player1).countRemainedShips(); + long player2Fleet = new PlayerService(player2).countRemainedShips(); Player winner = player1Fleet > player2Fleet ? player1 : player2; printMessage(String.format(PLAYER_WINNER_MESSAGE_FORMAT, winner.getName())); } } + private boolean isNoMoreAliveShips(Player player1, Player player2) { + return new PlayerService(player1).isNoMoreAliveShips() || new PlayerService(player2).isNoMoreAliveShips(); + } + } diff --git a/src/main/java/course_project/battleship_game/service/PlayerService.java b/src/main/java/course_project/battleship_game/service/PlayerService.java index f18d85d6..330f74a0 100644 --- a/src/main/java/course_project/battleship_game/service/PlayerService.java +++ b/src/main/java/course_project/battleship_game/service/PlayerService.java @@ -1,17 +1,27 @@ package course_project.battleship_game.service; -import course_project.battleship_game.model.Board; import course_project.battleship_game.model.Cell; import course_project.battleship_game.model.CellStatus; import course_project.battleship_game.model.Player; -import course_project.battleship_game.model.Ship; +import course_project.battleship_game.model.ShipType; +import course_project.battleship_game.utils.RandomCellGenerator; +import java.util.concurrent.ThreadLocalRandom; + +import static course_project.battleship_game.utils.Constants.CREATING_FLEET_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.CREATING_SHIP_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.FLEET_CREATED_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.HIT_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.MISSED_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.PLAYER_MOVE_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.REMAINING_AMOUNT_OF_TYPE_TO_CREATE; import static course_project.battleship_game.utils.Constants.SAME_COORDINATE_ERROR_MESSAGE; +import static course_project.battleship_game.utils.Constants.SHIP_CREATED_MESSAGE_FORMAT; import static course_project.battleship_game.utils.InputUtils.getCell; +import static course_project.battleship_game.utils.InputUtils.getDirection; +import static course_project.battleship_game.utils.PrintUtils.printBoardForPlayer; import static course_project.battleship_game.utils.PrintUtils.printMessage; public class PlayerService { @@ -25,7 +35,7 @@ public boolean isMoveSuccessful(Player enemy) { Cell cell = null; while (cell == null || !player.getLogOfMoves().contains(cell)) { if (player.getName().contains(DEFAULT_COMPUTER_NAME)) { - cell = new CreateService().createRandomCell(); + cell = RandomCellGenerator.generateRandomCell(); } else { cell = getCell(); } @@ -40,7 +50,7 @@ public boolean isMoveSuccessful(Player enemy) { } } printMessage(String.format(PLAYER_MOVE_MESSAGE_FORMAT, player.getName(), cell.toString())); - boolean hit = isHitCellOnBoard(enemy.getBoard(), cell); //new BoardService(enemy.getBoard()).isHitCellOnBoard(cell); + boolean hit = new BoardService(enemy.getBoard()).isHitCellOnBoard(cell); if (hit) { printMessage(String.format(HIT_MESSAGE_FORMAT, player.getName(), enemy.getName(), cell.toString())); } else { @@ -49,20 +59,66 @@ public boolean isMoveSuccessful(Player enemy) { return hit; } - - public boolean isNoMoreAliveShipsForBoard() { + public boolean isNoMoreAliveShips() { return player.getBoard().getShipList().stream().allMatch(ship -> new ShipService(ship).isNotAlive()); } - private boolean isHitCellOnBoard(Board board, Cell cell) { - Ship shipResult = board.getShipList().stream() - .filter(ship -> - ship.getCellsList().stream() - .anyMatch(cell1 -> cell1.equals(cell))).findFirst().orElse(null); - boolean hit = shipResult != null && new ShipService(shipResult).isHit(cell); - if (!hit) { - board.getBoardMatrix()[cell.getY()][cell.getX()].setCellStatus(CellStatus.MISSED); + public void createFleetForPlayer() { + printMessage(String.format(CREATING_FLEET_MESSAGE_FORMAT, player.getName())); + if (player.getModeToCreateFleet() == 0) { + createRightAmountOfTypeRandomly(ShipType.BATTLESHIP); + createRightAmountOfTypeRandomly(ShipType.CRUISER); + createRightAmountOfTypeRandomly(ShipType.DESTROYER); + createRightAmountOfTypeRandomly(ShipType.TORPEDO_BOAT); + } else { + createRightAmountOfTypeManually(ShipType.BATTLESHIP); + createRightAmountOfTypeManually(ShipType.CRUISER); + createRightAmountOfTypeManually(ShipType.DESTROYER); + createRightAmountOfTypeManually(ShipType.TORPEDO_BOAT); } - return hit; + printMessage(String.format(FLEET_CREATED_MESSAGE_FORMAT, player.getName())); } + + public long countRemainedShips() { + return player.getBoard().getShipList().stream().filter(ship -> !new ShipService(ship).isNotAlive()).count(); + } + + private void createRightAmountOfTypeManually(ShipType type) { + printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = getCell(); + int direction = getDirection(); + start.setCellStatus(CellStatus.SHIP); + boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + if (type.getAmount() - count != 0) { + printMessage(String.format(REMAINING_AMOUNT_OF_TYPE_TO_CREATE, + type.name().replace("_", " ").toLowerCase(), type.getAmount() - count)); + } + printBoardForPlayer(player, false); + } else { + printMessage(ERROR_INPUT_MESSAGE); + } + } + printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + "You", type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } + + private void createRightAmountOfTypeRandomly(ShipType type) { + printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = RandomCellGenerator.generateRandomCell(); + int direction = ThreadLocalRandom.current().nextInt(0, 2); + boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + } + } + printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + player.getName(), type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } + } diff --git a/src/main/java/course_project/battleship_game/utils/Constants.java b/src/main/java/course_project/battleship_game/utils/Constants.java index 62f5fbdd..b41e95dc 100644 --- a/src/main/java/course_project/battleship_game/utils/Constants.java +++ b/src/main/java/course_project/battleship_game/utils/Constants.java @@ -17,6 +17,7 @@ public class Constants { "1 - place your ships by yourself.\n"; public static final String CHOOSE_SHIP_DIRECTION_MESSAGE = "Put 0 - for horizontal placement or 1 - for vertical placement\n"; public static final String GET_CELL_COORDINATE_MESSAGE = "Type coordinate in format (Letters from A to J, numbers from 1 to 10)\n"; + public static final String EXCEPTION_MESSAGE = "Something went wrong. Please, restart the program.\n"; public static final String ERROR_INPUT_MESSAGE = "Wrong input.\n"; public static final String SAME_COORDINATE_ERROR_MESSAGE = "You have already done this move. Please try again!\n"; public static final String PLAYER_BOARD_MESSAGE_FORMAT = "\nThis is %s's board\n"; @@ -30,4 +31,5 @@ public class Constants { public static final String CREATING_SHIP_MESSAGE_FORMAT = "Creating %s\n"; public static final String SHIP_CREATED_MESSAGE_FORMAT = "%s successfully created %d %s(s).\n"; public static final String REMAINING_AMOUNT_OF_TYPE_TO_CREATE = "Remaining amount of %ss is %d\n"; + } diff --git a/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java b/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java new file mode 100644 index 00000000..09e2a49f --- /dev/null +++ b/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java @@ -0,0 +1,13 @@ +package course_project.battleship_game.utils; + +import course_project.battleship_game.model.Cell; + +import java.util.concurrent.ThreadLocalRandom; + +public class RandomCellGenerator { + public static Cell generateRandomCell() { + int x = ThreadLocalRandom.current().nextInt(0, 10); + int y = ThreadLocalRandom.current().nextInt(0, 10); + return new Cell(x, y); + } +} diff --git a/src/test/java/course_project/battleship_game/BoardServiceTest.java b/src/test/java/course_project/battleship_game/BoardServiceTest.java new file mode 100644 index 00000000..be8e17ad --- /dev/null +++ b/src/test/java/course_project/battleship_game/BoardServiceTest.java @@ -0,0 +1,74 @@ +package course_project.battleship_game; + +import course_project.battleship_game.model.Board; +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; +import course_project.battleship_game.model.ShipType; +import course_project.battleship_game.service.BoardService; +import course_project.battleship_game.utils.RandomGenerator; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +public class BoardServiceTest { + + @ParameterizedTest + @MethodSource("testCasesIsHitCellOnBoard") + void isHitCellOnBoardTrue(final Ship ship) { + Board board = Mockito.mock(Board.class); + BoardService boardService = new BoardService(board); + when(board.getShipList()).thenReturn(new ArrayList<>(Arrays.asList(ship))); + assertTrue(boardService.isHitCellOnBoard(ship.getCellsList().get(0))); + } + + @Test + void isHitCellOnBoardFalse() { + Board board = new Board(); + BoardService boardService = new BoardService(board); + Cell cell = new Cell(1, 1); + assertFalse(boardService.isHitCellOnBoard(cell)); + } + + @Test + void testIsCreatingShipSuccessfulTrue() { + Board board = new Board(); + BoardService boardService = new BoardService(board); + assertTrue(boardService.isCreatingShipSuccessful(new Cell(0, 0, CellStatus.SHIP), ShipType.TORPEDO_BOAT, 0)); + } + + @Test + void testIsCreatingShipSuccessfulFalse() { + Board board = Mockito.mock(Board.class); + BoardService boardService = new BoardService(board); + Cell start = new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()); + Ship ship = new Ship(start, ShipType.BATTLESHIP, 0); + when(board.getShipList()).thenReturn(new ArrayList<>(Arrays.asList(ship))); + assertFalse(boardService.isCreatingShipSuccessful(start, ShipType.BATTLESHIP, 0)); + } + + static Stream testCasesIsHitCellOnBoard() { + return Stream.of( + Arguments.of( + new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.BATTLESHIP, 0)), + Arguments.of(new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.TORPEDO_BOAT, 0)), + Arguments.of(new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.CRUISER, 1)), + Arguments.of(new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.DESTROYER, 1)) + ); + } + +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/GameServiceTest.java b/src/test/java/course_project/battleship_game/GameServiceTest.java new file mode 100644 index 00000000..0acf71d3 --- /dev/null +++ b/src/test/java/course_project/battleship_game/GameServiceTest.java @@ -0,0 +1,90 @@ +package course_project.battleship_game; + +import base.UnitBase; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.service.GameService; +import course_project.battleship_game.service.PlayerService; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GameServiceTest extends UnitBase { + private final GameService service = new GameService(); + + @Test + void testCreateUsersCVC() { + Player[] players = service.createPlayers(GameMode.CVC); + assertEquals(2, players.length); + assertTrue(players[0].getName().contains("Computer")); + assertTrue(players[1].getName().contains("Computer")); + } + + @Test + void testCreateUsersPVC() { + setInput("test\n0"); + Player[] players = service.createPlayers(GameMode.PVC); + assertEquals(2, players.length); + assertFalse(players[0].getName().contains("Computer")); + assertTrue(players[1].getName().contains("Computer")); + } + + @Test + void testCreateUsersPVP() { + setInput("test\n0\ntest1\n0"); + Player[] players = service.createPlayers(GameMode.PVP); + assertEquals(2, players.length); + assertFalse(players[0].getName().contains("Computer")); + assertFalse(players[1].getName().contains("Computer")); + } + + + @Test + void testRollingDiceShufflePlayers() { + Player[] players = service.createPlayers(GameMode.CVC); + Player one = players[0]; + service.rollingDiceToChooseWhoStarts(players); + if (getOutput().contains("1")) { + assertEquals(one, players[0]); + } else { + assertNotEquals(one, players[0]); + } + + } + + @Test + void testCreateFleet() { + Player[] players = service.createPlayers(GameMode.CVC); + service.createFleet(players); + assertEquals(10, players[0].getBoard().getShipList().size()); + assertEquals(10, players[1].getBoard().getShipList().size()); + } + + @Test + void testIsGameOverOnStart() { + Player[] players = service.createPlayers(GameMode.CVC); + service.createFleet(players); + assertFalse(service.isGameOver(players[0], players[1], GameMode.CVC)); + } + + @Test + void testIsGameOverTrue() { + Player[] players = service.createPlayers(GameMode.CVC); + PlayerService playerService = new PlayerService(players[0]); + playerService.createFleetForPlayer(); + assertTrue(service.isGameOver(players[0], players[1], GameMode.CVC)); + } + + @Test + void testDetermineWinner() { + Player[] players = service.createPlayers(GameMode.CVC); + PlayerService playerService = new PlayerService(players[0]); + playerService.createFleetForPlayer(); + service.determineWinner(players); + assertTrue(getOutput().contains(players[0].getName())); + } + +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/PlayerServiceTest.java b/src/test/java/course_project/battleship_game/PlayerServiceTest.java new file mode 100644 index 00000000..0b1d7a4e --- /dev/null +++ b/src/test/java/course_project/battleship_game/PlayerServiceTest.java @@ -0,0 +1,41 @@ +package course_project.battleship_game; + +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.service.PlayerService; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PlayerServiceTest { + + @Test + void testCreateRandomFleetForPlayer() { + Player hero = new Player("Hero", 0); + PlayerService serviceHero = new PlayerService(hero); + serviceHero.createFleetForPlayer(); + assertEquals(10, hero.getBoard().getShipList().size()); + } + + @Test + void testIsNoMoreAliveShipsTrue() { + Player hero = new Player("Hero", 0); + PlayerService serviceHero = new PlayerService(hero); + serviceHero.createFleetForPlayer(); + hero.getBoard().getShipList().forEach(ship -> ship.getCellsList().forEach(cell -> cell.setCellStatus(CellStatus.HIT))); + assertTrue(serviceHero.isNoMoreAliveShips()); + assertEquals(0, serviceHero.countRemainedShips()); + } + + @Test + void testIsNoMoreAliveShipsFalse() { + Player hero = new Player("Hero", 0); + PlayerService serviceHero = new PlayerService(hero); + serviceHero.createFleetForPlayer(); + assertFalse(serviceHero.isNoMoreAliveShips()); + assertEquals(10, serviceHero.countRemainedShips()); + } + +} diff --git a/src/test/java/course_project/battleship_game/ShipServiceTest.java b/src/test/java/course_project/battleship_game/ShipServiceTest.java new file mode 100644 index 00000000..1493f4b4 --- /dev/null +++ b/src/test/java/course_project/battleship_game/ShipServiceTest.java @@ -0,0 +1,58 @@ +package course_project.battleship_game; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; +import course_project.battleship_game.service.ShipService; +import course_project.battleship_game.utils.RandomGenerator; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +public class ShipServiceTest { + + @ParameterizedTest + @MethodSource("testCasesIsHit") + void testIsHit(final Cell cell) { + Ship shipTrue = Mockito.mock(Ship.class); + Ship shipFalse = Mockito.mock(Ship.class); + ShipService shipServiceTrue = new ShipService(shipTrue); + ShipService shipServiceFalse = new ShipService(shipFalse); + when(shipTrue.getCellsList()).thenReturn(new ArrayList<>(Arrays.asList(cell))); + assertTrue(shipServiceTrue.isHit(cell)); + when(shipFalse.getCellsList()).thenReturn(new ArrayList<>()); + assertFalse(shipServiceFalse.isHit(cell)); + } + + @Test + void testIsNotAlive() { + Ship ship = Mockito.mock(Ship.class); + ShipService shipService = new ShipService(ship); + when(ship.getCellsList()) + .thenReturn(new ArrayList<>(Collections.singletonList( + new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9(), CellStatus.HIT)))); + assertTrue(shipService.isNotAlive()); + } + + static Stream testCasesIsHit() { + return Stream.of( + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())), + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())), + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())), + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())) + ); + } + + +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/utils/Constants.java b/src/test/java/course_project/battleship_game/utils/Constants.java index e5b210df..93037d40 100644 --- a/src/test/java/course_project/battleship_game/utils/Constants.java +++ b/src/test/java/course_project/battleship_game/utils/Constants.java @@ -2,5 +2,14 @@ public class Constants { public static final String DEFAULT_PLAYER_NAME = "Player"; - public static final String ERROR_INPUT_MESSAGE = "Wrong input.\n"; + public static final String ERROR_INPUT_MESSAGE = "Wrong input."; + public static final String CHOOSE_SHIP_DIRECTION_MESSAGE = "Put 0 - for horizontal placement or 1 - for vertical placement"; + public static final String CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE = "\nChoose mode:\n" + + "0 - place your ships randomly\n" + + "1 - place your ships by yourself."; + public static final String CHOOSE_GAME_MODE_MESSAGE = "Choose game mode:\n" + + "0 - Computer vs Computer\n" + + "1 - Computer vs Player\n" + + "2 - Player vs Player"; + public static final String GET_PLAYER_NAME_MESSAGE = "Enter your name:"; } diff --git a/src/test/java/course_project/battleship_game/utils/CoordinateValidatorTest.java b/src/test/java/course_project/battleship_game/utils/CoordinateValidatorTest.java new file mode 100644 index 00000000..b33726b3 --- /dev/null +++ b/src/test/java/course_project/battleship_game/utils/CoordinateValidatorTest.java @@ -0,0 +1,35 @@ +package course_project.battleship_game.utils; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +public class CoordinateValidatorTest { + + @ParameterizedTest + @MethodSource("testCasesIsCoordinate") + void test(final String coordinate, final boolean expected) { + assertEquals(expected, CoordinateValidator.isCoordinate(coordinate)); + } + + static Stream testCasesIsCoordinate() { + return Stream.of( + Arguments.of("A1", true), + Arguments.of("a10", true), + Arguments.of("j1", true), + Arguments.of("J10", true), + Arguments.of("K6", false), + Arguments.of("x10", false), + Arguments.of("I11", false), + Arguments.of("1", false), + Arguments.of("y", false), + Arguments.of("i 9", false), + Arguments.of("90", false) + ); + } +} diff --git a/src/test/java/course_project/battleship_game/utils/InputUtilsTest.java b/src/test/java/course_project/battleship_game/utils/InputUtilsTest.java new file mode 100644 index 00000000..0b4b62ce --- /dev/null +++ b/src/test/java/course_project/battleship_game/utils/InputUtilsTest.java @@ -0,0 +1,94 @@ +package course_project.battleship_game.utils; + +import base.UnitBase; +import course_project.battleship_game.model.GameMode; +import org.junit.jupiter.api.Test; + +import static course_project.battleship_game.utils.Constants.CHOOSE_GAME_MODE_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_SHIP_DIRECTION_MESSAGE; +import static course_project.battleship_game.utils.Constants.DEFAULT_PLAYER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.GET_PLAYER_NAME_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class InputUtilsTest extends UnitBase { + + @Test + void testGetNameString() { + setInput("Hero"); + String playerName = InputUtils.getPlayerName(); + assertEquals("Hero", playerName); + assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); + } + + @Test + void testGetNameStringNumber() { + setInput("11"); + String playerName = InputUtils.getPlayerName(); + assertEquals("11", playerName); + assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); + } + + @Test + void testGetNameEmptyString() { + setInput(""); + String playerName = InputUtils.getPlayerName(); + assertEquals(DEFAULT_PLAYER_NAME, playerName); + assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); + } + + @Test + void testGetDirectionZero() { + setInput("2\nString\n0"); + assertEquals(0, InputUtils.getDirection()); + assertTrue(getOutput().contains(ERROR_INPUT_MESSAGE)); + assertTrue(getOutput().contains(CHOOSE_SHIP_DIRECTION_MESSAGE.trim())); + } + + @Test + void testGetDirectionOne() { + setInput("1"); + assertEquals(1, InputUtils.getDirection()); + assertTrue(getOutput().contains(CHOOSE_SHIP_DIRECTION_MESSAGE.trim())); + } + + @Test + void testGetModeToCreateFleetZero() { + setInput("2\nString\n0"); + assertEquals(0, InputUtils.getModeToCreateFleet()); + assertTrue(getOutput().contains(ERROR_INPUT_MESSAGE.trim())); + assertTrue(getOutput().contains(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE.trim())); + } + + @Test + void testGetModeToCreateFleetOne() { + setInput("1"); + assertEquals(1, InputUtils.getModeToCreateFleet()); + assertTrue(getOutput().contains(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE.trim())); + } + + @Test + void testGetGameModeCVC() { + setInput("0"); + assertEquals(GameMode.CVC, InputUtils.getGameMode()); + assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); + } + + @Test + void testGetGameModePVC() { + setInput("1"); + assertEquals(GameMode.PVC, InputUtils.getGameMode()); + assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); + } + + @Test + void testGetGameModePVP() { + setInput("s\n5\n2"); + assertEquals(GameMode.PVP, InputUtils.getGameMode()); + assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); + } + +} diff --git a/src/test/java/course_project/battleship_game/utils/RandomGenerator.java b/src/test/java/course_project/battleship_game/utils/RandomGenerator.java new file mode 100644 index 00000000..377ccd5b --- /dev/null +++ b/src/test/java/course_project/battleship_game/utils/RandomGenerator.java @@ -0,0 +1,9 @@ +package course_project.battleship_game.utils; + +import java.util.concurrent.ThreadLocalRandom; + +public class RandomGenerator { + public static int generateNumFrom0to9() { + return ThreadLocalRandom.current().nextInt(0, 10); + } +} From 860a78301b27057854175ddb3e52976d44949c4b Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 19 Sep 2021 21:15:46 +0300 Subject: [PATCH 69/80] refactor course_project --- .../battleship_game/service/PlayerService.java | 2 +- .../course_project/battleship_game/utils/Constants.java | 2 +- .../course_project/battleship_game/GameServiceTest.java | 7 +++---- .../course_project/battleship_game/utils/Constants.java | 1 + 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/course_project/battleship_game/service/PlayerService.java b/src/main/java/course_project/battleship_game/service/PlayerService.java index 330f74a0..3d3de73f 100644 --- a/src/main/java/course_project/battleship_game/service/PlayerService.java +++ b/src/main/java/course_project/battleship_game/service/PlayerService.java @@ -45,8 +45,8 @@ public boolean isMoveSuccessful(Player enemy) { } else { if (!player.getName().contains(DEFAULT_COMPUTER_NAME)) { printMessage(SAME_COORDINATE_ERROR_MESSAGE); - cell = null; } + cell = null; } } printMessage(String.format(PLAYER_MOVE_MESSAGE_FORMAT, player.getName(), cell.toString())); diff --git a/src/main/java/course_project/battleship_game/utils/Constants.java b/src/main/java/course_project/battleship_game/utils/Constants.java index b41e95dc..4ee0edac 100644 --- a/src/main/java/course_project/battleship_game/utils/Constants.java +++ b/src/main/java/course_project/battleship_game/utils/Constants.java @@ -24,7 +24,7 @@ public class Constants { public static final String PLAYER_TURN_MESSAGE_FORMAT = "\nNow it is %s's turn\n"; public static final String PLAYER_MOVE_MESSAGE_FORMAT = "%s made move on %s.\n"; public static final String HIT_MESSAGE_FORMAT = "%s has just hit the ship of %s located on %s!\n"; - public static final String PLAYER_WINNER_MESSAGE_FORMAT = "Congratulations %s! You won the game!"; + public static final String PLAYER_WINNER_MESSAGE_FORMAT = "\nCongratulations %s! You won the game!\n"; public static final String MISSED_MESSAGE_FORMAT = "%s missed on %s.\n"; public static final String CREATING_FLEET_MESSAGE_FORMAT = "\nCreating fleet for %s\n"; public static final String FLEET_CREATED_MESSAGE_FORMAT = "The fleet for %s has been created!\n"; diff --git a/src/test/java/course_project/battleship_game/GameServiceTest.java b/src/test/java/course_project/battleship_game/GameServiceTest.java index 0acf71d3..2a6983c9 100644 --- a/src/test/java/course_project/battleship_game/GameServiceTest.java +++ b/src/test/java/course_project/battleship_game/GameServiceTest.java @@ -7,6 +7,7 @@ import course_project.battleship_game.service.PlayerService; import org.junit.jupiter.api.Test; +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -37,11 +38,10 @@ void testCreateUsersPVP() { setInput("test\n0\ntest1\n0"); Player[] players = service.createPlayers(GameMode.PVP); assertEquals(2, players.length); - assertFalse(players[0].getName().contains("Computer")); - assertFalse(players[1].getName().contains("Computer")); + assertFalse(players[0].getName().contains(DEFAULT_COMPUTER_NAME)); + assertFalse(players[1].getName().contains(DEFAULT_COMPUTER_NAME)); } - @Test void testRollingDiceShufflePlayers() { Player[] players = service.createPlayers(GameMode.CVC); @@ -52,7 +52,6 @@ void testRollingDiceShufflePlayers() { } else { assertNotEquals(one, players[0]); } - } @Test diff --git a/src/test/java/course_project/battleship_game/utils/Constants.java b/src/test/java/course_project/battleship_game/utils/Constants.java index 93037d40..37d9b0c9 100644 --- a/src/test/java/course_project/battleship_game/utils/Constants.java +++ b/src/test/java/course_project/battleship_game/utils/Constants.java @@ -12,4 +12,5 @@ public class Constants { "1 - Computer vs Player\n" + "2 - Player vs Player"; public static final String GET_PLAYER_NAME_MESSAGE = "Enter your name:"; + public static final String DEFAULT_COMPUTER_NAME = "Computer"; } From a8810e37005f4518b8b4470296d7c96d83cadd0f Mon Sep 17 00:00:00 2001 From: rlrio Date: Sun, 19 Sep 2021 23:49:10 +0300 Subject: [PATCH 70/80] refactor course_project --- .../course_project/battleship_game/Main.java | 3 +- .../controller/GameController.java | 39 +++++++++++++++++- .../controller/GameControllerImpl.java | 41 ------------------- .../InputController.java} | 23 ++++++----- .../PrintController.java} | 12 +++--- .../battleship_game/service/GameService.java | 15 +++---- .../service/PlayerService.java | 17 ++++---- .../battleship_game/utils/Constants.java | 5 +++ .../utils/CoordinateValidator.java | 14 +++++-- .../InputControllerTest.java} | 31 ++++++++------ 10 files changed, 107 insertions(+), 93 deletions(-) delete mode 100644 src/main/java/course_project/battleship_game/controller/GameControllerImpl.java rename src/main/java/course_project/battleship_game/{utils/InputUtils.java => controller/InputController.java} (81%) rename src/main/java/course_project/battleship_game/{utils/PrintUtils.java => controller/PrintController.java} (82%) rename src/test/java/course_project/battleship_game/{utils/InputUtilsTest.java => controller/InputControllerTest.java} (75%) diff --git a/src/main/java/course_project/battleship_game/Main.java b/src/main/java/course_project/battleship_game/Main.java index 3e38eb8d..f00f300a 100644 --- a/src/main/java/course_project/battleship_game/Main.java +++ b/src/main/java/course_project/battleship_game/Main.java @@ -1,12 +1,11 @@ package course_project.battleship_game; import course_project.battleship_game.controller.GameController; -import course_project.battleship_game.controller.GameControllerImpl; public class Main { public static void main(String[] args) { - GameController controller = new GameControllerImpl(); + GameController controller = new GameController(); controller.run(); } } \ No newline at end of file diff --git a/src/main/java/course_project/battleship_game/controller/GameController.java b/src/main/java/course_project/battleship_game/controller/GameController.java index e57054da..9f5d2c62 100644 --- a/src/main/java/course_project/battleship_game/controller/GameController.java +++ b/src/main/java/course_project/battleship_game/controller/GameController.java @@ -1,5 +1,40 @@ package course_project.battleship_game.controller; -public interface GameController { - void run(); +import course_project.battleship_game.exception.GameException; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.service.GameService; + +import static course_project.battleship_game.controller.PrintController.printMessage; +import static course_project.battleship_game.utils.Constants.EXCEPTION_MESSAGE; +import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; +import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; + +public class GameController { + private GameService service = new GameService(); + private final InputController inputController = new InputController(); + + public void run() { + printMessage(WELCOME_MESSAGE); + GameMode gameMode = inputController.getGameMode(); + Player[] players = service.createPlayers(gameMode); + service.rollingDiceToChooseWhoStarts(players); + try { + service.createFleet(players); + } catch (GameException e) { + printMessage(EXCEPTION_MESSAGE); + } + printMessage(FLEETS_CREATED_MESSAGE); + Player player1 = players[0]; + Player player2 = players[1]; + boolean isGameOver = false; + while (!isGameOver) { + isGameOver = service.isGameOver(player1, player2, gameMode); + if (!isGameOver) { + isGameOver = service.isGameOver(player2, player1, gameMode); + } + } + service.determineWinner(players); + } + } diff --git a/src/main/java/course_project/battleship_game/controller/GameControllerImpl.java b/src/main/java/course_project/battleship_game/controller/GameControllerImpl.java deleted file mode 100644 index 92b2bb30..00000000 --- a/src/main/java/course_project/battleship_game/controller/GameControllerImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -package course_project.battleship_game.controller; - -import course_project.battleship_game.exception.GameException; -import course_project.battleship_game.model.GameMode; -import course_project.battleship_game.model.Player; -import course_project.battleship_game.service.GameService; - -import static course_project.battleship_game.utils.Constants.EXCEPTION_MESSAGE; -import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; -import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; -import static course_project.battleship_game.utils.InputUtils.getGameMode; -import static course_project.battleship_game.utils.PrintUtils.printMessage; - -public class GameControllerImpl implements GameController { - private GameService service = new GameService(); - - @Override - public void run() { - printMessage(WELCOME_MESSAGE); - GameMode gameMode = getGameMode(); - Player[] players = service.createPlayers(gameMode); - service.rollingDiceToChooseWhoStarts(players); - try { - service.createFleet(players); - } catch (GameException e) { - printMessage(EXCEPTION_MESSAGE); - } - printMessage(FLEETS_CREATED_MESSAGE); - Player player1 = players[0]; - Player player2 = players[1]; - boolean isGameOver = false; - while (!isGameOver) { - isGameOver = service.isGameOver(player1, player2, gameMode); - if (!isGameOver) { - isGameOver = service.isGameOver(player2, player1, gameMode); - } - } - service.determineWinner(players); - } - -} diff --git a/src/main/java/course_project/battleship_game/utils/InputUtils.java b/src/main/java/course_project/battleship_game/controller/InputController.java similarity index 81% rename from src/main/java/course_project/battleship_game/utils/InputUtils.java rename to src/main/java/course_project/battleship_game/controller/InputController.java index 8105eb44..fd623821 100644 --- a/src/main/java/course_project/battleship_game/utils/InputUtils.java +++ b/src/main/java/course_project/battleship_game/controller/InputController.java @@ -1,12 +1,14 @@ -package course_project.battleship_game.utils; +package course_project.battleship_game.controller; import course_project.battleship_game.model.Cell; import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.utils.CoordinateValidator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import static course_project.battleship_game.controller.PrintController.printMessage; import static course_project.battleship_game.utils.Constants.CHOOSE_GAME_MODE_MESSAGE; import static course_project.battleship_game.utils.Constants.CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE; import static course_project.battleship_game.utils.Constants.CHOOSE_SHIP_DIRECTION_MESSAGE; @@ -14,18 +16,17 @@ import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; import static course_project.battleship_game.utils.Constants.GET_CELL_COORDINATE_MESSAGE; import static course_project.battleship_game.utils.Constants.GET_PLAYER_NAME_MESSAGE; -import static course_project.battleship_game.utils.PrintUtils.printMessage; -public class InputUtils { - private static final BufferedReader READER = new BufferedReader(new InputStreamReader(System.in)); +public class InputController { + private final BufferedReader READER = new BufferedReader(new InputStreamReader(System.in)); - public static String getPlayerName() { + public String getPlayerName() { printMessage(GET_PLAYER_NAME_MESSAGE); String line = readLine(); return line == null || line.isEmpty() ? DEFAULT_PLAYER_NAME : line; } - public static GameMode getGameMode() { + public GameMode getGameMode() { printMessage(CHOOSE_GAME_MODE_MESSAGE); String mode = readLine(); while (true) { @@ -42,17 +43,17 @@ public static GameMode getGameMode() { } } - public static int getModeToCreateFleet() { + public int getModeToCreateFleet() { printMessage(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE); return getZeroOrOne(); } - public static int getDirection() { + public int getDirection() { printMessage(CHOOSE_SHIP_DIRECTION_MESSAGE); return getZeroOrOne(); } - public static Cell getCell() { + public Cell getCell() { printMessage(GET_CELL_COORDINATE_MESSAGE); String coordinate = readLine(); while (!CoordinateValidator.isCoordinate(coordinate)) { @@ -64,7 +65,7 @@ public static Cell getCell() { return new Cell(x, y); } - private static String readLine() { + private String readLine() { try { return READER.readLine(); } catch (IOException e) { @@ -72,7 +73,7 @@ private static String readLine() { } } - private static int getZeroOrOne() { + private int getZeroOrOne() { String mode = readLine(); while (true) { if (mode.equals("0") || mode.equals("1")) { diff --git a/src/main/java/course_project/battleship_game/utils/PrintUtils.java b/src/main/java/course_project/battleship_game/controller/PrintController.java similarity index 82% rename from src/main/java/course_project/battleship_game/utils/PrintUtils.java rename to src/main/java/course_project/battleship_game/controller/PrintController.java index 81c66e22..3e9ea3c5 100644 --- a/src/main/java/course_project/battleship_game/utils/PrintUtils.java +++ b/src/main/java/course_project/battleship_game/controller/PrintController.java @@ -1,4 +1,4 @@ -package course_project.battleship_game.utils; +package course_project.battleship_game.controller; import course_project.battleship_game.model.Cell; import course_project.battleship_game.model.CellStatus; @@ -9,20 +9,20 @@ import static course_project.battleship_game.utils.Constants.PLAYER_BOARD_MESSAGE_FORMAT; import static java.lang.System.lineSeparator; -public class PrintUtils { +public class PrintController { public static void printMessage(String message) { System.out.print(message); } - public static void printBoards(GameMode mode, Player player1, Player player2) { + public void printBoards(GameMode mode, Player player1, Player player2) { if (mode.equals(GameMode.CVC) || !player1.getName().contains(DEFAULT_COMPUTER_NAME)) { printBoardForPlayer(player1, false); printBoardForPlayer(player2, true); } } - public static void printBoardForPlayer(Player player, boolean isEnemy) { + public void printBoardForPlayer(Player player, boolean isEnemy) { printMessage(String.format(PLAYER_BOARD_MESSAGE_FORMAT, player.getName())); printHeader(); Cell[][] boardMatrix = player.getBoard().getBoardMatrix(); @@ -35,7 +35,7 @@ public static void printBoardForPlayer(Player player, boolean isEnemy) { } } - private static void printCell(boolean isEnemy, Cell cell) { + private void printCell(boolean isEnemy, Cell cell) { if (isEnemy && cell.getCellStatus().equals(CellStatus.SHIP)) { printMessage(CellStatus.EMPTY.getCharacter()); } else { @@ -43,7 +43,7 @@ private static void printCell(boolean isEnemy, Cell cell) { } } - private static void printHeader() { + private void printHeader() { printMessage(" "); for (int i = 1; i < 11; i++) { printMessage(i + " "); diff --git a/src/main/java/course_project/battleship_game/service/GameService.java b/src/main/java/course_project/battleship_game/service/GameService.java index 1758c838..abefb30c 100644 --- a/src/main/java/course_project/battleship_game/service/GameService.java +++ b/src/main/java/course_project/battleship_game/service/GameService.java @@ -1,28 +1,29 @@ package course_project.battleship_game.service; +import course_project.battleship_game.controller.InputController; +import course_project.battleship_game.controller.PrintController; import course_project.battleship_game.exception.GameException; import course_project.battleship_game.model.GameMode; import course_project.battleship_game.model.Player; import java.util.concurrent.ThreadLocalRandom; +import static course_project.battleship_game.controller.PrintController.printMessage; import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; import static course_project.battleship_game.utils.Constants.PLAYER_TURN_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.PLAYER_WINNER_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.ROLLING_DICE_MESSAGE; -import static course_project.battleship_game.utils.InputUtils.getModeToCreateFleet; -import static course_project.battleship_game.utils.InputUtils.getPlayerName; -import static course_project.battleship_game.utils.PrintUtils.printBoards; -import static course_project.battleship_game.utils.PrintUtils.printMessage; public class GameService { + private final InputController inputController = new InputController(); + private final PrintController printController = new PrintController(); public Player[] createPlayers(GameMode mode) { Player[] players = new Player[2]; players[0] = mode.equals(GameMode.CVC) ? new Player(DEFAULT_COMPUTER_NAME + " Mimi", 0) : - new Player(getPlayerName(), getModeToCreateFleet()); + new Player(inputController.getPlayerName(), inputController.getModeToCreateFleet()); players[1] = !mode.equals(GameMode.PVP) ? new Player(DEFAULT_COMPUTER_NAME + " Navi", 0) : - new Player(getPlayerName(), getModeToCreateFleet()); + new Player(inputController.getPlayerName(), inputController.getModeToCreateFleet()); return players; } @@ -51,7 +52,7 @@ public boolean isGameOver(Player player1, Player player2, GameMode gameMode) { printMessage(String.format(PLAYER_TURN_MESSAGE_FORMAT, player1.getName())); while (isMoveSuccessful && !isNoMoreAliveShips(player1, player2)) { isMoveSuccessful = new PlayerService(player1).isMoveSuccessful(player2); - printBoards(gameMode, player1, player2); + printController.printBoards(gameMode, player1, player2); } return isNoMoreAliveShips(player1, player2); } diff --git a/src/main/java/course_project/battleship_game/service/PlayerService.java b/src/main/java/course_project/battleship_game/service/PlayerService.java index 3d3de73f..e238b0c1 100644 --- a/src/main/java/course_project/battleship_game/service/PlayerService.java +++ b/src/main/java/course_project/battleship_game/service/PlayerService.java @@ -1,5 +1,7 @@ package course_project.battleship_game.service; +import course_project.battleship_game.controller.InputController; +import course_project.battleship_game.controller.PrintController; import course_project.battleship_game.model.Cell; import course_project.battleship_game.model.CellStatus; import course_project.battleship_game.model.Player; @@ -8,6 +10,7 @@ import java.util.concurrent.ThreadLocalRandom; +import static course_project.battleship_game.controller.PrintController.printMessage; import static course_project.battleship_game.utils.Constants.CREATING_FLEET_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.CREATING_SHIP_MESSAGE_FORMAT; import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; @@ -19,13 +22,11 @@ import static course_project.battleship_game.utils.Constants.REMAINING_AMOUNT_OF_TYPE_TO_CREATE; import static course_project.battleship_game.utils.Constants.SAME_COORDINATE_ERROR_MESSAGE; import static course_project.battleship_game.utils.Constants.SHIP_CREATED_MESSAGE_FORMAT; -import static course_project.battleship_game.utils.InputUtils.getCell; -import static course_project.battleship_game.utils.InputUtils.getDirection; -import static course_project.battleship_game.utils.PrintUtils.printBoardForPlayer; -import static course_project.battleship_game.utils.PrintUtils.printMessage; public class PlayerService { private final Player player; + private final InputController inputController = new InputController(); + private final PrintController printController = new PrintController(); public PlayerService(Player player) { this.player = player; @@ -37,7 +38,7 @@ public boolean isMoveSuccessful(Player enemy) { if (player.getName().contains(DEFAULT_COMPUTER_NAME)) { cell = RandomCellGenerator.generateRandomCell(); } else { - cell = getCell(); + cell = inputController.getCell(); } if (!player.getLogOfMoves().contains(cell)) { @@ -87,8 +88,8 @@ private void createRightAmountOfTypeManually(ShipType type) { printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); int count = 0; while (count != type.getAmount()) { - Cell start = getCell(); - int direction = getDirection(); + Cell start = inputController.getCell(); + int direction = inputController.getDirection(); start.setCellStatus(CellStatus.SHIP); boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); if (created) { @@ -97,7 +98,7 @@ private void createRightAmountOfTypeManually(ShipType type) { printMessage(String.format(REMAINING_AMOUNT_OF_TYPE_TO_CREATE, type.name().replace("_", " ").toLowerCase(), type.getAmount() - count)); } - printBoardForPlayer(player, false); + printController.printBoardForPlayer(player, false); } else { printMessage(ERROR_INPUT_MESSAGE); } diff --git a/src/main/java/course_project/battleship_game/utils/Constants.java b/src/main/java/course_project/battleship_game/utils/Constants.java index 4ee0edac..48436ce6 100644 --- a/src/main/java/course_project/battleship_game/utils/Constants.java +++ b/src/main/java/course_project/battleship_game/utils/Constants.java @@ -2,6 +2,11 @@ public class Constants { public static final int BOARD_SIZE = 10; + public static final int LOWER_BOUND = 48; + public static final int UPPER_BOUND = 58; + public static final int CELL_INT_UPPER_BOUND = 11; + public static final int CHAR_LOWER_BOUND = 64; + public static final int CHAR_UPPER_BOUND = 75; public static final String DEFAULT_PLAYER_NAME = "Player"; public static final String DEFAULT_COMPUTER_NAME = "Computer"; public static final String WELCOME_MESSAGE = "Welcome to the Battleship game!\n"; diff --git a/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java b/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java index 56cffc5e..ce85da9b 100644 --- a/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java +++ b/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java @@ -1,13 +1,19 @@ package course_project.battleship_game.utils; +import static course_project.battleship_game.utils.Constants.CELL_INT_UPPER_BOUND; +import static course_project.battleship_game.utils.Constants.CHAR_LOWER_BOUND; +import static course_project.battleship_game.utils.Constants.CHAR_UPPER_BOUND; +import static course_project.battleship_game.utils.Constants.LOWER_BOUND; +import static course_project.battleship_game.utils.Constants.UPPER_BOUND; + public class CoordinateValidator { public static boolean isCoordinate(String coordinate) { if (coordinate.length() > 3) { return false; } - boolean isFirstLetter = coordinate.toUpperCase().charAt(0) > 64 && - coordinate.toUpperCase().charAt(0) < 75; + boolean isFirstLetter = CHAR_LOWER_BOUND < coordinate.toUpperCase().charAt(0) && + coordinate.toUpperCase().charAt(0) < CHAR_UPPER_BOUND; boolean isNumber = coordinate.length() > 1 && isSuitableForCellCoordinate(coordinate.substring(1)); return isFirstLetter && isNumber; } @@ -15,13 +21,13 @@ public static boolean isCoordinate(String coordinate) { private static boolean isSuitableForCellCoordinate(String str) { int count = 0; for (int ch : str.toCharArray()) { - if (48 <= ch && ch < 58) { + if (LOWER_BOUND <= ch && ch < UPPER_BOUND) { count++; } } if (count == str.length()) { int i = Integer.parseInt(str); - return 0 < i && i < 11; + return 0 < i && i < CELL_INT_UPPER_BOUND; } return false; } diff --git a/src/test/java/course_project/battleship_game/utils/InputUtilsTest.java b/src/test/java/course_project/battleship_game/controller/InputControllerTest.java similarity index 75% rename from src/test/java/course_project/battleship_game/utils/InputUtilsTest.java rename to src/test/java/course_project/battleship_game/controller/InputControllerTest.java index 0b4b62ce..a7a76024 100644 --- a/src/test/java/course_project/battleship_game/utils/InputUtilsTest.java +++ b/src/test/java/course_project/battleship_game/controller/InputControllerTest.java @@ -1,4 +1,4 @@ -package course_project.battleship_game.utils; +package course_project.battleship_game.controller; import base.UnitBase; import course_project.battleship_game.model.GameMode; @@ -14,12 +14,19 @@ import static org.junit.jupiter.api.Assertions.assertTrue; -public class InputUtilsTest extends UnitBase { +public class InputControllerTest extends UnitBase { + InputController controller; + + @Override + protected void setInput(String input) { + super.setInput(input); + controller = new InputController(); + } @Test void testGetNameString() { setInput("Hero"); - String playerName = InputUtils.getPlayerName(); + String playerName = controller.getPlayerName(); assertEquals("Hero", playerName); assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); } @@ -27,7 +34,7 @@ void testGetNameString() { @Test void testGetNameStringNumber() { setInput("11"); - String playerName = InputUtils.getPlayerName(); + String playerName = controller.getPlayerName(); assertEquals("11", playerName); assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); } @@ -35,7 +42,7 @@ void testGetNameStringNumber() { @Test void testGetNameEmptyString() { setInput(""); - String playerName = InputUtils.getPlayerName(); + String playerName = controller.getPlayerName(); assertEquals(DEFAULT_PLAYER_NAME, playerName); assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); } @@ -43,7 +50,7 @@ void testGetNameEmptyString() { @Test void testGetDirectionZero() { setInput("2\nString\n0"); - assertEquals(0, InputUtils.getDirection()); + assertEquals(0, controller.getDirection()); assertTrue(getOutput().contains(ERROR_INPUT_MESSAGE)); assertTrue(getOutput().contains(CHOOSE_SHIP_DIRECTION_MESSAGE.trim())); } @@ -51,14 +58,14 @@ void testGetDirectionZero() { @Test void testGetDirectionOne() { setInput("1"); - assertEquals(1, InputUtils.getDirection()); + assertEquals(1, controller.getDirection()); assertTrue(getOutput().contains(CHOOSE_SHIP_DIRECTION_MESSAGE.trim())); } @Test void testGetModeToCreateFleetZero() { setInput("2\nString\n0"); - assertEquals(0, InputUtils.getModeToCreateFleet()); + assertEquals(0, controller.getModeToCreateFleet()); assertTrue(getOutput().contains(ERROR_INPUT_MESSAGE.trim())); assertTrue(getOutput().contains(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE.trim())); } @@ -66,28 +73,28 @@ void testGetModeToCreateFleetZero() { @Test void testGetModeToCreateFleetOne() { setInput("1"); - assertEquals(1, InputUtils.getModeToCreateFleet()); + assertEquals(1, controller.getModeToCreateFleet()); assertTrue(getOutput().contains(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE.trim())); } @Test void testGetGameModeCVC() { setInput("0"); - assertEquals(GameMode.CVC, InputUtils.getGameMode()); + assertEquals(GameMode.CVC, controller.getGameMode()); assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); } @Test void testGetGameModePVC() { setInput("1"); - assertEquals(GameMode.PVC, InputUtils.getGameMode()); + assertEquals(GameMode.PVC, controller.getGameMode()); assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); } @Test void testGetGameModePVP() { setInput("s\n5\n2"); - assertEquals(GameMode.PVP, InputUtils.getGameMode()); + assertEquals(GameMode.PVP, controller.getGameMode()); assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); } From 223083deebd673a8ecc319044a5fbc60a123cf9c Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 20 Sep 2021 00:16:30 +0300 Subject: [PATCH 71/80] refactor course_project --- .../controller/InputController.java | 1 - .../utils/RandomCellGenerator.java | 1 + .../controller/GameControllerTest.java | 17 +++++++ .../controller/InputControllerTest.java | 3 +- .../controller/PrintControllerTest.java | 51 +++++++++++++++++++ .../battleship_game/utils/Constants.java | 1 + 6 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 src/test/java/course_project/battleship_game/controller/GameControllerTest.java create mode 100644 src/test/java/course_project/battleship_game/controller/PrintControllerTest.java diff --git a/src/main/java/course_project/battleship_game/controller/InputController.java b/src/main/java/course_project/battleship_game/controller/InputController.java index fd623821..8589e8a7 100644 --- a/src/main/java/course_project/battleship_game/controller/InputController.java +++ b/src/main/java/course_project/battleship_game/controller/InputController.java @@ -83,5 +83,4 @@ private int getZeroOrOne() { mode = readLine(); } } - } diff --git a/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java b/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java index 09e2a49f..268d679d 100644 --- a/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java +++ b/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java @@ -5,6 +5,7 @@ import java.util.concurrent.ThreadLocalRandom; public class RandomCellGenerator { + public static Cell generateRandomCell() { int x = ThreadLocalRandom.current().nextInt(0, 10); int y = ThreadLocalRandom.current().nextInt(0, 10); diff --git a/src/test/java/course_project/battleship_game/controller/GameControllerTest.java b/src/test/java/course_project/battleship_game/controller/GameControllerTest.java new file mode 100644 index 00000000..5ddf28fe --- /dev/null +++ b/src/test/java/course_project/battleship_game/controller/GameControllerTest.java @@ -0,0 +1,17 @@ +package course_project.battleship_game.controller; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GameControllerTest extends UnitBase { + + @Test + void testRunCVC() { + setInput("0"); + new GameController().run(); + printOut(); + assertTrue(getOutput().contains("won the game")); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/controller/InputControllerTest.java b/src/test/java/course_project/battleship_game/controller/InputControllerTest.java index a7a76024..0b0eb31b 100644 --- a/src/test/java/course_project/battleship_game/controller/InputControllerTest.java +++ b/src/test/java/course_project/battleship_game/controller/InputControllerTest.java @@ -13,9 +13,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - public class InputControllerTest extends UnitBase { - InputController controller; + private InputController controller; @Override protected void setInput(String input) { diff --git a/src/test/java/course_project/battleship_game/controller/PrintControllerTest.java b/src/test/java/course_project/battleship_game/controller/PrintControllerTest.java new file mode 100644 index 00000000..33d85eef --- /dev/null +++ b/src/test/java/course_project/battleship_game/controller/PrintControllerTest.java @@ -0,0 +1,51 @@ +package course_project.battleship_game.controller; + +import base.UnitBase; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.service.PlayerService; +import org.junit.jupiter.api.Test; + +import static course_project.battleship_game.utils.Constants.PLAYER_BOARD_MESSAGE_FORMAT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PrintControllerTest extends UnitBase { + + @Test + void testPrintBoards() { + GameMode mode = GameMode.CVC; + Player hero = new Player("Hero", 0); + Player villain = new Player("Villain", 0); + PlayerService serviceHero = new PlayerService(hero); + PlayerService serviceVillain = new PlayerService(villain); + serviceHero.createFleetForPlayer(); + serviceVillain.createFleetForPlayer(); + new PrintController().printBoards(mode, hero, villain); + printOut(); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT, hero.getName()))); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT, villain.getName()))); + } + + @Test + void printBoardForPlayerHero() { + Player hero = new Player("Hero", 0); + PlayerService service = new PlayerService(hero); + service.createFleetForPlayer(); + new PrintController().printBoardForPlayer(hero, false); + printOut(); + assertEquals(10, hero.getBoard().getShipList().size()); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT.trim(), hero.getName()))); + } + + @Test + void printBoardForPlayerEnemy() { + Player enemy = new Player("Villain", 0); + PlayerService service = new PlayerService(enemy); + service.createFleetForPlayer(); + new PrintController().printBoardForPlayer(enemy, true); + printOut(); + assertEquals(10, enemy.getBoard().getShipList().size()); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT.trim(), enemy.getName()))); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/utils/Constants.java b/src/test/java/course_project/battleship_game/utils/Constants.java index 37d9b0c9..fbba0f54 100644 --- a/src/test/java/course_project/battleship_game/utils/Constants.java +++ b/src/test/java/course_project/battleship_game/utils/Constants.java @@ -13,4 +13,5 @@ public class Constants { "2 - Player vs Player"; public static final String GET_PLAYER_NAME_MESSAGE = "Enter your name:"; public static final String DEFAULT_COMPUTER_NAME = "Computer"; + public static final String PLAYER_BOARD_MESSAGE_FORMAT = "This is %s's board"; } From b7a6098aba9214d0dd46cc05b2fa225c8eaebf72 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 20 Sep 2021 00:17:38 +0300 Subject: [PATCH 72/80] refactor course_project --- .../battleship_game/controller/GameController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/course_project/battleship_game/controller/GameController.java b/src/main/java/course_project/battleship_game/controller/GameController.java index 9f5d2c62..37c87094 100644 --- a/src/main/java/course_project/battleship_game/controller/GameController.java +++ b/src/main/java/course_project/battleship_game/controller/GameController.java @@ -11,7 +11,7 @@ import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; public class GameController { - private GameService service = new GameService(); + private final GameService service = new GameService(); private final InputController inputController = new InputController(); public void run() { From 068e9fb92f8db76902bcb21386b5051ce85a2875 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 20 Sep 2021 00:21:39 +0300 Subject: [PATCH 73/80] update README --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1ee4549b..acffd2e9 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ | HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [PowerOfNumberTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | PowerOfNumber App with method pow implemented via recursion | | HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/custom_regex_matcher) [CustomRegexMatcherTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/custom_regex_matcher) | The App checks whether the arguments match the hardcoded regex | | HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_6/map_problems_generator) | 1)CollidingMapProblemsGeneratorKey is the class that always creates collisions in the HashMap.
2)MutableMapProblemsGeneratorKey is the class with HashCode method that returns random value. | -| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_7) | Custom Functional Interface KittenToCatFunction with abstract method grow(). +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_7) | Custom Functional Interface KittenToCatFunction with abstract method grow(). | +| Course Project | [BattleShipGame](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/course_project/battleship_game)
[UnitTests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/course_project/battleship_game)| BattleShip game with three modes (CVC, PVC, PVP). [Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file From 98c314510a398dd9414aa810968de45f35095aae Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 20 Sep 2021 00:32:04 +0300 Subject: [PATCH 74/80] refactor course_project --- .../battleship_game/{ => service}/BoardServiceTest.java | 3 +-- .../battleship_game/{ => service}/GameServiceTest.java | 4 +--- .../battleship_game/{ => service}/PlayerServiceTest.java | 3 +-- .../battleship_game/{ => service}/ShipServiceTest.java | 3 +-- 4 files changed, 4 insertions(+), 9 deletions(-) rename src/test/java/course_project/battleship_game/{ => service}/BoardServiceTest.java (96%) rename src/test/java/course_project/battleship_game/{ => service}/GameServiceTest.java (95%) rename src/test/java/course_project/battleship_game/{ => service}/PlayerServiceTest.java (93%) rename src/test/java/course_project/battleship_game/{ => service}/ShipServiceTest.java (95%) diff --git a/src/test/java/course_project/battleship_game/BoardServiceTest.java b/src/test/java/course_project/battleship_game/service/BoardServiceTest.java similarity index 96% rename from src/test/java/course_project/battleship_game/BoardServiceTest.java rename to src/test/java/course_project/battleship_game/service/BoardServiceTest.java index be8e17ad..f5e9621e 100644 --- a/src/test/java/course_project/battleship_game/BoardServiceTest.java +++ b/src/test/java/course_project/battleship_game/service/BoardServiceTest.java @@ -1,11 +1,10 @@ -package course_project.battleship_game; +package course_project.battleship_game.service; import course_project.battleship_game.model.Board; import course_project.battleship_game.model.Cell; import course_project.battleship_game.model.CellStatus; import course_project.battleship_game.model.Ship; import course_project.battleship_game.model.ShipType; -import course_project.battleship_game.service.BoardService; import course_project.battleship_game.utils.RandomGenerator; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; diff --git a/src/test/java/course_project/battleship_game/GameServiceTest.java b/src/test/java/course_project/battleship_game/service/GameServiceTest.java similarity index 95% rename from src/test/java/course_project/battleship_game/GameServiceTest.java rename to src/test/java/course_project/battleship_game/service/GameServiceTest.java index 2a6983c9..967d6011 100644 --- a/src/test/java/course_project/battleship_game/GameServiceTest.java +++ b/src/test/java/course_project/battleship_game/service/GameServiceTest.java @@ -1,10 +1,8 @@ -package course_project.battleship_game; +package course_project.battleship_game.service; import base.UnitBase; import course_project.battleship_game.model.GameMode; import course_project.battleship_game.model.Player; -import course_project.battleship_game.service.GameService; -import course_project.battleship_game.service.PlayerService; import org.junit.jupiter.api.Test; import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; diff --git a/src/test/java/course_project/battleship_game/PlayerServiceTest.java b/src/test/java/course_project/battleship_game/service/PlayerServiceTest.java similarity index 93% rename from src/test/java/course_project/battleship_game/PlayerServiceTest.java rename to src/test/java/course_project/battleship_game/service/PlayerServiceTest.java index 0b1d7a4e..0b44f914 100644 --- a/src/test/java/course_project/battleship_game/PlayerServiceTest.java +++ b/src/test/java/course_project/battleship_game/service/PlayerServiceTest.java @@ -1,8 +1,7 @@ -package course_project.battleship_game; +package course_project.battleship_game.service; import course_project.battleship_game.model.CellStatus; import course_project.battleship_game.model.Player; -import course_project.battleship_game.service.PlayerService; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/src/test/java/course_project/battleship_game/ShipServiceTest.java b/src/test/java/course_project/battleship_game/service/ShipServiceTest.java similarity index 95% rename from src/test/java/course_project/battleship_game/ShipServiceTest.java rename to src/test/java/course_project/battleship_game/service/ShipServiceTest.java index 1493f4b4..7e661a6a 100644 --- a/src/test/java/course_project/battleship_game/ShipServiceTest.java +++ b/src/test/java/course_project/battleship_game/service/ShipServiceTest.java @@ -1,9 +1,8 @@ -package course_project.battleship_game; +package course_project.battleship_game.service; import course_project.battleship_game.model.Cell; import course_project.battleship_game.model.CellStatus; import course_project.battleship_game.model.Ship; -import course_project.battleship_game.service.ShipService; import course_project.battleship_game.utils.RandomGenerator; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; From 34b0d61c448928b7118fb745c1f0e1079b1a7e62 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 20 Sep 2021 17:36:34 +0300 Subject: [PATCH 75/80] hw5 --- .../homework_5/math_power/utils/PowerOfNumberValidator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java b/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java index 5c04af1e..b4716091 100644 --- a/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java +++ b/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java @@ -2,7 +2,7 @@ public final class PowerOfNumberValidator { - public static boolean isValid(String[] args) throws NumberFormatException { + public static boolean isValid(String[] args) { try { return args.length == 2 && Integer.parseInt(args[0]) >= 0 && Integer.parseInt(args[1]) >= 0; } catch (NumberFormatException e) { From 03ea478e27f9d14a5727cbaa19eed14c50262d1a Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 20 Sep 2021 23:01:46 +0300 Subject: [PATCH 76/80] update hw6 --- .../map_problems_generator/Main.java | 3 ++- .../impl/MutableMapProblemsGeneratorKey.java | 21 +++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java index c25dbe70..086a8ea1 100644 --- a/src/main/java/homework_6/map_problems_generator/Main.java +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -23,9 +23,10 @@ public static void main(String[] args) { System.out.println("Testing MutableMapProblemsGeneratorKey:"); Map, Integer> map = new HashMap<>(); - MapProblemsGenerator myObject = new MutableMapProblemsGeneratorKey<>(); + MutableMapProblemsGeneratorKey myObject = new MutableMapProblemsGeneratorKey<>(1); System.out.println("myObject = " + myObject); map.put(myObject, 1); + myObject.setId(2); System.out.println("map.containsKey(myObject) = " + map.containsKey(myObject)); System.out.println("map.size() = " + map.size()); System.out.println("Map keys:"); diff --git a/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java b/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java index d33c827b..27ada9f6 100644 --- a/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java +++ b/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java @@ -1,19 +1,28 @@ package homework_6.map_problems_generator.impl; -import java.util.Random; - public class MutableMapProblemsGeneratorKey extends AbstractMapProblemsGenerator { + private int id; - public MutableMapProblemsGeneratorKey() { + public MutableMapProblemsGeneratorKey(int id) { super(null); + this.id = id; + } + + public void setId(int id) { + this.id = id; } - public MutableMapProblemsGeneratorKey(T value) { - super(value); + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + MutableMapProblemsGeneratorKey that = (MutableMapProblemsGeneratorKey) o; + return id == that.id; } @Override public int hashCode() { - return new Random().nextInt(); + return Integer.hashCode(id); } } \ No newline at end of file From 9e732a748a94010d66db9158103b2c224158c021 Mon Sep 17 00:00:00 2001 From: rlrio Date: Mon, 20 Sep 2021 23:03:05 +0300 Subject: [PATCH 77/80] update hw6 --- .../impl/CollidingMapProblemsGeneratorKey.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java b/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java index b751bf0d..a78d7d65 100644 --- a/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java +++ b/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java @@ -14,4 +14,9 @@ public CollidingMapProblemsGeneratorKey(T value) { public int hashCode() { return 31; } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } } From 962a051c59b9b419cea04ee1d43e01d631d6c75e Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 21 Sep 2021 12:58:33 +0300 Subject: [PATCH 78/80] update hw3 --- src/main/java/homework_3/ImmutableWorker.java | 43 +++++-------------- src/main/java/homework_3/Main.java | 19 ++++---- .../java/homework_3/ImmutableWorkerTest.java | 2 - 3 files changed, 20 insertions(+), 44 deletions(-) diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 603fe63c..56ffc1ab 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -1,7 +1,6 @@ package homework_3; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -45,42 +44,22 @@ public ImmutableWorker(String name, int id, Age age) { this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); } - public String getName() { - return name; - } - - public String getDepartment() { - return department; - } - - public int getId() { - return id; - } - - public List getTasks() { - return tasks; - } - - public Age getAge() { - return age; - } - public ImmutableWorker updateWorker(String name, String department, int id, List tasks, Age age) { if (name == null) { - name = this.getName(); + name = this.name; } if (department == null) { - department = this.getDepartment(); + department = this.department; } if (id == 0) { - id = this.getId(); + id = this.id; } if (tasks == null) { tasks = new ArrayList<>(); - Collections.copy(tasks, this.tasks); + tasks.addAll(this.tasks); } if (age == null) { - age = this.getAge(); + age = this.age; } return new ImmutableWorker(name, department, id, tasks, age); } @@ -90,16 +69,16 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ImmutableWorker that = (ImmutableWorker) o; - return getId() == that.getId() && - getName().equals(that.getName()) && - Objects.equals(getDepartment(), that.getDepartment()) && - Objects.equals(getTasks(), that.getTasks()) && - Objects.equals(getAge(), that.getAge()); + return id == that.id && + Objects.equals(name, that.name) && + Objects.equals(department, that.department) && + Objects.equals(tasks, that.tasks) && + Objects.equals(age, that.age); } @Override public int hashCode() { - return Objects.hash(getName(), getDepartment(), getId(), getTasks(), getAge()); + return Objects.hash(name, department, id, tasks, age); } @Override diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java index c3b80b48..fe2a7467 100644 --- a/src/main/java/homework_3/Main.java +++ b/src/main/java/homework_3/Main.java @@ -10,17 +10,16 @@ public static void main(String[] args) { Age age = new Age(13, 5, 1980); ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); testList.add("task2"); - System.out.println("worker tasks list size: " + worker.getTasks().size()); System.out.println("testList size: " + testList.size()); - //age.setDay(5); - //System.out.println("updated Age = " + age.getDay()); - //System.out.println("age day of the worker = " + worker.getAge().getDay()); - //worker.getAge().setDay(5); - System.out.println("age day of the worker = " + worker.getAge().getDay()); - System.out.println(worker.getName()); - worker = worker.updateWorker("Jackson", "Sales", 897, testList, age); - System.out.println(worker); - worker = worker.updateWorker(null, "Account", 0, null, null); System.out.println(worker); + System.out.println(worker.hashCode()); + ImmutableWorker worker1 = worker.updateWorker("Jackson", "Sales", 897, testList, age); + System.out.println(worker1); + System.out.println(worker1.hashCode()); + ImmutableWorker worker2 = worker.updateWorker(null, "Account", 0, null, null); + System.out.println(worker2); + System.out.println(worker2.hashCode()); + System.out.println(worker == worker1); + System.out.println(worker1 == worker2); } } diff --git a/src/test/java/homework_3/ImmutableWorkerTest.java b/src/test/java/homework_3/ImmutableWorkerTest.java index e547d824..72b9aa30 100644 --- a/src/test/java/homework_3/ImmutableWorkerTest.java +++ b/src/test/java/homework_3/ImmutableWorkerTest.java @@ -16,7 +16,5 @@ void testIfImmutable() { ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); ImmutableWorker anotherWorker = worker.updateWorker("null", "Sales", 0, null, null); assertNotSame(worker, anotherWorker); - assertNotSame(worker.getAge(), anotherWorker.getAge()); - assertNotSame(worker.getTasks(), anotherWorker.getTasks()); } } \ No newline at end of file From 750631e5d921a54b7a65347db88688f61778e92b Mon Sep 17 00:00:00 2001 From: rlrio Date: Tue, 21 Sep 2021 23:59:24 +0300 Subject: [PATCH 79/80] update hw3 --- src/main/java/homework_3/ImmutableWorker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 56ffc1ab..16cb2076 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -59,7 +59,7 @@ public ImmutableWorker updateWorker(String name, String department, int id, List tasks.addAll(this.tasks); } if (age == null) { - age = this.age; + age = new Age(this.age); } return new ImmutableWorker(name, department, id, tasks, age); } From 9af70177f32bc733a6550ebf2c7e35a27be59ff6 Mon Sep 17 00:00:00 2001 From: rlrio Date: Wed, 22 Sep 2021 00:02:54 +0300 Subject: [PATCH 80/80] update hw3 --- src/main/java/homework_3/Age.java | 15 ++++----------- src/main/java/homework_3/ImmutableWorker.java | 8 ++++---- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/main/java/homework_3/Age.java b/src/main/java/homework_3/Age.java index fd56e25a..2bb3411b 100644 --- a/src/main/java/homework_3/Age.java +++ b/src/main/java/homework_3/Age.java @@ -12,18 +12,11 @@ public Age(int day, int month, int year) { } public Age(Age age) { - this(age.getDay(), age.getMonth(), age.getYear()); + this(age.day, age.month, age.year); } - public int getDay() { - return day; - } - - public int getMonth() { - return month; - } - - public int getYear() { - return year; + @Override + public String toString() { + return day + "." + month + "." + year; } } diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java index 16cb2076..3224013b 100644 --- a/src/main/java/homework_3/ImmutableWorker.java +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -25,7 +25,7 @@ public ImmutableWorker(String name, String department, int id, List task this.department = department; this.id = id; this.tasks = new ArrayList<>(tasks); - this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); + this.age = new Age(age); } public ImmutableWorker(String name, String department, int id, Age age) { @@ -33,7 +33,7 @@ public ImmutableWorker(String name, String department, int id, Age age) { this.department = department; this.id = id; this.tasks = new ArrayList<>(); - this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); + this.age = new Age(age); } public ImmutableWorker(String name, int id, Age age) { @@ -41,7 +41,7 @@ public ImmutableWorker(String name, int id, Age age) { this.department = "No department"; this.id = id; this.tasks = new ArrayList<>(); - this.age = new Age(age.getDay(), age.getMonth(), age.getYear()); + this.age = new Age(age); } public ImmutableWorker updateWorker(String name, String department, int id, List tasks, Age age) { @@ -88,7 +88,7 @@ public String toString() { ", department='" + department + '\'' + ", id=" + id + ", tasks_size=" + tasks.size() + - ", age=" + age.getDay() + "." + age.getMonth() + "." + age.getYear() + + ", age=" + age.toString() + '}'; } }