From bc5b4177b219a895eb6f29519695c686e1646d7a Mon Sep 17 00:00:00 2001 From: Artem Nikolaev Date: Mon, 5 Jul 2021 23:52:09 +0300 Subject: [PATCH 01/44] Test push --- src/main/java/Homework_1/Homework_1.java | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 src/main/java/Homework_1/Homework_1.java diff --git a/src/main/java/Homework_1/Homework_1.java b/src/main/java/Homework_1/Homework_1.java new file mode 100644 index 00000000..0cfe9bcf --- /dev/null +++ b/src/main/java/Homework_1/Homework_1.java @@ -0,0 +1,4 @@ +package Homework_1; + +public class Homework_1 { +} From c9a91efa105bf0ccc6f2994338360608c274dfc5 Mon Sep 17 00:00:00 2001 From: Allzza Date: Tue, 6 Jul 2021 00:18:41 +0300 Subject: [PATCH 02/44] =?UTF-8?q?=D0=BA=D0=BE=D0=B4=20=D0=B4=D0=BE=D0=BC?= =?UTF-8?q?=D0=B0=D1=88=D0=BA=D0=B8=20=E2=84=961.=20=D0=A1=20=D0=BA=D0=B8?= =?UTF-8?q?=D1=80=D0=B8=D0=BB=D0=BB=D0=B8=D1=86=D0=B5=D0=B9=20=D0=BD=D0=B5?= =?UTF-8?q?=20=D0=BF=D0=B0=D1=88=D0=B5=D1=82(?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/Homework_1/Homework_1.java | 4 ---- src/main/java/Homework_1/Main.java | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) delete mode 100644 src/main/java/Homework_1/Homework_1.java create mode 100644 src/main/java/Homework_1/Main.java diff --git a/src/main/java/Homework_1/Homework_1.java b/src/main/java/Homework_1/Homework_1.java deleted file mode 100644 index 0cfe9bcf..00000000 --- a/src/main/java/Homework_1/Homework_1.java +++ /dev/null @@ -1,4 +0,0 @@ -package Homework_1; - -public class Homework_1 { -} diff --git a/src/main/java/Homework_1/Main.java b/src/main/java/Homework_1/Main.java new file mode 100644 index 00000000..8798a85b --- /dev/null +++ b/src/main/java/Homework_1/Main.java @@ -0,0 +1,17 @@ +package Homework_1; + +public class Main { + + public static void main(String[] args) { + for (String object : args) { + if (object.equals("ошибка")) { + System.out.println("Тревога"); + break; + } + else { + System.out.println(object + ": " + object.length() + " букв"); + } + } + + } +} From edb888f4f67dd3bae13cb4e8fdcd856c723d92b0 Mon Sep 17 00:00:00 2001 From: Allzza Date: Wed, 7 Jul 2021 21:38:05 +0300 Subject: [PATCH 03/44] readme modified --- README.md | 4 ++-- src/main/java/homework_1/Main.java | 14 +++++++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5d686e9f..20337beb 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Dima Troshkin* | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..86a98748 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -2,8 +2,16 @@ public class Main { - public static void main(String[] args) { - System.out.println("Hello homework!"); - } + public static void main(String[] args) { + for (String object : args) { + if (object.equals("ошибка")) { + System.out.println("Тревога"); + break; + } + else { + System.out.println(object + ": " + object.length() + " букв"); + } + } + } } From 0995d15100fb89f74ee3b0b8bf629a8314455b2c Mon Sep 17 00:00:00 2001 From: Dmitrii Troshkin <86798105+Allzza@users.noreply.github.com> Date: Fri, 9 Jul 2021 15:35:18 +0300 Subject: [PATCH 04/44] Delete src/main/java/Homework_1 directory deleted extra directory --- src/main/java/Homework_1/Main.java | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 src/main/java/Homework_1/Main.java diff --git a/src/main/java/Homework_1/Main.java b/src/main/java/Homework_1/Main.java deleted file mode 100644 index 8798a85b..00000000 --- a/src/main/java/Homework_1/Main.java +++ /dev/null @@ -1,17 +0,0 @@ -package Homework_1; - -public class Main { - - public static void main(String[] args) { - for (String object : args) { - if (object.equals("ошибка")) { - System.out.println("Тревога"); - break; - } - else { - System.out.println(object + ": " + object.length() + " букв"); - } - } - - } -} From 64d8f00cc7649185b92964b89756cfce364f4f4a Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 11 Jul 2021 17:58:46 +0300 Subject: [PATCH 05/44] connecting on new pc --- src/main/java/homework_1/Main.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..89ad39aa 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -3,7 +3,15 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello homework!"); - } + for (String object : args) { + if (object.equals("ошибка")) { + System.out.println("Тревога"); + break; + } + else { + System.out.println(object + ": " + object.length() + " букв"); + } + } -} + } +} \ No newline at end of file From 266c2b840bd6d6ded507a98362cf7e5bd8e73542 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 11 Jul 2021 18:01:01 +0300 Subject: [PATCH 06/44] connecting on new pc --- src/main/java/homework_1/Main.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..89ad39aa 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -3,7 +3,15 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello homework!"); - } + for (String object : args) { + if (object.equals("ошибка")) { + System.out.println("Тревога"); + break; + } + else { + System.out.println(object + ": " + object.length() + " букв"); + } + } -} + } +} \ No newline at end of file From 8b478c0ee897dead176c4b26864ef84223d9201e Mon Sep 17 00:00:00 2001 From: Dmitrii Troshkin <86798105+Allzza@users.noreply.github.com> Date: Wed, 14 Jul 2021 21:09:49 +0300 Subject: [PATCH 07/44] Update src/main/java/homework_1/Main.java Co-authored-by: Artem Nikolaev --- src/main/java/homework_1/Main.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 89ad39aa..5bac5188 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -3,15 +3,14 @@ public class Main { public static void main(String[] args) { - for (String object : args) { - if (object.equals("ошибка")) { + for (String s: args) { + if (s.equals("ошибка")) { System.out.println("Тревога"); break; - } - else { - System.out.println(object + ": " + object.length() + " букв"); + } else { + System.out.println(s + ": " + s.length() + " букв"); } } } -} \ No newline at end of file +} From 68238756d1a7a6ac607de746a1fc9348d3e6b5e0 Mon Sep 17 00:00:00 2001 From: Allzza Date: Wed, 14 Jul 2021 21:16:01 +0300 Subject: [PATCH 08/44] made link to my branch --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 20337beb..2254fb10 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,6 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 67f119c9aadcf7a17b089d4eb957612913a178d2 Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 19 Jul 2021 18:16:36 +0300 Subject: [PATCH 09/44] changed functionality according to description --- src/main/java/homework_1/Main.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 5bac5188..0b7d92ba 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -4,12 +4,12 @@ public class Main { public static void main(String[] args) { for (String s: args) { + + System.out.println(s + ": " + s.length() + " букв"); if (s.equals("ошибка")) { System.out.println("Тревога"); break; - } else { - System.out.println(s + ": " + s.length() + " букв"); - } + } } } From 565446c069f0c84d82c4049d899f4f5fc582c714 Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 19 Jul 2021 19:11:07 +0300 Subject: [PATCH 10/44] traffic light added + readme modified --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2254fb10..585e90c5 100644 --- a/README.md +++ b/README.md @@ -5,5 +5,6 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/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/DimaTroshkin/src/main/java/homework_2) | The app that reads time from keyboard ads says which color the traffic light is| [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 4fe6027b9b68ba8756b40401f9603498e7ea2705 Mon Sep 17 00:00:00 2001 From: Dmitrii Troshkin <86798105+Allzza@users.noreply.github.com> Date: Mon, 19 Jul 2021 19:15:53 +0300 Subject: [PATCH 11/44] Update Main.java --- src/main/java/homework_1/Main.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 0b7d92ba..5422f9d8 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -4,8 +4,7 @@ public class Main { public static void main(String[] args) { for (String s: args) { - - System.out.println(s + ": " + s.length() + " букв"); + System.out.println(s + ": " + s.length() + " букв"); if (s.equals("ошибка")) { System.out.println("Тревога"); break; From c63ac420c5091b8ad228a544a732418dcee29b53 Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 19 Jul 2021 19:21:19 +0300 Subject: [PATCH 12/44] traffic light added + readme modified --- src/main/java/homework_2/Traffic_light.java | 49 +++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/homework_2/Traffic_light.java diff --git a/src/main/java/homework_2/Traffic_light.java b/src/main/java/homework_2/Traffic_light.java new file mode 100644 index 00000000..c26f3b32 --- /dev/null +++ b/src/main/java/homework_2/Traffic_light.java @@ -0,0 +1,49 @@ +package homework_2; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Traffic_light { +// считывает количество секунд с начала дня с командной строки во время работы, переводит в инт, +// выводит в командную строку цвет светофора (любым вариантом/сообщением, +// главное чтобы было различие зеленый-желтый-красный). +// Цикл светофора - 60 секунд. +// С 0 <= light < 35 зеленый, 35 <= light < 40 желтый, 40 <= light < 55 красный, 55 <= light < 60 желтый. +// +// Ограничения ввода: минимальное 0, максимальное 24*60*60 - 1 = 86399 + + public static void main(String[] args) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + int time; + + while (true) { + System.out.println("Введите целое число от 0 до 86399"); + time = Integer.parseInt(reader.readLine()); + if (time < 0){ + System.out.println("Число отрицательное. Введите целое число от 0 до 86399"); + } + else if (time > 86399){ + System.out.println("Число слишком большое. Введите целое число от 0 до 86399"); + } + else { + break; + } + } + + int light = time % 60; + + if (light < 35){ + System.out.println(" Зеленый"); + } + else if (light < 40){ + System.out.println("Желтый"); + } + else if (light < 55){ + System.out.println("Красный"); + } + else { + System.out.println("Желтый"); + } + } +} From bda20a4f979cb5a5eae25644b20f4bb78783e95a Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 19 Jul 2021 19:23:52 +0300 Subject: [PATCH 13/44] traffic light name changed --- .../java/homework_2/{Traffic_light.java => TrafficLight.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/main/java/homework_2/{Traffic_light.java => TrafficLight.java} (98%) diff --git a/src/main/java/homework_2/Traffic_light.java b/src/main/java/homework_2/TrafficLight.java similarity index 98% rename from src/main/java/homework_2/Traffic_light.java rename to src/main/java/homework_2/TrafficLight.java index c26f3b32..363fb664 100644 --- a/src/main/java/homework_2/Traffic_light.java +++ b/src/main/java/homework_2/TrafficLight.java @@ -4,7 +4,7 @@ import java.io.IOException; import java.io.InputStreamReader; -public class Traffic_light { +public class TrafficLight { // считывает количество секунд с начала дня с командной строки во время работы, переводит в инт, // выводит в командную строку цвет светофора (любым вариантом/сообщением, // главное чтобы было различие зеленый-желтый-красный). From 26b29eb9530e8387eba23dae4e44d6d7d0613077 Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 19 Jul 2021 20:09:29 +0300 Subject: [PATCH 14/44] traffic light exception added --- src/main/java/homework_2/TrafficLight.java | 50 +++++++++++----------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/src/main/java/homework_2/TrafficLight.java b/src/main/java/homework_2/TrafficLight.java index 363fb664..08a65f5e 100644 --- a/src/main/java/homework_2/TrafficLight.java +++ b/src/main/java/homework_2/TrafficLight.java @@ -15,35 +15,37 @@ public class TrafficLight { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - int time; + String str; while (true) { System.out.println("Введите целое число от 0 до 86399"); - time = Integer.parseInt(reader.readLine()); - if (time < 0){ - System.out.println("Число отрицательное. Введите целое число от 0 до 86399"); - } - else if (time > 86399){ - System.out.println("Число слишком большое. Введите целое число от 0 до 86399"); - } - else { - break; - } - } + str = reader.readLine(); - int light = time % 60; + try { + int time = Integer.parseInt(str); + if (time < 0){ + System.out.println("Разрешено вводить только положительные числа"); + } + else if (time > 86399) { + System.out.println("Вы ввели слишком большое число. День закончился"); + } + else { + int light = time % 60; - if (light < 35){ - System.out.println(" Зеленый"); - } - else if (light < 40){ - System.out.println("Желтый"); - } - else if (light < 55){ - System.out.println("Красный"); - } - else { - System.out.println("Желтый"); + if (light < 35) { + System.out.println(" Зеленый"); + } else if (light < 40) { + System.out.println("Желтый"); + } else if (light < 55) { + System.out.println("Красный"); + } else { + System.out.println("Желтый"); + } + break; + } + } catch (NumberFormatException e) { + System.out.println("Разрешено вводить только числа"); + } } } } From a49641947694c3791c13c95476e791d78cb9a504 Mon Sep 17 00:00:00 2001 From: Allzza Date: Tue, 20 Jul 2021 17:24:54 +0300 Subject: [PATCH 15/44] while (true) deleted --- src/main/java/homework_2/TrafficLight.java | 47 ++++++++++------------ 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/src/main/java/homework_2/TrafficLight.java b/src/main/java/homework_2/TrafficLight.java index 08a65f5e..be4dd490 100644 --- a/src/main/java/homework_2/TrafficLight.java +++ b/src/main/java/homework_2/TrafficLight.java @@ -17,35 +17,30 @@ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String str; - while (true) { - System.out.println("Введите целое число от 0 до 86399"); - str = reader.readLine(); + System.out.println("Введите целое число от 0 до 86399"); + str = reader.readLine(); - try { - int time = Integer.parseInt(str); - if (time < 0){ - System.out.println("Разрешено вводить только положительные числа"); + try { + int time = Integer.parseInt(str); + if (time < 0) { + System.out.println("Разрешено вводить только положительные числа"); + } else if (time > 86399) { + System.out.println("Вы ввели слишком большое число. День закончился"); + } else { + int light = time % 60; + if (light < 35) { + System.out.println(" Зеленый"); + } else if (light < 40) { + System.out.println("Желтый"); + } else if (light < 55) { + System.out.println("Красный"); + } else { + System.out.println("Желтый"); } - else if (time > 86399) { - System.out.println("Вы ввели слишком большое число. День закончился"); - } - else { - int light = time % 60; - - if (light < 35) { - System.out.println(" Зеленый"); - } else if (light < 40) { - System.out.println("Желтый"); - } else if (light < 55) { - System.out.println("Красный"); - } else { - System.out.println("Желтый"); - } - break; - } - } catch (NumberFormatException e) { - System.out.println("Разрешено вводить только числа"); } + } catch (NumberFormatException e) { + System.out.println("Разрешено вводить только целые положительные числа"); } } } + From a656a097691e45b9d15ee24f59f22c31c2c03572 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 25 Jul 2021 12:44:37 +0300 Subject: [PATCH 16/44] traffic light remade according to specification --- src/main/java/homework_2/TrafficLight.java | 51 ------------------- .../pyramid_printer/PyramidPrinter.java | 31 +++++++++++ .../java/homework_2/traffic_light/Main.java | 9 ++++ .../traffic_light/TrafficLight.java | 51 +++++++++++++++++++ 4 files changed, 91 insertions(+), 51 deletions(-) delete mode 100644 src/main/java/homework_2/TrafficLight.java create mode 100644 src/main/java/homework_2/pyramid_printer/PyramidPrinter.java create mode 100644 src/main/java/homework_2/traffic_light/Main.java create mode 100644 src/main/java/homework_2/traffic_light/TrafficLight.java diff --git a/src/main/java/homework_2/TrafficLight.java b/src/main/java/homework_2/TrafficLight.java deleted file mode 100644 index 08a65f5e..00000000 --- a/src/main/java/homework_2/TrafficLight.java +++ /dev/null @@ -1,51 +0,0 @@ -package homework_2; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -public class TrafficLight { -// считывает количество секунд с начала дня с командной строки во время работы, переводит в инт, -// выводит в командную строку цвет светофора (любым вариантом/сообщением, -// главное чтобы было различие зеленый-желтый-красный). -// Цикл светофора - 60 секунд. -// С 0 <= light < 35 зеленый, 35 <= light < 40 желтый, 40 <= light < 55 красный, 55 <= light < 60 желтый. -// -// Ограничения ввода: минимальное 0, максимальное 24*60*60 - 1 = 86399 - - public static void main(String[] args) throws IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - String str; - - while (true) { - System.out.println("Введите целое число от 0 до 86399"); - str = reader.readLine(); - - try { - int time = Integer.parseInt(str); - if (time < 0){ - System.out.println("Разрешено вводить только положительные числа"); - } - else if (time > 86399) { - System.out.println("Вы ввели слишком большое число. День закончился"); - } - else { - int light = time % 60; - - if (light < 35) { - System.out.println(" Зеленый"); - } else if (light < 40) { - System.out.println("Желтый"); - } else if (light < 55) { - System.out.println("Красный"); - } else { - System.out.println("Желтый"); - } - break; - } - } catch (NumberFormatException e) { - System.out.println("Разрешено вводить только числа"); - } - } - } -} 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..773f738c --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,31 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { +// считывает число с командной строки, и печатает пирамиду из "x" согласно введенному положительному целому числу. +// После первой печати завершает работу. + + public static void main(String[] args) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + String str; + int num; + + System.out.println("Введите положительное целое число"); + str = reader.readLine(); + + try { + num = Integer.parseInt(str); + if (num < 0) { + System.out.println("Разрешено вводить только положительные числа"); + } + } catch (NumberFormatException e) { + System.out.println("Разрешено вводить только целые положительные числа"); + } + + System.out.println("здесь писать код"); + + } +} \ No newline at end of file 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..6cd1896e --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,9 @@ +package homework_2.traffic_light; + +import java.io.IOException; + +public class Main { + public static void main(String[] args) throws IOException { + new TrafficLight().run(); + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..e15002be --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,51 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { +// считывает количество секунд с начала дня с командной строки во время работы, переводит в инт, +// выводит в командную строку цвет светофора (любым вариантом/сообщением, +// главное чтобы было различие зеленый-желтый-красный). +// Цикл светофора - 60 секунд. +// С 0 <= light < 35 зеленый, 35 <= light < 40 желтый, 40 <= light < 55 красный, 55 <= light < 60 желтый. +// +// Ограничения ввода: минимальное 0, максимальное 24*60*60 - 1 = 86399 + + public static final String RESET = "\u001B[0m"; + public static final String RED = "\u001B[31m"; + public static final String GREEN = "\u001B[32m"; + public static final String YELLOW = "\u001B[33m"; + + public void run () { + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + String str; + + System.out.println("Enter the number from 0 to 86399"); + + try { + str = reader.readLine(); + int time = Integer.parseInt(str); + if (time < 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter "); + } else if (time > 86399) { + System.out.println("The day is over"); + } else { + int light = time % 60; + + if (light < 35) { + System.out.println(GREEN + "GREEN" + RESET); + } else if (light < 40) { + System.out.println(YELLOW + "YELLOW" + RESET); + } else if (light < 55) { + System.out.println(RED + "RED" + RESET); + } else { + System.out.println(YELLOW + "YELLOW" + RESET); + } + } + } catch (NumberFormatException | IOException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + } +} From 6e99a49744f9e984afc82fd51a93e51dd11b8d22 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 25 Jul 2021 17:25:19 +0300 Subject: [PATCH 17/44] 2nd HW is ready for review --- .../java/homework_2/pyramid_printer/Main.java | 7 ++ .../pyramid_printer/PyramidPrinter.java | 23 +++-- .../java/homework_2/traffic_light/Main.java | 4 +- .../traffic_light/TrafficLight.java | 2 +- src/main/java/random_chars_table/Main.java | 8 ++ .../random_chars_table/RandomCharsTable.java | 97 +++++++++++++++++++ 6 files changed, 129 insertions(+), 12 deletions(-) create mode 100644 src/main/java/homework_2/pyramid_printer/Main.java create mode 100644 src/main/java/random_chars_table/Main.java create mode 100644 src/main/java/random_chars_table/RandomCharsTable.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/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java index 773f738c..bc983c36 100644 --- a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -8,24 +8,31 @@ public class PyramidPrinter { // считывает число с командной строки, и печатает пирамиду из "x" согласно введенному положительному целому числу. // После первой печати завершает работу. - public static void main(String[] args) throws IOException { + public static void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String str; int num; - System.out.println("Введите положительное целое число"); - str = reader.readLine(); + System.out.println("Enter 1 positive integer"); try { + str = reader.readLine(); num = Integer.parseInt(str); if (num < 0) { - System.out.println("Разрешено вводить только положительные числа"); + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } else { + printPyramid(num); } - } catch (NumberFormatException e) { - System.out.println("Разрешено вводить только целые положительные числа"); + } catch (NumberFormatException | IOException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } + } - System.out.println("здесь писать код"); - + private static void printPyramid(int num) { + String output = ""; + for (int i = 0; i < num; i++) { + output += "x"; + System.out.println(output); + } } } \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index 6cd1896e..fa033081 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -1,9 +1,7 @@ package homework_2.traffic_light; -import java.io.IOException; - public class Main { - public static void main(String[] args) throws IOException { + public static void main(String[] args) { new TrafficLight().run(); } } diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java index e15002be..533c6e77 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -18,7 +18,7 @@ public class TrafficLight { public static final String GREEN = "\u001B[32m"; public static final String YELLOW = "\u001B[33m"; - public void run () { + public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String str; diff --git a/src/main/java/random_chars_table/Main.java b/src/main/java/random_chars_table/Main.java new file mode 100644 index 00000000..bba7dfe5 --- /dev/null +++ b/src/main/java/random_chars_table/Main.java @@ -0,0 +1,8 @@ +package random_chars_table; + + +public class Main { + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/random_chars_table/RandomCharsTable.java b/src/main/java/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..e23b2fa6 --- /dev/null +++ b/src/main/java/random_chars_table/RandomCharsTable.java @@ -0,0 +1,97 @@ +package random_chars_table; + +import org.w3c.dom.ls.LSOutput; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + + public void run() { + + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter parameters in following format: [positive integer] [positive integer] [even|odd]"); + + try { + String s = reader.readLine(); + String[] params = s.split(" "); + + int rows = Integer.parseInt(params[0]); + int cols = Integer.parseInt(params[1]); + String strategy = params[2]; + + if (NumOfParamsIsOk(params) && StrategyIsOk(strategy) && isPositive(rows) && isPositive(cols)) { + + char[][] letters = getRandomLetters(rows, cols); + printTable(letters); + printStrategy(letters, strategy); + + } else { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + } + } catch (NumberFormatException | ArrayIndexOutOfBoundsException | IOException e) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + } + } + + private static boolean isPositive(int num) { + return num > 0; + } + + private static boolean StrategyIsOk(String strategy) { + return strategy.equals("even") || strategy.equals("odd"); + } + + private static boolean NumOfParamsIsOk(String[] params) { + return params.length == 3; + } + + private static char[][] getRandomLetters(int rows, int cols) { + int minIndex = 65; //Char A index + int maxIndex = 90; //Char Z index + char[][] randomLettersTable = new char[rows][cols]; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + randomLettersTable[i][j] = (char) ((int) ((Math.random() * (maxIndex - minIndex)) + minIndex)); + } + } + return randomLettersTable; + } + + private static void printTable(char[][] table) { + for (char[] row : table) { + StringBuilder s = new StringBuilder("|"); + for (char letter : row) { + s.append(" ").append(letter).append(" |"); + } + System.out.println(s); + } + } + + private static void printStrategy(char[][] table, String strategy) { + StringBuilder output = new StringBuilder(); + + if (strategy.equals("even")) { + output.append("Even letters - "); + for (char[] row : table) { + for (char letter : row) { + if ((int) letter % 2 == 0) { + output.append(letter).append(", "); + } + } + } + } else { + output.append("Odd letters - "); + for (char[] row : table) { + for (char letter : row) { + if ((int) letter % 2 != 0) { + output.append(letter).append(", "); + } + } + } + } + System.out.println(output.substring(0, output.length() - 2)); + } +} From cd5f59a0904acbeb36caa62f2a315c502289b5aa Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 25 Jul 2021 17:27:04 +0300 Subject: [PATCH 18/44] 2nd HW is ready for review_ --- src/main/java/{ => homework_2}/random_chars_table/Main.java | 2 +- .../{ => homework_2}/random_chars_table/RandomCharsTable.java | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) rename src/main/java/{ => homework_2}/random_chars_table/Main.java (74%) rename src/main/java/{ => homework_2}/random_chars_table/RandomCharsTable.java (98%) diff --git a/src/main/java/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java similarity index 74% rename from src/main/java/random_chars_table/Main.java rename to src/main/java/homework_2/random_chars_table/Main.java index bba7dfe5..08f6f602 100644 --- a/src/main/java/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -1,4 +1,4 @@ -package random_chars_table; +package homework_2.random_chars_table; public class Main { diff --git a/src/main/java/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java similarity index 98% rename from src/main/java/random_chars_table/RandomCharsTable.java rename to src/main/java/homework_2/random_chars_table/RandomCharsTable.java index e23b2fa6..8134cee8 100644 --- a/src/main/java/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -1,6 +1,4 @@ -package random_chars_table; - -import org.w3c.dom.ls.LSOutput; +package homework_2.random_chars_table; import java.io.BufferedReader; import java.io.IOException; From 283294f53b62613703b5dc95cb21d20c48557bfc Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 25 Jul 2021 17:38:55 +0300 Subject: [PATCH 19/44] 2nd HW is ready for review. Added info to README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 585e90c5..2d3dfc21 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,8 @@ | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/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/DimaTroshkin/src/main/java/homework_2) | The app that reads time from keyboard ads says which color the traffic light is| - +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_1/) | The app that reads input arguments and prints them, until "error" argument | +| HW2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard ads says which color the traffic light is| +| HW2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/pyramid_printer/) | The app that makes pyramid of "x" using int input| +| Hw2.3 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/)| The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From d2a67d8e2a6b202b059957fcf3ed075074789fce Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 25 Jul 2021 17:39:51 +0300 Subject: [PATCH 20/44] 2nd HW is ready for review. Added info to README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d3dfc21..f88809c4 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_1/) | The app that reads input arguments and prints them, until "error" argument | -| HW2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard ads says which color the traffic light is| +| HW2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard and says which color the traffic light is| | HW2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/pyramid_printer/) | The app that makes pyramid of "x" using int input| | Hw2.3 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/)| The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 419d58f5bb497f12666e349d45d1948e59fa68c7 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 25 Jul 2021 21:19:38 +0300 Subject: [PATCH 21/44] 2nd HW is ready for review. Added CodingBat Link to README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index f88809c4..0c4fdbbe 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,13 @@ ## *Dima Troshkin* +[CodingBat Account](https://codingbat.com/done?user=allzza4279@gmail.com&tag=1424372731) + | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_1/) | The app that reads input arguments and prints them, until "error" argument | | HW2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard and says which color the traffic light is| | HW2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/pyramid_printer/) | The app that makes pyramid of "x" using int input| | Hw2.3 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/)| The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| + [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 83554282758e1378525827305f0da9b37b31b3b7 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 8 Aug 2021 22:00:01 +0300 Subject: [PATCH 22/44] Tests for HW2 added, +slight changes Immutable Class HW 3 is written --- README.md | 2 +- .../homework_2/random_chars_table/Main.java | 2 +- .../random_chars_table/RandomCharsTable.java | 4 +- .../java/homework_2/traffic_light/Main.java | 2 +- .../traffic_light/TrafficLight.java | 4 +- .../homework_3/ImmutableClassTerminator.java | 55 +++++++ src/main/java/homework_3/Main.java | 24 +++ src/test/java/base/UnitBase.java | 79 +++++----- .../pyramid_printer/PyramidPrinterTest.java | 91 +++++++++++ .../RandomCharsTableTest.java | 144 ++++++++++++++++++ .../traffic_light/TrafficLightTest.java | 123 +++++++++++++++ 11 files changed, 484 insertions(+), 46 deletions(-) create mode 100644 src/main/java/homework_3/ImmutableClassTerminator.java create mode 100644 src/main/java/homework_3/Main.java create mode 100644 src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java create mode 100644 src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java create mode 100644 src/test/java/homework_2/traffic_light/TrafficLightTest.java diff --git a/README.md b/README.md index 0c4fdbbe..a21f9113 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_1/) | The app that reads input arguments and prints them, until "error" argument | | HW2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard and says which color the traffic light is| -| HW2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/pyramid_printer/) | The app that makes pyramid of "x" using int input| +| HW2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/homework_2.pyramid_printer/) | The app that makes pyramid of "x" using int input| | Hw2.3 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/)| The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) 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 08f6f602..6787be60 100644 --- a/src/main/java/homework_2/random_chars_table/Main.java +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -3,6 +3,6 @@ public class Main { public static void main(String[] args) { - new RandomCharsTable().run(); + 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 8134cee8..321d9158 100644 --- a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -6,7 +6,7 @@ public class RandomCharsTable { - public void run() { + public static void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter parameters in following format: [positive integer] [positive integer] [even|odd]"); @@ -28,7 +28,7 @@ public void run() { } else { System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } - } catch (NumberFormatException | ArrayIndexOutOfBoundsException | IOException e) { + } catch (Exception e) { System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); } } diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java index fa033081..1764517c 100644 --- a/src/main/java/homework_2/traffic_light/Main.java +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -2,6 +2,6 @@ public class Main { public static void main(String[] args) { - new TrafficLight().run(); + 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 533c6e77..62b25291 100644 --- a/src/main/java/homework_2/traffic_light/TrafficLight.java +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -18,7 +18,7 @@ public class TrafficLight { public static final String GREEN = "\u001B[32m"; public static final String YELLOW = "\u001B[33m"; - public void run() { + public static void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String str; @@ -28,7 +28,7 @@ public void run() { str = reader.readLine(); int time = Integer.parseInt(str); if (time < 0) { - System.out.println("Only 1 non-negative integer is allowed as passed parameter "); + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); } else if (time > 86399) { System.out.println("The day is over"); } else { diff --git a/src/main/java/homework_3/ImmutableClassTerminator.java b/src/main/java/homework_3/ImmutableClassTerminator.java new file mode 100644 index 00000000..64c0f90b --- /dev/null +++ b/src/main/java/homework_3/ImmutableClassTerminator.java @@ -0,0 +1,55 @@ +package homework_3; + +/* How to make Immutable Objects: + 1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields. + 2. Make all fields final and private. + 3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. + A more sophisticated approach is to make the constructor private and construct instances in factory methods. + 4. If the instance fields include references to mutable objects, don't allow those objects to be changed: + - Don't provide methods that modify the mutable objects. + - Don't share references to the mutable objects. Never store references to external, mutable objects passed to + the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies + of your internal mutable objects when necessary to avoid returning the originals in your methods. +*/ + +import java.util.Date; + +public final class ImmutableClassTerminator { + private final int departureYear; + private final String model; + private final Date timeTravelDate; + + public ImmutableClassTerminator(int departureYear, String model, Date timeTravelDate) { + this.departureYear = departureYear; + this.model = model; + this.timeTravelDate = timeTravelDate; + } + + public ImmutableClassTerminator(int departureYear, Date timeTravelDate) { + this.departureYear = departureYear; + this.model = "T100"; + this.timeTravelDate = timeTravelDate; + } + + public ImmutableClassTerminator(int departureYear, String model) { + this.departureYear = departureYear; + this.model = model; + this.timeTravelDate = new Date(); + } + + public int getDepartureYear() { + return departureYear; + } + + public String getModel() { + return model; + } + + public Date getTimeTravelDate() { + return (Date) timeTravelDate.clone(); + } + + public ImmutableClassTerminator changeTimeTravelDate(Date newTimeTravelDate) { + return new ImmutableClassTerminator(departureYear, model, newTimeTravelDate); + } +} diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java new file mode 100644 index 00000000..058176b1 --- /dev/null +++ b/src/main/java/homework_3/Main.java @@ -0,0 +1,24 @@ +package homework_3; + +import java.util.Date; + +public class Main { + public static void main(String[] args) { + ImmutableClassTerminator terminator = new ImmutableClassTerminator(2077, "T100"); + int year = terminator.getDepartureYear(); + String model = terminator.getModel(); + Date date = terminator.getTimeTravelDate(); + + System.out.println(year); + System.out.println(model); + + System.out.println(date); + date.setTime(0); + System.out.println(date); + System.out.println(terminator.getTimeTravelDate()); //field does not change + + ImmutableClassTerminator newTerminator = terminator.changeTimeTravelDate(new Date(1212121212121L)); + Date newDate = newTerminator.getTimeTravelDate(); + System.out.println(newDate); + } +} diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 97e2685b..a8ff7a28 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -5,58 +5,59 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; public abstract class UnitBase { - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } } - } - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } // @Test // void example() { diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..a6031034 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,91 @@ +package homework_2.pyramid_printer; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +import base.UnitBase; + +class PyramidPrinterTest extends UnitBase { + + @Test + void givenPositiveIntFour_whenRun_thenPrintPyramid() { + setInput("4"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + assertEquals("xxxx", getOutputLines()[3]); + } + + @Test + void givenZero_whenRun_thenWriteErrMsgAndStop() { + setInput("0"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void givenNothing_whenRun_thenWriteErrMsgAndStop() { + setInput(""); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenNegativeInt_whenRun_thenWriteErrMsgAndStop() { + setInput("-4"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenDouble_whenRun_thenWriteErrMsgAndStop() { + setInput("2.5"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenString_whenRun_thenWriteErrMsgAndStop() { + setInput("String"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenMoreThenOneInput_whenRun_thenWriteErrMsgAndStop() { + setInput("3 0"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + +} 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..7701cd75 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,144 @@ +package homework_2.random_chars_table; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import base.UnitBase; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class RandomCharsTableTest extends UnitBase { + + final String WELCOME_MSG = "Enter parameters in following format: [positive integer] [positive integer] [even|odd]"; + final String ERR_MSG = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + @Test + public void givenNull_whenRun_thenPrintErrMsg() { + setInput(""); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenString_whenRun_thenPrintErrMsg() { + setInput("null"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenDoubles_whenRun_thenPrintErrMsg() { + setInput("2.5 3 odd"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenNotEnoughArguments_whenRun_thenPrintErrMsg() { + setInput("25 odd"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenTooManyArguments_whenRun_thenPrintErrMsg() { + setInput("2 5 lol odd"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenWrongStrategy_whenRun_thenPrintErrMsg() { + setInput("2 5 ewen"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenCorrectInputThreeFiveOdd_whenRun_thenPrintErrMsg() { + setInput("3 5 odd"); + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + final String actualResult = getOutputLines()[3]; + removeFromOutput(actualResult); + final String Table = getOutput(); + +// Finding only letters + final Pattern pattern = Pattern.compile("[A-Z]"); + final Matcher matcher = pattern.matcher(Table); + StringBuilder letters = new StringBuilder(); + while (matcher.find()) { + letters.append(matcher.group(0)); + } + +// Applying Strategy + StringBuilder expectedResult = new StringBuilder("Odd letters - "); + for (int i = 0; i < letters.length(); i++) { + char ch = letters.charAt(i); + if ((int) ch % 2 != 0) { + expectedResult.append(ch); + expectedResult.append(", "); + } + } + expectedResult = new StringBuilder(expectedResult.substring(0, expectedResult.length() - 2)); + assertEquals(expectedResult.toString(), actualResult); + } + + @Test + public void givenCorrectInputThreeFiveEven_whenRun_thenPrintErrMsg() { + setInput("3 5 even"); + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + final String actualResult = getOutputLines()[3]; + removeFromOutput(actualResult); + final String Table = getOutput(); + +// Finding only letters + final Pattern pattern = Pattern.compile("[A-Z]"); + final Matcher matcher = pattern.matcher(Table); + StringBuilder letters = new StringBuilder(); + while (matcher.find()) { + letters.append(matcher.group(0)); + } + +// Applying Strategy + StringBuilder expectedResult = new StringBuilder("Even letters - "); + for (int i = 0; i < letters.length(); i++) { + char ch = letters.charAt(i); + if ((int) ch % 2 == 0) { + expectedResult.append(ch); + expectedResult.append(", "); + } + } + expectedResult = new StringBuilder(expectedResult.substring(0, expectedResult.length() - 2)); + assertEquals(expectedResult.toString(), actualResult); + } + +} 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..01cd8278 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,123 @@ +package homework_2.traffic_light; + +import homework_2.random_chars_table.RandomCharsTable; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import base.UnitBase; + +public class TrafficLightTest extends UnitBase { + + final String ERR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + final String WELCOME_MSG = "Enter the number from 0 to 86399"; + final String RED = "[31mRED\u001B[0m"; + final String GREEN = "[32mGREEN\u001B[0m"; + final String YELLOW = "[33mYELLOW\u001B[0m"; + + @Test + public void givenNull_whenRun_thenPrintErrMsg() { + setInput(""); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenString_whenRun_thenPrintErrMsg() { + setInput("someString"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenDouble_whenRun_thenPrintErrMsg() { + setInput("2.55"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenMoreArguments_whenRun_thenPrintErrMsg() { + setInput("2 5"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void given0_whenRun_thenPrintErrMsg() { + setInput("0"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(GREEN, getOutputLines()[0]); + } + + @Test + public void given65_whenRun_thenPrintErrMsg() { + setInput("65"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(GREEN, getOutputLines()[0]); + } + + @Test + public void given35_whenRun_thenPrintErrMsg() { + setInput("35"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(YELLOW, getOutputLines()[0]); + } + + @Test + public void given55_whenRun_thenPrintErrMsg() { + setInput("55"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(YELLOW, getOutputLines()[0]); + } + + @Test + public void given155_whenRun_thenPrintErrMsg() { + setInput("155"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(YELLOW, getOutputLines()[0]); + } + + @Test + public void given40_whenRun_thenPrintErrMsg() { + setInput("40"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(RED, getOutputLines()[0]); + } + + @Test + public void given114_whenRun_thenPrintErrMsg() { + setInput("114"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(RED, getOutputLines()[0]); + } + + @Test + public void givenTooBig_whenRun_thenPrintErrMsg() { + setInput("86401"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals("The day is over", getOutputLines()[0]); + } +} From c6b08c453dc0c05c4e7f6cf7d97920bb370926aa Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 8 Aug 2021 22:26:00 +0300 Subject: [PATCH 23/44] new methods are added to HW2 tests to make code clearer --- .../RandomCharsTableTest.java | 81 +++++++++++-------- 1 file changed, 47 insertions(+), 34 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 7701cd75..bb65cb74 100644 --- a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -1,8 +1,11 @@ package homework_2.random_chars_table; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; + import base.UnitBase; + import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -79,66 +82,76 @@ public void givenWrongStrategy_whenRun_thenPrintErrMsg() { @Test public void givenCorrectInputThreeFiveOdd_whenRun_thenPrintErrMsg() { - setInput("3 5 odd"); + String input = "3 5 odd"; + String strategy = input.split(" ")[2]; + + setInput(input); RandomCharsTable.run(); printOut(); removeFromOutput(WELCOME_MSG); final String actualResult = getOutputLines()[3]; removeFromOutput(actualResult); - final String Table = getOutput(); + final String table = getOutput(); -// Finding only letters - final Pattern pattern = Pattern.compile("[A-Z]"); - final Matcher matcher = pattern.matcher(Table); - StringBuilder letters = new StringBuilder(); - while (matcher.find()) { - letters.append(matcher.group(0)); - } - -// Applying Strategy - StringBuilder expectedResult = new StringBuilder("Odd letters - "); - for (int i = 0; i < letters.length(); i++) { - char ch = letters.charAt(i); - if ((int) ch % 2 != 0) { - expectedResult.append(ch); - expectedResult.append(", "); - } - } - expectedResult = new StringBuilder(expectedResult.substring(0, expectedResult.length() - 2)); + StringBuilder letters = getLettersFromTable(table); + StringBuilder expectedResult = getExpectedResult(letters,strategy); assertEquals(expectedResult.toString(), actualResult); } @Test public void givenCorrectInputThreeFiveEven_whenRun_thenPrintErrMsg() { - setInput("3 5 even"); + String input = "3 5 even"; + String strategy = input.split(" ")[2]; + + setInput(input); RandomCharsTable.run(); printOut(); removeFromOutput(WELCOME_MSG); final String actualResult = getOutputLines()[3]; removeFromOutput(actualResult); - final String Table = getOutput(); + final String table = getOutput(); + + StringBuilder letters = getLettersFromTable(table); + StringBuilder expectedResult = getExpectedResult(letters,strategy); + assertEquals(expectedResult.toString(), actualResult); + } -// Finding only letters - final Pattern pattern = Pattern.compile("[A-Z]"); - final Matcher matcher = pattern.matcher(Table); + + public StringBuilder getLettersFromTable(String table) { + Pattern pattern = Pattern.compile("[A-Z]"); + Matcher matcher = pattern.matcher(table); StringBuilder letters = new StringBuilder(); while (matcher.find()) { letters.append(matcher.group(0)); } + return letters; + } -// Applying Strategy - StringBuilder expectedResult = new StringBuilder("Even letters - "); - for (int i = 0; i < letters.length(); i++) { - char ch = letters.charAt(i); - if ((int) ch % 2 == 0) { - expectedResult.append(ch); - expectedResult.append(", "); + public StringBuilder getExpectedResult(StringBuilder letters, String strategy) { + StringBuilder expectedResult = new StringBuilder(); + + if (strategy.equals("even")) { + expectedResult.append("Even letters - "); + for (int i = 0; i < letters.length(); i++) { + char ch = letters.charAt(i); + if ((int) ch % 2 == 0) { + expectedResult.append(ch); + expectedResult.append(", "); + } + } + } else { + expectedResult.append("Odd letters - "); + for (int i = 0; i < letters.length(); i++) { + char ch = letters.charAt(i); + if ((int) ch % 2 != 0) { + expectedResult.append(ch); + expectedResult.append(", "); + } } } expectedResult = new StringBuilder(expectedResult.substring(0, expectedResult.length() - 2)); - assertEquals(expectedResult.toString(), actualResult); + return expectedResult; } - } From 42342a74854b3efa891f0662cb04ff6cca3c498f Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 8 Aug 2021 22:39:38 +0300 Subject: [PATCH 24/44] README info added --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a21f9113..4d231aab 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,14 @@ ## *Dima Troshkin* -[CodingBat Account](https://codingbat.com/done?user=allzza4279@gmail.com&tag=1424372731) +[CodingBat Profile](https://codingbat.com/done?user=allzza4279@gmail.com&tag=1424372731) | Number | Solution | Short description | --- | --- | --- | | HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_1/) | The app that reads input arguments and prints them, until "error" argument | -| HW2.1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard and says which color the traffic light is| -| HW2.2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/homework_2.pyramid_printer/) | The app that makes pyramid of "x" using int input| -| Hw2.3 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/)| The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| +| HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard and says which color the traffic light is| +| | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/homework_2.pyramid_printer/) | The app that makes pyramid of "x" using int input| +| | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/) | The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_3/)| An example of Immutable Class realization | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 31540dcd2a47ef8a42bae3e6e03dbbab2dc11241 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sat, 21 Aug 2021 11:24:44 +0300 Subject: [PATCH 25/44] packages and input for hw4 --- .../custom_file_reader/CustomFileReader.java | 9 +++++++++ src/main/java/homework_4/custom_file_reader/Main.java | 4 ++++ src/main/resources/custom_file_reader/file.txt | 11 +++++++++++ 3 files changed, 24 insertions(+) create mode 100644 src/main/java/homework_4/custom_file_reader/CustomFileReader.java create mode 100644 src/main/java/homework_4/custom_file_reader/Main.java create mode 100644 src/main/resources/custom_file_reader/file.txt diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..766225fe --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,9 @@ +package homework_4.custom_file_reader; + +import java.io.FileInputStream; + +public class CustomFileReader { + String FILENAME = ""; + +// FileInputStream fileInputStream = new FileInputStream(); +} 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..f280e600 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,4 @@ +package homework_4.custom_file_reader; + +public class Main { +} diff --git a/src/main/resources/custom_file_reader/file.txt b/src/main/resources/custom_file_reader/file.txt new file mode 100644 index 00000000..3a35e7f4 --- /dev/null +++ b/src/main/resources/custom_file_reader/file.txt @@ -0,0 +1,11 @@ +В дипломатии и продвинутой психологии есть один мощный прием, который помогает моментально поставить на место самых +разных людей. Помогает вытащить на свет и выставить напоказ их поверхностные знания, слабую компетенцию и +неосведомленность. С его помощью вы сможете быстро занять уверенную позицию в разговоре и решительно развернуть общение +в свою пользу. +Прием называется "Вскрыть незнание". Сразу к сути. Человек сообщает свое мнение. Говорит что-то, в чем, как он думает, +он хорошо разбирается. Вы, с помощью уточняющих вопросов, спрашиваете его, насколько он хорошо знаком с другими +мнениями, фактами и знаниями по теме. +Убедившись, что собеседник не обладает достаточным количеством знаний для объективного анализа, вы открыто подводите +его к мысли и делаете вывод, что он в принципе не может быть прав, так как не знает полной картины темы обсуждения. +А, значит, вообще не может думать и утверждать, что он прав. Потому что его выводы построены на однобоком и очень +шатком фундаменте, который может обрушиться в любой момент, как только появятся новые знания. \ No newline at end of file From a85f7af33541f518c2075e25fc1c65c675f9ed41 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sat, 21 Aug 2021 13:29:52 +0300 Subject: [PATCH 26/44] new file.txt --- .../custom_file_reader/CustomFileReader.java | 18 ++++++++-- .../homework_4/custom_file_reader/Main.java | 25 ++++++++++++++ .../resources/custom_file_reader/file.txt | 34 +++++++++++++------ 3 files changed, 64 insertions(+), 13 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 766225fe..848e8c0b 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -1,9 +1,23 @@ package homework_4.custom_file_reader; +import java.io.File; import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; public class CustomFileReader { - String FILENAME = ""; + final static String FILE_PATH = "custom_file_reader" + File.separator + "file.txt"; -// FileInputStream fileInputStream = new FileInputStream(); + + public static void run1() throws IOException { + System.out.println(FILE_PATH); + FileInputStream fileInputStream = new FileInputStream(FILE_PATH); + int i; + + while((i=fileInputStream.read())!= -1){ + System.out.print((char)i); + } + } } diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java index f280e600..aeaec293 100644 --- a/src/main/java/homework_4/custom_file_reader/Main.java +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -1,4 +1,29 @@ package homework_4.custom_file_reader; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + public class Main { + public static void main(String[] args) throws IOException { +// CustomFileReader customFileReader = new CustomFileReader(); +// CustomFileReader.run1(); + +// URL url = new URL("https://github.com/NikolaevArtem/Java_Core_June_2021/blob/31540dcd2a47ef8a42bae3e6e03dbbab2dc11241/src/main/resources/custom_file_reader/file.txt"); +// InputStream input = url.openStream(); +// byte[] buffer = input.readAllBytes(); +// String str = new String(buffer); +// System.out.println(str); + + Path path = Path.of("src/main/resources/custom_file_reader/file.txt"); + List list = Files.readAllLines(path); + + for (String str : list) + System.out.println(str); + } + + } diff --git a/src/main/resources/custom_file_reader/file.txt b/src/main/resources/custom_file_reader/file.txt index 3a35e7f4..8af74d73 100644 --- a/src/main/resources/custom_file_reader/file.txt +++ b/src/main/resources/custom_file_reader/file.txt @@ -1,11 +1,23 @@ -В дипломатии и продвинутой психологии есть один мощный прием, который помогает моментально поставить на место самых -разных людей. Помогает вытащить на свет и выставить напоказ их поверхностные знания, слабую компетенцию и -неосведомленность. С его помощью вы сможете быстро занять уверенную позицию в разговоре и решительно развернуть общение -в свою пользу. -Прием называется "Вскрыть незнание". Сразу к сути. Человек сообщает свое мнение. Говорит что-то, в чем, как он думает, -он хорошо разбирается. Вы, с помощью уточняющих вопросов, спрашиваете его, насколько он хорошо знаком с другими -мнениями, фактами и знаниями по теме. -Убедившись, что собеседник не обладает достаточным количеством знаний для объективного анализа, вы открыто подводите -его к мысли и делаете вывод, что он в принципе не может быть прав, так как не знает полной картины темы обсуждения. -А, значит, вообще не может думать и утверждать, что он прав. Потому что его выводы построены на однобоком и очень -шатком фундаменте, который может обрушиться в любой момент, как только появятся новые знания. \ No newline at end of file +July 4, 1776 + +The Unanimous Declaration of the thirteen united* States of America. + +When, in the course of human events, it becomes necessary for one people to dissolve the Political Bands which have +connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the +Laws of Nature and of Nature's God entitle them, a decent Respect to the Opinions of Mankind requires that they should +declare the causes which impel them to the Separation. + +We hold these Truths to be self-evident, that all Men are created equal, that they are endowed by their Creator with +certain unalienable Rights, that among these are Life, Liberty and the Pursuit of Happiness -- That to secure these +Rights, Governments are instituted among Men, deriving their just Powers from the Consent of the Governed, that +whenever any Form of Government becomes destructive to these Ends, it is the Right of the People to alter or to abolish +it, and to institute new Government, laying its Foundation on such Principles and organizing its Powers in such Form, +as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments +long established should not be changed for light and transient Causes; and accordingly all Experience hath shown that +Mankind are more disposed to suffer, while Evils are sufferable, than to right themselves by abolishing the Forms to +which they are accustomed. But when a long Train of Abuses and Usurpations, pursuing invariably the same Object, +evinces a Design to reduce them under absolute Despotism, it is their Right, it is their Duty, to throw off such +Government, and to provide new Guards for their future Security. Such has been the patient Sufferance of these Colonies; +and such is now the Necessity which constrains them to alter their former Systems of Government. The History of the +present King of Great- Britain is a History of repeated Injuries and Usurpations, all having in direct Object the +Establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid World. From 2edf8105da46e6a6f3dd2c60d7fe32a5197541fa Mon Sep 17 00:00:00 2001 From: Allzza Date: Sat, 21 Aug 2021 20:16:32 +0300 Subject: [PATCH 27/44] HW 4 is done --- .../custom_annotation/CustomAnnotation.java | 12 +++++ .../custom_annotation/FirstProgram.java | 19 ++++++++ .../homework_4/custom_annotation/Main.java | 11 +++++ .../custom_file_reader/CustomFileReader.java | 48 ++++++++++++++----- .../homework_4/custom_file_reader/Main.java | 16 ++----- src/main/java/homework_4/singleton/Main.java | 8 ++++ .../java/homework_4/singleton/Singleton.java | 15 ++++++ .../custom_file_reader/file_for_test.txt | 23 +++++++++ .../traffic_light/TrafficLightTest.java | 1 - .../CustomAnnotationTest.java | 25 ++++++++++ .../CustomFileReaderTest.java | 45 +++++++++++++++++ .../homework_4/singleton/SingletonTest.java | 14 ++++++ 12 files changed, 211 insertions(+), 26 deletions(-) create mode 100644 src/main/java/homework_4/custom_annotation/CustomAnnotation.java create mode 100644 src/main/java/homework_4/custom_annotation/FirstProgram.java create mode 100644 src/main/java/homework_4/custom_annotation/Main.java create mode 100644 src/main/java/homework_4/singleton/Main.java create mode 100644 src/main/java/homework_4/singleton/Singleton.java create mode 100644 src/main/resources/custom_file_reader/file_for_test.txt create mode 100644 src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java create mode 100644 src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java create mode 100644 src/test/java/homework_4/singleton/SingletonTest.java diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java new file mode 100644 index 00000000..23e1d35c --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE ) +public @interface CustomAnnotation { + String output() default "Hello, World!"; +} diff --git a/src/main/java/homework_4/custom_annotation/FirstProgram.java b/src/main/java/homework_4/custom_annotation/FirstProgram.java new file mode 100644 index 00000000..b6a4b84d --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/FirstProgram.java @@ -0,0 +1,19 @@ +package homework_4.custom_annotation; + +@CustomAnnotation +public class FirstProgram { + private static String output; + + public FirstProgram(String s) { + output = s; + System.out.println(output); + } + + public FirstProgram() { + final CustomAnnotation annotation = FirstProgram.class.getAnnotation(CustomAnnotation.class); + output = annotation.output(); + System.out.println(output); + } + +} + diff --git a/src/main/java/homework_4/custom_annotation/Main.java b/src/main/java/homework_4/custom_annotation/Main.java new file mode 100644 index 00000000..44b1f0c4 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Main.java @@ -0,0 +1,11 @@ +package homework_4.custom_annotation; + +public class Main { + public static void main(String[] args) { + + new FirstProgram(); // with default value given by annotation + new FirstProgram("Hello, 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 848e8c0b..7b4a0243 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -1,23 +1,47 @@ package homework_4.custom_file_reader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; -public class CustomFileReader { - final static String FILE_PATH = "custom_file_reader" + File.separator + "file.txt"; +public class CustomFileReader { + private static final String FILE_PATH = "src/main/resources/custom_file_reader/file.txt"; public static void run1() throws IOException { - System.out.println(FILE_PATH); - FileInputStream fileInputStream = new FileInputStream(FILE_PATH); + String content = Files.readString(Path.of(FILE_PATH)); + printWithoutDotAndComma(content); + } + + + public static void run2() throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(FILE_PATH), 300); int i; + while ((i = bufferedInputStream.read()) != -1) { + printWithoutDotAndComma((char) i); + } + bufferedInputStream.close(); + } - while((i=fileInputStream.read())!= -1){ - System.out.print((char)i); + public static void run3() throws IOException { + FileReader fileReader = new FileReader(FILE_PATH, StandardCharsets.UTF_8); + int i; + while ((i = fileReader.read()) != -1) { + printWithoutDotAndComma((char) i); } + fileReader.close(); + } + + public static void printWithoutDotAndComma(String s) { + char[] chars = s.toCharArray(); + for (char ch : chars) + if (ch != '.' && ch != ',') + System.out.print(ch); + } + + public static void printWithoutDotAndComma(char ch) { + if (ch != '.' && ch != ',') + System.out.print(ch); } } diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java index aeaec293..1a9a16bd 100644 --- a/src/main/java/homework_4/custom_file_reader/Main.java +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -9,20 +9,10 @@ public class Main { public static void main(String[] args) throws IOException { -// CustomFileReader customFileReader = new CustomFileReader(); -// CustomFileReader.run1(); + CustomFileReader.run1(); + CustomFileReader.run2(); + CustomFileReader.run3(); -// URL url = new URL("https://github.com/NikolaevArtem/Java_Core_June_2021/blob/31540dcd2a47ef8a42bae3e6e03dbbab2dc11241/src/main/resources/custom_file_reader/file.txt"); -// InputStream input = url.openStream(); -// byte[] buffer = input.readAllBytes(); -// String str = new String(buffer); -// System.out.println(str); - - Path path = Path.of("src/main/resources/custom_file_reader/file.txt"); - List list = Files.readAllLines(path); - - for (String str : list) - System.out.println(str); } diff --git a/src/main/java/homework_4/singleton/Main.java b/src/main/java/homework_4/singleton/Main.java new file mode 100644 index 00000000..91c5144a --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,8 @@ +package homework_4.singleton; + +public class Main { + public static void main(String[] args) { + System.out.println(Singleton.getInstance()); + System.out.println(Singleton.getInstance()); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..2c2e65b1 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +public class Singleton { + + private Singleton() { + } + + private static class SingletonHolder { + public static final Singleton INSTANCE_HOLDER = new Singleton(); + } + + public static Singleton getInstance() { + return SingletonHolder.INSTANCE_HOLDER; + } +} diff --git a/src/main/resources/custom_file_reader/file_for_test.txt b/src/main/resources/custom_file_reader/file_for_test.txt new file mode 100644 index 00000000..172e0750 --- /dev/null +++ b/src/main/resources/custom_file_reader/file_for_test.txt @@ -0,0 +1,23 @@ +July 4 1776 + +The Unanimous Declaration of the thirteen united* States of America + +When in the course of human events it becomes necessary for one people to dissolve the Political Bands which have +connected them with another and to assume among the Powers of the Earth the separate and equal Station to which the +Laws of Nature and of Nature's God entitle them a decent Respect to the Opinions of Mankind requires that they should +declare the causes which impel them to the Separation + +We hold these Truths to be self-evident that all Men are created equal that they are endowed by their Creator with +certain unalienable Rights that among these are Life Liberty and the Pursuit of Happiness -- That to secure these +Rights Governments are instituted among Men deriving their just Powers from the Consent of the Governed that +whenever any Form of Government becomes destructive to these Ends it is the Right of the People to alter or to abolish +it and to institute new Government laying its Foundation on such Principles and organizing its Powers in such Form +as to them shall seem most likely to effect their Safety and Happiness Prudence indeed will dictate that Governments +long established should not be changed for light and transient Causes; and accordingly all Experience hath shown that +Mankind are more disposed to suffer while Evils are sufferable than to right themselves by abolishing the Forms to +which they are accustomed But when a long Train of Abuses and Usurpations pursuing invariably the same Object +evinces a Design to reduce them under absolute Despotism it is their Right it is their Duty to throw off such +Government and to provide new Guards for their future Security Such has been the patient Sufferance of these Colonies; +and such is now the Necessity which constrains them to alter their former Systems of Government The History of the +present King of Great- Britain is a History of repeated Injuries and Usurpations all having in direct Object the +Establishment of an absolute Tyranny over these States To prove this let Facts be submitted to a candid World \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java index 01cd8278..490be0a1 100644 --- a/src/test/java/homework_2/traffic_light/TrafficLightTest.java +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -1,6 +1,5 @@ package homework_2.traffic_light; -import homework_2.random_chars_table.RandomCharsTable; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import base.UnitBase; diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..2dfe0b40 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,25 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class CustomAnnotationTest extends UnitBase { + private final static String DEFAULT_MESSAGE = "Hello, World!"; + + @Test + public void emptyConstructor() { + new FirstProgram(); + printOut(); + assertEquals(DEFAULT_MESSAGE, getOutput()); + } + + @Test + public void nonEmptyConstructor() { + String msg = "Some message"; + new FirstProgram(msg); + printOut(); + assertEquals(msg, getOutput()); + } + +} 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..79311b1b --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,45 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +class CustomFileReaderTest extends UnitBase { + private static final String FILE_PATH = "src/main/resources/custom_file_reader/file_for_test.txt"; + + @Test + public void checkRun1() throws IOException { + final String expectedContent = Files.readString(Path.of(FILE_PATH)); + + CustomFileReader.run1(); + printOut(); + final String actualContent = getOutput(); + + assertEquals(expectedContent, actualContent); + } + + @Test + public void checkRun2() throws IOException { + final String expectedContent = Files.readString(Path.of(FILE_PATH)); + + CustomFileReader.run2(); + printOut(); + final String actualContent = getOutput(); + + assertEquals(expectedContent, actualContent); + } + + @Test + public void checkRun3() throws IOException { + final String expectedContent = Files.readString(Path.of(FILE_PATH)); + + CustomFileReader.run3(); + printOut(); + final String actualContent = getOutput(); + + assertEquals(expectedContent, actualContent); + } +} 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..3203593d --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,14 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SingletonTest{ + + @Test + public void checkSingleton() { + Singleton singleton = Singleton.getInstance(); + Singleton anotherSingleton = Singleton.getInstance(); + assertEquals(singleton,anotherSingleton); + } +} From 69dbdf9a90da9dfd522953f9811027969e97fba2 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sat, 21 Aug 2021 20:25:21 +0300 Subject: [PATCH 28/44] README.md modified --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d231aab..ff37412c 100644 --- a/README.md +++ b/README.md @@ -11,5 +11,7 @@ | | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/homework_2.pyramid_printer/) | The app that makes pyramid of "x" using int input| | | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/) | The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| | HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_3/)| An example of Immutable Class realization | - +| HW4 | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/custom_annotation/)| An example of custom annotation realization | +| | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/custom_file_reader/)| An app which reads String data from file.txt and removes commas and fullstops | +| | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/singleton/)| An example of singleton class | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From a89343d9cfe49564412a2fb6fd2a9bf40f75051a Mon Sep 17 00:00:00 2001 From: Allzza Date: Sat, 21 Aug 2021 23:19:41 +0300 Subject: [PATCH 29/44] HW 5: PowerOfNumber & tests are done --- .../java/homework_5/power_of_number/Main.java | 7 ++ .../power_of_number/PowerOfNumber.java | 52 +++++++++++ .../power_of_number/PowerOfNumberTest.java | 91 +++++++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 src/main/java/homework_5/power_of_number/Main.java create mode 100644 src/main/java/homework_5/power_of_number/PowerOfNumber.java create mode 100644 src/test/java/homework_5/power_of_number/PowerOfNumberTest.java diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..9a31c2f9 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) throws Throwable { + PowerOfNumber.run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..56f70020 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,52 @@ +package homework_5.power_of_number; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; + +public class PowerOfNumber { + final private static String ERROR_MSG = "Only 2 non-negative integers are allowed"; + private static Object Exception; + + public static void run() throws Throwable { + System.out.println("Enter 2 non-negative integers"); + try { + int[] numbers = getNumbers(); + int a = numbers[0]; + int b = numbers[1]; + System.out.println(power(a,b)); + + } catch (Exception e) { + System.out.println(ERROR_MSG); + } + } + + public static int[] getNumbers() throws Throwable { + String[] s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + s = reader.readLine().split(" "); + + if (s.length != 2) + throw (Throwable) Exception; + + int[] numbers = new int[2]; + for (int i = 0; i < 2; i++) { + numbers[i] = Integer.parseInt(s[i]); + } + + if (numbers[0] < 0 || numbers[1] < 0) + throw (Throwable) Exception; + return numbers; + } + + public static int power(int a, int b) { + int result = 1; + if (b == 0){ + return result; + } + result = a * power(a, b - 1); + return result; + } + +} diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..011da070 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,91 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PowerOfNumberTest extends UnitBase { + final private static String ERROR_MSG = "Only 2 non-negative integers are allowed"; + + @Test + public void given02_whenRun_thenPrint0() throws Throwable { + setInput("0 2"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(0, Integer.parseInt(getOutput())); + } + + @Test + public void given24_whenRun_thenPrint16() throws Throwable { + setInput("2 4"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(16, Integer.parseInt(getOutput())); + } + + @Test + public void given20_whenRun_thenPrint1() throws Throwable { + setInput("2 0"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(1, Integer.parseInt(getOutput())); + } + + @Test + public void givenOneNumber_whenRun_thenPrintErr() throws Throwable { + setInput("2 "); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenMoreNumbersThenNeeded_whenRun_thenPrintErr() throws Throwable { + setInput("2 3 4"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenString_whenRun_thenPrintErr() throws Throwable { + setInput("asg djj"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenDoubleNumbers_whenRun_thenPrintErr() throws Throwable { + setInput("2.0 3.0"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenNegative_whenRun_thenPrintErr() throws Throwable { + setInput("-2 3"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + +} From 95c12905d13f112df9f5f9d026ad072e543a14b5 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sat, 21 Aug 2021 23:26:10 +0300 Subject: [PATCH 30/44] README.md modified for HW5 --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index ff37412c..12fe084d 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,7 @@ | HW4 | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/custom_annotation/)| An example of custom annotation realization | | | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/custom_file_reader/)| An app which reads String data from file.txt and removes commas and fullstops | | | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/singleton/)| An example of singleton class | +| HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/custom_regex_matcher/)| An app which takes String from terminal and checks whether given String matches hardcoded regex| +| | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/power_of_number/)| An app which calculates a^b for two non-negative integers a and b | + [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 06f4d219b1f452824eb37b96c1f3f43e52af473b Mon Sep 17 00:00:00 2001 From: Allzza Date: Thu, 26 Aug 2021 00:29:51 +0300 Subject: [PATCH 31/44] CustomRegexMatcher is done --- .../CustomRegexMatcher.java | 35 +++++++++++++++++++ .../homework_5/custom_regex_matcher/Main.java | 7 ++++ .../CustomRegexMatcherTest.java | 18 ++++++++++ 3 files changed, 60 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 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..8fdd4871 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,35 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + final private static String REGEX = "^\\w*@\\w*\\.\\w*"; + + public static void run() { + try { + String s = getString(); + System.out.println(matchRegex(s)); + } catch (Throwable e){ + System.out.println("Wrong input"); + } + + } + + public static String getString() throws Throwable { + System.out.println("Please, enter your string..."); + String s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + s = reader.readLine(); + reader.close(); + return s; + } + + public static boolean matchRegex(String s) { + Pattern pattern = Pattern.compile(REGEX); + Matcher matcher = pattern.matcher(s); + return (matcher.matches()); + } +} 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..930fddfb --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) throws Throwable { + CustomRegexMatcher.run(); + } +} 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..71209efe --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,18 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomRegexMatcherTest extends UnitBase { + + @Test + public void givenMatching1_whenRun_thenPrintTrue() { + setInput("allzza4279@gmail.com"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("true",getOutput()); + } +} From 4377bb9113b0b8abc3ee31ac8c5488c54ef4444d Mon Sep 17 00:00:00 2001 From: Allzza Date: Thu, 26 Aug 2021 21:07:38 +0300 Subject: [PATCH 32/44] CustomRegexMatcher tests added --- .../CustomRegexMatcherTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) 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 71209efe..dfa459a4 100644 --- a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -15,4 +15,34 @@ public void givenMatching1_whenRun_thenPrintTrue() { assertEquals("true",getOutput()); } + + @Test + public void givenMatching2_whenRun_thenPrintTrue() { + setInput("dimatroshkin@mail.ru"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("true",getOutput()); + } + + @Test + public void givenNonMatching1_whenRun_thenPrintFalse() { + setInput("my email is: dimatroshkin@mail.ru"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("false",getOutput()); + } + + @Test + public void givenNonMatching2_whenRun_thenPrintFalse() { + setInput("/.epof@.rert.surr"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("false",getOutput()); + } } From 3c0bae2db12ad4160391d2374b01febf376d6051 Mon Sep 17 00:00:00 2001 From: Allzza Date: Wed, 15 Sep 2021 23:03:27 +0300 Subject: [PATCH 33/44] hw 7 done --- README.md | 2 +- src/main/java/homework_7/Cat.java | 47 ++++++++++++++++++ src/main/java/homework_7/Kitten.java | 48 ++++++++++++++++++ .../java/homework_7/KittenToCatFunction.java | 6 +++ src/main/java/homework_7/Main.java | 26 ++++++++++ src/main/java/homework_7/SubKitten.java | 49 +++++++++++++++++++ 6 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 src/main/java/homework_7/Cat.java create mode 100644 src/main/java/homework_7/Kitten.java create mode 100644 src/main/java/homework_7/KittenToCatFunction.java create mode 100644 src/main/java/homework_7/Main.java create mode 100644 src/main/java/homework_7/SubKitten.java diff --git a/README.md b/README.md index 12fe084d..b4b639e1 100644 --- a/README.md +++ b/README.md @@ -16,5 +16,5 @@ | | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/singleton/)| An example of singleton class | | HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/custom_regex_matcher/)| An app which takes String from terminal and checks whether given String matches hardcoded regex| | | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/power_of_number/)| An app which calculates a^b for two non-negative integers a and b | - +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_7/)| The realisation of @FunctionalInterface KittenToCatFunction with abstract method grow(). From now on we know how does kitten become a cat!| [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..dcdaca27 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,47 @@ +package homework_7; + +public class Cat { + private String name; + private int age; + private int weight; + + static { + System.out.println(" My \"MEOW\" grows! I wanna eat! \n"); + } + + 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 void setAge(int age) { + this.age = age; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void Meow() { + System.out.println("This is real MEOW! I wanna eat!"); + } + + @Override + public String toString() { + return "Cat " + name + " is " + age + " months old and weights " + weight + " gr. Truly mature cat! \n"; + } + +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..d50fd502 --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,48 @@ +package homework_7; + +public class Kitten { + private String name; + private int age; + private int weight; + + static { + System.out.println(" ... new kitten has just appeared! \n"); + } + + public Kitten(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 void setAge(int age) { + this.age = age; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void Meow() { + System.out.println("meoww! meoww!"); + } + + @Override + public String toString() { + return "Kitten " + name + " is only " + age + " months old and weights just " + weight + " g. So tiny and cute! \n"; + } + +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..7ff36d0e --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7; + +@FunctionalInterface +public interface KittenToCatFunction { + Cat grow(Kitten kitten); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..9d4b5cd5 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,26 @@ +package homework_7; + +public class Main { + + public static void main(String[] args) { + KittenToCatFunction timeToGrow = k -> new Cat(k.getName(), 12, k.getWeight()*4); + + Kitten youngKitten = new Kitten("Vaskya", 2, 250); + System.out.println(youngKitten); + +// then.. + Cat matureCat = timeToGrow.grow(youngKitten); + System.out.println(matureCat); + +// Let`s try to make Cat from Cat + Cat oldCat = new Cat("Serj", 24, 2000); +// Cat old = timeToGrow.grow(oldCat); doesn`t work + +// Let`s try to make Cat from SubKitten + SubKitten subKitten = new SubKitten("Antoha", 8, 500); + Cat matureCatFromSubKitten = timeToGrow.grow(subKitten); // it works + System.out.println(matureCatFromSubKitten); + } + + +} diff --git a/src/main/java/homework_7/SubKitten.java b/src/main/java/homework_7/SubKitten.java new file mode 100644 index 00000000..136cdcde --- /dev/null +++ b/src/main/java/homework_7/SubKitten.java @@ -0,0 +1,49 @@ +package homework_7; + +public class SubKitten extends Kitten{ + + private String name; + private int age; + private int weight; + + public SubKitten(String name, int age, int weight) { + super(name,age,weight); + this.name = name; + this.age = age; + this.weight = weight; + } + + static { + System.out.println(" ... new SubKitten has just appeared! \n"); + } + + public String getName() { + return name; + } + + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void Meow() { + System.out.println("SubKitten meoww! SubKitten meoww!"); + } + + @Override + public String toString() { + return "SubKitten " + name + " is only " + age + " months old and weights just " + weight + " g. So subtiny and subcute! \n"; + } +} From 2a79bf109c04a4f4d4a78a10ee4d7ead18b2c8a3 Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 19 Sep 2021 01:19:07 +0300 Subject: [PATCH 34/44] course project alpha --- src/main/java/course_project/Battle.java | 57 ++++ src/main/java/course_project/Main.java | 11 + .../course_project/engine/BoardPrinter.java | 58 ++++ .../java/course_project/engine/Input.java | 66 +++++ .../engine/PositionChecker.java | 76 +++++ .../course_project/engine/ShipPlacer.java | 65 ++++ .../java/course_project/engine/Shooter.java | 83 ++++++ .../java/course_project/models/Board.java | 43 +++ .../course_project/models/Coordinate.java | 74 +++++ .../java/course_project/models/Player.java | 65 ++++ src/main/java/course_project/models/Ship.java | 51 ++++ .../course_project/BoardChangeCellTest.java | 52 ++++ .../course_project/CoordinateCheckTest.java | 86 ++++++ .../java/course_project/ModeCheckTest.java | 63 ++++ .../ShipPositioningCheckerTest.java | 277 ++++++++++++++++++ 15 files changed, 1127 insertions(+) create mode 100644 src/main/java/course_project/Battle.java create mode 100644 src/main/java/course_project/Main.java create mode 100644 src/main/java/course_project/engine/BoardPrinter.java create mode 100644 src/main/java/course_project/engine/Input.java create mode 100644 src/main/java/course_project/engine/PositionChecker.java create mode 100644 src/main/java/course_project/engine/ShipPlacer.java create mode 100644 src/main/java/course_project/engine/Shooter.java create mode 100644 src/main/java/course_project/models/Board.java create mode 100644 src/main/java/course_project/models/Coordinate.java create mode 100644 src/main/java/course_project/models/Player.java create mode 100644 src/main/java/course_project/models/Ship.java create mode 100644 src/test/java/course_project/BoardChangeCellTest.java create mode 100644 src/test/java/course_project/CoordinateCheckTest.java create mode 100644 src/test/java/course_project/ModeCheckTest.java create mode 100644 src/test/java/course_project/ShipPositioningCheckerTest.java diff --git a/src/main/java/course_project/Battle.java b/src/main/java/course_project/Battle.java new file mode 100644 index 00000000..8595569b --- /dev/null +++ b/src/main/java/course_project/Battle.java @@ -0,0 +1,57 @@ +package course_project; + +import course_project.models.Player; +import course_project.models.Ship; +import course_project.engine.ShipPlacer; +import course_project.engine.Shooter; + +import java.io.IOException; +import java.util.ArrayList; + +public class Battle { + + public static void run() throws IOException { + Player player1 = new Player(); + Player player2 = new Player(); + + ArrayList players = new ArrayList<>(); + players.add(player1); + players.add(player2); + + Player currentPlayer; + for (Player player : players) { // preparing both players battlefields + currentPlayer = player; + + System.out.println("\n \n" + currentPlayer.Name() + ", welcome to the Sea Battle. \n \n" + + "It`s time to place your ships. Remember the main rule: ships must not touch each other.\n" + "To place a ship you basically need to type coordinate and then choose mode. \n" + + "There are two ways to place your ships from starting coordinate: from left to right (key \"h\") & from up to down (key \"v\")\n" + + "If there is only one possible way, it will be chosen automatically, if it`s impossible to place ship from this coordinate, you will have to choose another one.\n"); + + System.out.println("Let`s begin with Carrier - huge battleship with size 4. \n"); + ShipPlacer.placement(new Ship("Carrier", 4), currentPlayer); + + System.out.println("Now place 2 Cruisers of size 3"); + for (int i = 0; i < 2; i++) { + ShipPlacer.placement(new Ship("Cruiser", 3), currentPlayer); + } + System.out.println("Now place 3 Destroyers of size 2"); + for (int i = 0; i < 3; i++) { + ShipPlacer.placement(new Ship("Destroyer", 2), currentPlayer); + } + System.out.println("And finally place 4 Scout ships of size 1"); + for (int i = 0; i < 4; i++) { + ShipPlacer.placement(new Ship("Scout", 1), currentPlayer); + } + } + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n"); + + while (player1.Hp() > 0 && player2.Hp() > 0) { + Shooter.Shoot(player1, player2); + if (player2.Hp() == 0) { + break; + } + Shooter.Shoot(player2, player1); + } + } +} diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..7e09e77f --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +import java.io.IOException; + +public class Main { + + + public static void main(String[] args) throws IOException { + Battle.run(); + } +} diff --git a/src/main/java/course_project/engine/BoardPrinter.java b/src/main/java/course_project/engine/BoardPrinter.java new file mode 100644 index 00000000..db265e90 --- /dev/null +++ b/src/main/java/course_project/engine/BoardPrinter.java @@ -0,0 +1,58 @@ +package course_project.engine; + +import course_project.models.Player; +import course_project.models.Board; + +import java.util.Locale; + +public class BoardPrinter { + + public static void printMainBoard(Player player) { + Board board = player.MainBoard(); + System.out.println(player.Name() + ": MAIN BOARD"); + int rowNum = 1; + String rowOffset; + System.out.println(" " + board.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); + for (int row : board.getRowNames()) { + rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; + System.out.print(rowOffset); + + for (String cell : board.getBoard().get(row)){ + System.out.print(" " + cell + " " + "|"); + } + System.out.print("\n"); + rowNum++; + } + } + + public static void printBothBoards(Player player) { + Board mainBoard = player.MainBoard(); + Board scanBoard = player.ScanBoard(); + int rowNum = 1; + String spaceBetween = " "; + String rowOffset; + System.out.println(spaceBetween + player.Name() + ": MAIN BOARD" + spaceBetween + spaceBetween + " ENEMY TRACKING"); + // top + System.out.print(" " + mainBoard.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); + System.out.print(spaceBetween); + System.out.println(" " + scanBoard.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); + + for (int row : mainBoard.getRowNames()) { + rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; + System.out.print(rowOffset); + + for (String cell : mainBoard.getBoard().get(row)){ + System.out.print(" " + cell + " " + "|"); + } + System.out.print(spaceBetween); + System.out.print(rowOffset); + for (String cell : scanBoard.getBoard().get(row)){ + System.out.print(" " + cell + " " + "|"); + } + + System.out.print("\n"); + rowNum++; + } + } + +} diff --git a/src/main/java/course_project/engine/Input.java b/src/main/java/course_project/engine/Input.java new file mode 100644 index 00000000..6c7e168e --- /dev/null +++ b/src/main/java/course_project/engine/Input.java @@ -0,0 +1,66 @@ +package course_project.engine; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Locale; + +public class Input { + + public static String getRightCoordinate() throws IOException { + System.out.println("Enter coordinate if format: \"a1\""); + String s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + s = reader.readLine(); + if (Input.checkCoordinate(s)) { + System.out.println("Coordinate: " + s); + return s; + } else { + System.out.println("Wrong Input! use letters from a to j and numbers from 1 to 10, like \"d4\""); + } + } + } + + public static String getRightMode() throws IOException { + System.out.println("Choose mode: use letter \"v\" to place it vertically or \"h\" to place it horizontally"); + String s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + s = reader.readLine(); + if (Input.checkMode(s)) { + System.out.println("Mode: " + s); + return s; + } else { + System.out.println("Wrong mode! use letter \"v\" to place it vertically or \"h\" to place it horizontally."); + } + } + } + + public static boolean checkCoordinate(String s) { + if (s.length() > 3 || s.length() < 2) { + return false; + } + + if (!s.toLowerCase(Locale.ROOT).substring(0,1).matches("[a-j]")) { + return false; + } + + if (!s.toLowerCase(Locale.ROOT).substring(1,2).matches("[1-9]")) { + return false; + } + + if (s.length() == 3 && !s.toLowerCase(Locale.ROOT).substring(2).matches("0")) { + return false; + } + return true; + } + + public static boolean checkMode(String s) { + if (s.toLowerCase(Locale.ROOT).matches("[vh]")) { + return true; + } + return false; + } + +} diff --git a/src/main/java/course_project/engine/PositionChecker.java b/src/main/java/course_project/engine/PositionChecker.java new file mode 100644 index 00000000..431e2d5a --- /dev/null +++ b/src/main/java/course_project/engine/PositionChecker.java @@ -0,0 +1,76 @@ +package course_project.engine; + +import course_project.models.Board; +import course_project.models.Coordinate; + +import java.util.List; + +public class PositionChecker { + + public static boolean possibleToPlace(Board b, Coordinate c, int size, String mode) { + // mode h: left -> right , mode v: up - > down from coordinate given + int horizSize; + int vertSize; + + if (mode.equalsIgnoreCase("h")) { // space needed for ship in horizontal mode + horizSize = size; + vertSize = 1; + } else { // space needed for ship in vertical mode + horizSize = 1; + vertSize = size; + } + + List currentRow; + List upperRow; + List lowerRow; + + // Checking upper row + if (b.getBoard().containsKey(c.Row() - 1)) { // if it exist + upperRow = b.getBoard().get(c.Row() - 1); + for (int col = c.Col() - 1; col <= c.Col() + horizSize; col++) { // check all cols from current -1 to current + size + if (col >= 0 && col < 10) { // if mainBoard contains such col + if (!upperRow.get(col).equals(" ")) { // cell must be empty + return false; + } + } + } + } + + // Checking hull rows + for (int i = 0; i < vertSize; i++) { + if (!b.getBoard().containsKey(c.Row() + i)) { // if doesn`t exist -> not enough vertical space + return false; + } + currentRow = b.getBoard().get(c.Row() + i); + for (int col = c.Col() - 1; col <= c.Col() + horizSize; col++) { // check all cols from current -1 to current + horiz size + if (col >= 0 && col < 10) { // if mainBoard contains such col + if (!currentRow.get(col).equals(" ")) { // cell must be empty + return false; + } + } else { + if ((col - 1 > 9) && mode.equalsIgnoreCase("h")) { // if not enough space horizontally (last hull coord comes out of the map) + return false; + } + } + } + + } + + + // Checking lower row + if (b.getBoard().containsKey(c.Row() + vertSize)) { // if it exist + lowerRow = b.getBoard().get(c.Row() + vertSize); + for (int col = c.Col() - 1; col <= c.Col() + horizSize; col++) { // check all cols from current -1 to current + size + if (col >= 0 && col < 10) { // if mainBoard contains such col + if (!lowerRow.get(col).equals(" ")) { // cell must be empty + return false; + } + } + } + } + + return true; + } + + +} diff --git a/src/main/java/course_project/engine/ShipPlacer.java b/src/main/java/course_project/engine/ShipPlacer.java new file mode 100644 index 00000000..6054b1af --- /dev/null +++ b/src/main/java/course_project/engine/ShipPlacer.java @@ -0,0 +1,65 @@ +package course_project.engine; + +import course_project.models.Player; +import course_project.models.Board; +import course_project.models.Coordinate; +import course_project.models.Ship; + +import java.io.IOException; +import java.util.ArrayList; + +public class ShipPlacer { + + public static void placement(Ship ship, Player p) throws IOException { + + Board b = p.MainBoard(); + while (true) { + BoardPrinter.printMainBoard(p); + System.out.println("It`s time to place a ship."); + Coordinate c = new Coordinate(Input.getRightCoordinate()); + String mode; + int size = ship.getSize(); + + if (PositionChecker.possibleToPlace(b, c, size, "v") && PositionChecker.possibleToPlace(b, c, size, "h")) { + if (size == 1) { //scout does not need direction + placeShip(p,c,ship,"h"); + break; + } + mode = Input.getRightMode(); + placeShip(p,c,ship,mode); + break; + + } else if (PositionChecker.possibleToPlace(b, c, size, "v")) { + placeShip(p,c,ship,"v"); + break; + } else if (PositionChecker.possibleToPlace(b, c, size, "h")) { + placeShip(p,c,ship,"h"); + break; + } else { + System.out.println("Impossible to place it here!"); + } + } + } + + private static void placeShip(Player p, Coordinate c, Ship ship, String mode ) { + Board b = p.MainBoard(); + int size = ship.getSize(); + int cCol = c.Col(); // current col & row + int cRow = c.Row(); + ArrayList shipCoords = new ArrayList<>(); + for (int i = 0; i < size; i++) { + if (mode.equalsIgnoreCase("h")) { + shipCoords.add(new Coordinate(cRow, cCol + i)); + } else if (mode.equalsIgnoreCase("v")) { + shipCoords.add(new Coordinate(cRow + i, cCol)); + } + } + for (Coordinate coordinate : shipCoords) { + b.changeCell(coordinate, "H"); + } + ship.setCoords(shipCoords); + p.Ships().add(ship); + BoardPrinter.printMainBoard(p); + } +} + diff --git a/src/main/java/course_project/engine/Shooter.java b/src/main/java/course_project/engine/Shooter.java new file mode 100644 index 00000000..c0a6677a --- /dev/null +++ b/src/main/java/course_project/engine/Shooter.java @@ -0,0 +1,83 @@ +package course_project.engine; + +import course_project.models.Player; +import course_project.models.Ship; +import course_project.models.Coordinate; + + +import java.io.IOException; +import java.util.List; + +public class Shooter { + + public static void Shoot(Player currentPlayer, Player enemyPlayer) throws IOException { + boolean shootMore = true; + while (shootMore) { + System.out.println(currentPlayer.Name() + " turn! Enter a coordinate to shoot."); + BoardPrinter.printBothBoards(currentPlayer); + Coordinate c = getUniqueShoot(currentPlayer); + + for (Ship ship : enemyPlayer.Ships()) { + + if (ship.getCoords().contains(c)) { + shootMore = true; + ship.decreaseHp(); + enemyPlayer.reduceHp(); + addMark(currentPlayer, enemyPlayer, c, "X"); + + if (shipAlive(ship)) { + System.out.println("Successful hit! Shoot one more time!"); + } else { + if (enemyPlayer.Hp() == 0) { + System.out.println("Enemy " + ship + " killed!"); + System.out.println(currentPlayer.Name() + " won! Congratulations!!!"); + shootMore = false; + break; + } + System.out.println("Enemy " + ship + " killed! Shoot one more time!"); + //TODO get oriole coordinates and fill + } + break; //another ships cannot contain that coordinate + } else { + shootMore = false; + } + } + if (!shootMore && enemyPlayer.Hp() > 0) { + System.out.println("Miss!"); + addMark(currentPlayer, enemyPlayer, c, "*"); + } + } + } + + private static Coordinate getUniqueShoot(Player currentPlayer) throws IOException { + while (true) { + Coordinate c = new Coordinate(Input.getRightCoordinate()); + if (currentPlayer.CheckedCells().contains(c)) { + System.out.println("That cell is already checked, choose another one"); + } else { + currentPlayer.CheckedCells().add(c); + System.out.println("Shooting at cell " + c + "..."); + return c; + } + } + } + + private static boolean shipAlive(Ship ship) { + return ship.getHp() > 0; + } + + private static void addMark(Player currentPlayer, Player enemyPlayer, Coordinate c, String sign) { + enemyPlayer.MainBoard().changeCell(c, sign); + currentPlayer.ScanBoard().changeCell(c, sign); + } + + private static void addMark(Player currentPlayer, Player enemyPlayer, List coordinateList, String sign) { + for (Coordinate c : coordinateList) { + enemyPlayer.MainBoard().changeCell(c, sign); + currentPlayer.ScanBoard().changeCell(c, sign); + } + } + +// private static ArrayList oreole + +} diff --git a/src/main/java/course_project/models/Board.java b/src/main/java/course_project/models/Board.java new file mode 100644 index 00000000..611a919c --- /dev/null +++ b/src/main/java/course_project/models/Board.java @@ -0,0 +1,43 @@ +package course_project.models; + +import java.util.*; + +public class Board { + private HashMap> board; + private final List rowNames = Arrays.asList(1, 2 , 3, 4, 5, 6, 7, 8, 9, 10); + private final List colNames = Arrays.asList("a", "b" , "c", "d", "e", "f", "g", "h", "i", "j"); + private final List emptyRows = Arrays.asList(" ", " " , " ", " ", " ", " ", " ", " ", " ", " "); + + public Board() { + this.board = new HashMap<>(); + for (int r : rowNames) { + board.put(r, getEmptyRows()); + } + } + + private List getEmptyRows() { + return new ArrayList<>(emptyRows); + } + + public List getRowNames() { + return this.rowNames; + } + + public List getColNames() { + return this.colNames; + } + + public HashMap> getBoard() { + return this.board; + } + + public void changeCell(Coordinate coordinate, String sign) { + List currentRow = board.get(coordinate.Row()); + currentRow.set(coordinate.Col(),sign); + board.put(coordinate.Row(), currentRow); + } + + public String getCell(Coordinate c) { + return board.get(c.Row()).get(c.Col()); + } +} diff --git a/src/main/java/course_project/models/Coordinate.java b/src/main/java/course_project/models/Coordinate.java new file mode 100644 index 00000000..35a39713 --- /dev/null +++ b/src/main/java/course_project/models/Coordinate.java @@ -0,0 +1,74 @@ +package course_project.models; + +import java.util.Locale; +import java.util.Objects; + +public class Coordinate { + private int col; + private int row; + + public Coordinate(String s) { + col = s.toLowerCase(Locale.ROOT).charAt(0) - 97; + row = Integer.parseInt(s.substring(1)); + } + + public Coordinate(int r, int c) { + this.row = r; + this.col = c; + } + + public Coordinate(Coordinate c) { + this.row = c.row; + this.col = c.col; + } + + public int Col() { + return col; + } + + public int Row() { + return row; + } + + @Override + public String toString() { + return "" + (char) (col + 97) + row; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Coordinate)) return false; + Coordinate that = (Coordinate) o; + return Col() == that.Col() && Row() == that.Row(); + } + + @Override + public int hashCode() { + return Objects.hash(Col(), Row()); + } + + public boolean exists() { + return this.row >= 1 && this.row <= 10 && this.col >= 0 && this.col <= 9; + } + + public Coordinate upper() { + return new Coordinate(this.row - 1, this.col); + } + + public Coordinate lower() { + return new Coordinate(this.row + 1, this.col); + } + + public Coordinate lower(int n) { + return new Coordinate(this.row + n, this.col); + } + + public Coordinate toLeft() { + return new Coordinate(this.row, this.col - 1); + } + + public Coordinate toRight() { + return new Coordinate(this.row, this.col + 1); + } +} diff --git a/src/main/java/course_project/models/Player.java b/src/main/java/course_project/models/Player.java new file mode 100644 index 00000000..406905ee --- /dev/null +++ b/src/main/java/course_project/models/Player.java @@ -0,0 +1,65 @@ +package course_project.models; + +import java.util.ArrayList; +import java.util.HashSet; + +public class Player { + private static int count = 1; + private String name; + private ArrayList ships; + private Board mainBoard; + private Board scanBoard; + private HashSet checkedCells; + private int hp = 20; + + public Player(String name) { + this.name = name; + ships = new ArrayList<>(10); + mainBoard = new Board(); + scanBoard = new Board(); + checkedCells = new HashSet<>(40); + count++; + } + + public Player() { + this.name = "Player " + count; + ships = new ArrayList<>(10); + mainBoard = new Board(); + scanBoard = new Board(); + checkedCells = new HashSet<>(40); + count++; + } + + + public static void setCount(int count) { + Player.count = count; + } + + public String Name() { + return name; + } + + public ArrayList Ships() { + return ships; + } + + public Board MainBoard() { + return mainBoard; + } + + public Board ScanBoard() { + return scanBoard; + } + + public HashSet CheckedCells() { + return checkedCells; + } + + public void reduceHp() { + hp--; + } + + public int Hp() { + return hp; + } +} diff --git a/src/main/java/course_project/models/Ship.java b/src/main/java/course_project/models/Ship.java new file mode 100644 index 00000000..9a0620e3 --- /dev/null +++ b/src/main/java/course_project/models/Ship.java @@ -0,0 +1,51 @@ +package course_project.models; + +import java.util.ArrayList; + +public class Ship { + private String name; + private int hp; + private int size; + private ArrayList coords; + + public Ship(String name, int size) { + this.name = name; + this.size = size; + this.hp = size; + this.coords = new ArrayList<>(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getHp() { + return hp; + } + + public int getSize() { + return size; + } + + + public ArrayList getCoords() { + return coords; + } + + public void setCoords(ArrayList coords) { + this.coords = coords; + } + + public void decreaseHp() { + hp--; + } + + @Override + public String toString() { + return name; + } +} diff --git a/src/test/java/course_project/BoardChangeCellTest.java b/src/test/java/course_project/BoardChangeCellTest.java new file mode 100644 index 00000000..ffe74f28 --- /dev/null +++ b/src/test/java/course_project/BoardChangeCellTest.java @@ -0,0 +1,52 @@ +package course_project; + +import course_project.models.Board; +import course_project.models.Coordinate; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class BoardChangeCellTest { + + + Board b = new Board(); + Coordinate c; + String sign; + + @Test + void putA1() { + c = new Coordinate("a1"); + sign = "v"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + + @Test + void putJ10() { + c = new Coordinate("j10"); + sign = "t"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + + @Test + void putA10() { + c = new Coordinate("a10"); + sign = "*"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + + @Test + void putJ1() { + c = new Coordinate("a10"); + sign = "X"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + +} diff --git a/src/test/java/course_project/CoordinateCheckTest.java b/src/test/java/course_project/CoordinateCheckTest.java new file mode 100644 index 00000000..0423b06b --- /dev/null +++ b/src/test/java/course_project/CoordinateCheckTest.java @@ -0,0 +1,86 @@ +package course_project; + +import course_project.engine.Input; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class CoordinateCheckTest { + + @Test + void testWrongInput_1() { + String input = "a0"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_2() { + String input = "0"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_3() { + String input = "q"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_4() { + String input = "q1"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_5() { + String input = ""; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_6() { + String input = "null"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_7() { + String input = "a12"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_8() { + String input = "k6"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_9() { + String input = "112"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_10() { + String input = "abds"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testRightInput_1() { + String input = "a1"; + assertTrue(Input.checkCoordinate(input)); + } + + @Test + void testRightInput_2() { + String input = "B6"; + assertTrue(Input.checkCoordinate(input)); + } + @Test + void testRightInput_3() { + String input = "j10"; + assertTrue(Input.checkCoordinate(input)); + } + +} diff --git a/src/test/java/course_project/ModeCheckTest.java b/src/test/java/course_project/ModeCheckTest.java new file mode 100644 index 00000000..35410400 --- /dev/null +++ b/src/test/java/course_project/ModeCheckTest.java @@ -0,0 +1,63 @@ +package course_project; + +import course_project.engine.Input; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class ModeCheckTest { + + @Test + void testGivenRightMode_v() { + String input = "v"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenRightMode_V() { + String input = "V"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenRightMode_h() { + String input = "h"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenRightMode_H() { + String input = "H"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_1() { + String input = "Hv"; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_2() { + String input = "g"; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_3() { + String input = "1"; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_4() { + String input = " "; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_5() { + String input = ""; + assertFalse(Input.checkMode(input)); + } + +} diff --git a/src/test/java/course_project/ShipPositioningCheckerTest.java b/src/test/java/course_project/ShipPositioningCheckerTest.java new file mode 100644 index 00000000..87c884bb --- /dev/null +++ b/src/test/java/course_project/ShipPositioningCheckerTest.java @@ -0,0 +1,277 @@ +package course_project; +import course_project.models.Board; +import course_project.models.Coordinate; +import course_project.engine.PositionChecker; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class ShipPositioningCheckerTest { + + Board b = new Board(); + Coordinate c; + int size; + String mode; + + + @Test + void test_EnoughPlace_VerticalA1() { + c = new Coordinate("a1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_EnoughPlace_Horizontal_A1() { + c = new Coordinate("a1"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_EnoughPlace_Vertical_J1() { + c = new Coordinate("j1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_EnoughPlace_Vertical_A6() { + c = new Coordinate("a6"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_EnoughPlace_Horizontal_A6() { + c = new Coordinate("a6"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_EnoughPlace_Horizontal_A10() { + c = new Coordinate("a8"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_NotEnoughPlace_Vertical_A8() { + c = new Coordinate("a8"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_NotEnoughPlace_HorizontalJ1() { + c = new Coordinate("j1"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_NotEnoughPlace_HorizontalJ8() { + c = new Coordinate("j8"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalD1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d1"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalE1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("e1"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalF1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f1"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalD5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d5"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalE5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("e5"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalF5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f5"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalD6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d6"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalE6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("e6"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalF6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f6"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalA4() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("a4"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalA5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("a5"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalA6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("a6"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalF4() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f4"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalF5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f5"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalF6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f6"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_HorizontalC3() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("c3"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_HorizontalD7() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d7"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_HorizontalG4() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("g4"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_VerticalC1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("c1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_VerticalG1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("g1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_VerticalD7() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("g1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + } + +} From 23bf1afd86148c2803ccab0e87d3ffed292b942d Mon Sep 17 00:00:00 2001 From: Allzza Date: Sun, 19 Sep 2021 01:28:58 +0300 Subject: [PATCH 35/44] README.md modified --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b4b639e1..54907e64 100644 --- a/README.md +++ b/README.md @@ -17,4 +17,5 @@ | HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/custom_regex_matcher/)| An app which takes String from terminal and checks whether given String matches hardcoded regex| | | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/power_of_number/)| An app which calculates a^b for two non-negative integers a and b | | HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_7/)| The realisation of @FunctionalInterface KittenToCatFunction with abstract method grow(). From now on we know how does kitten become a cat!| +| HW7 | [SeaBattle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/course_project/)| The Sea Battle game 1 by 1 (No AI) | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) From 23dfa528a1c5cfa35dec7fede96c05b0c585932f Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 20 Sep 2021 00:21:16 +0300 Subject: [PATCH 36/44] slight changes, added important test section, checked style --- src/main/java/course_project/Battle.java | 23 ++-- .../course_project/engine/BoardPrinter.java | 20 +-- .../java/course_project/engine/Input.java | 4 +- .../engine/PositionChecker.java | 18 +-- .../course_project/engine/ShipPlacer.java | 20 +-- .../java/course_project/engine/Shooter.java | 81 ++++++------ .../java/course_project/models/Board.java | 24 ++-- .../course_project/models/Coordinate.java | 20 +-- .../java/course_project/models/Player.java | 30 ++--- src/main/java/course_project/models/Ship.java | 15 +-- .../course_project/CoordinateCheckTest.java | 2 + .../java/course_project/MakeOneShootTest.java | 122 ++++++++++++++++++ .../java/course_project/ModeCheckTest.java | 1 + .../ShipPositioningCheckerTest.java | 62 ++++----- 14 files changed, 287 insertions(+), 155 deletions(-) create mode 100644 src/test/java/course_project/MakeOneShootTest.java diff --git a/src/main/java/course_project/Battle.java b/src/main/java/course_project/Battle.java index 8595569b..16b31572 100644 --- a/src/main/java/course_project/Battle.java +++ b/src/main/java/course_project/Battle.java @@ -22,7 +22,7 @@ public static void run() throws IOException { for (Player player : players) { // preparing both players battlefields currentPlayer = player; - System.out.println("\n \n" + currentPlayer.Name() + ", welcome to the Sea Battle. \n \n" + + System.out.println("\n \n" + currentPlayer.name() + ", welcome to the Sea Battle. \n \n" + "It`s time to place your ships. Remember the main rule: ships must not touch each other.\n" + "To place a ship you basically need to type coordinate and then choose mode. \n" + "There are two ways to place your ships from starting coordinate: from left to right (key \"h\") & from up to down (key \"v\")\n" + "If there is only one possible way, it will be chosen automatically, if it`s impossible to place ship from this coordinate, you will have to choose another one.\n"); @@ -34,21 +34,22 @@ public static void run() throws IOException { for (int i = 0; i < 2; i++) { ShipPlacer.placement(new Ship("Cruiser", 3), currentPlayer); } - System.out.println("Now place 3 Destroyers of size 2"); - for (int i = 0; i < 3; i++) { - ShipPlacer.placement(new Ship("Destroyer", 2), currentPlayer); - } - System.out.println("And finally place 4 Scout ships of size 1"); - for (int i = 0; i < 4; i++) { - ShipPlacer.placement(new Ship("Scout", 1), currentPlayer); - } +// System.out.println("Now place 3 Destroyers of size 2"); +// for (int i = 0; i < 3; i++) { +// ShipPlacer.placement(new Ship("Destroyer", 2), currentPlayer); +// } +// System.out.println("And finally place 4 Scout ships of size 1"); +// for (int i = 0; i < 4; i++) { +// ShipPlacer.placement(new Ship("Scout", 1), currentPlayer); +// } + } System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n"); - while (player1.Hp() > 0 && player2.Hp() > 0) { + while (player1.hp() > 0 && player2.hp() > 0) { Shooter.Shoot(player1, player2); - if (player2.Hp() == 0) { + if (player2.hp() == 0) { break; } Shooter.Shoot(player2, player1); diff --git a/src/main/java/course_project/engine/BoardPrinter.java b/src/main/java/course_project/engine/BoardPrinter.java index db265e90..6174fee6 100644 --- a/src/main/java/course_project/engine/BoardPrinter.java +++ b/src/main/java/course_project/engine/BoardPrinter.java @@ -8,16 +8,16 @@ public class BoardPrinter { public static void printMainBoard(Player player) { - Board board = player.MainBoard(); - System.out.println(player.Name() + ": MAIN BOARD"); + Board board = player.mainBoard(); + System.out.println(player.name() + ": MAIN BOARD"); int rowNum = 1; String rowOffset; System.out.println(" " + board.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); for (int row : board.getRowNames()) { - rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; + rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; System.out.print(rowOffset); - for (String cell : board.getBoard().get(row)){ + for (String cell : board.getBoard().get(row)) { System.out.print(" " + cell + " " + "|"); } System.out.print("\n"); @@ -26,27 +26,27 @@ public static void printMainBoard(Player player) { } public static void printBothBoards(Player player) { - Board mainBoard = player.MainBoard(); - Board scanBoard = player.ScanBoard(); + Board mainBoard = player.mainBoard(); + Board scanBoard = player.scanBoard(); int rowNum = 1; String spaceBetween = " "; String rowOffset; - System.out.println(spaceBetween + player.Name() + ": MAIN BOARD" + spaceBetween + spaceBetween + " ENEMY TRACKING"); + System.out.println(spaceBetween + player.name() + ": MAIN BOARD" + spaceBetween + spaceBetween + " ENEMY TRACKING"); // top System.out.print(" " + mainBoard.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); System.out.print(spaceBetween); System.out.println(" " + scanBoard.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); for (int row : mainBoard.getRowNames()) { - rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; + rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; System.out.print(rowOffset); - for (String cell : mainBoard.getBoard().get(row)){ + for (String cell : mainBoard.getBoard().get(row)) { System.out.print(" " + cell + " " + "|"); } System.out.print(spaceBetween); System.out.print(rowOffset); - for (String cell : scanBoard.getBoard().get(row)){ + for (String cell : scanBoard.getBoard().get(row)) { System.out.print(" " + cell + " " + "|"); } diff --git a/src/main/java/course_project/engine/Input.java b/src/main/java/course_project/engine/Input.java index 6c7e168e..79ebebb5 100644 --- a/src/main/java/course_project/engine/Input.java +++ b/src/main/java/course_project/engine/Input.java @@ -42,11 +42,11 @@ public static boolean checkCoordinate(String s) { return false; } - if (!s.toLowerCase(Locale.ROOT).substring(0,1).matches("[a-j]")) { + if (!s.toLowerCase(Locale.ROOT).substring(0, 1).matches("[a-j]")) { return false; } - if (!s.toLowerCase(Locale.ROOT).substring(1,2).matches("[1-9]")) { + if (!s.toLowerCase(Locale.ROOT).substring(1, 2).matches("[1-9]")) { return false; } diff --git a/src/main/java/course_project/engine/PositionChecker.java b/src/main/java/course_project/engine/PositionChecker.java index 431e2d5a..0beae767 100644 --- a/src/main/java/course_project/engine/PositionChecker.java +++ b/src/main/java/course_project/engine/PositionChecker.java @@ -25,9 +25,9 @@ public static boolean possibleToPlace(Board b, Coordinate c, int size, String mo List lowerRow; // Checking upper row - if (b.getBoard().containsKey(c.Row() - 1)) { // if it exist - upperRow = b.getBoard().get(c.Row() - 1); - for (int col = c.Col() - 1; col <= c.Col() + horizSize; col++) { // check all cols from current -1 to current + size + if (b.getBoard().containsKey(c.row() - 1)) { // if it exist + upperRow = b.getBoard().get(c.row() - 1); + for (int col = c.col() - 1; col <= c.col() + horizSize; col++) { // check all cols from current -1 to current + size if (col >= 0 && col < 10) { // if mainBoard contains such col if (!upperRow.get(col).equals(" ")) { // cell must be empty return false; @@ -38,11 +38,11 @@ public static boolean possibleToPlace(Board b, Coordinate c, int size, String mo // Checking hull rows for (int i = 0; i < vertSize; i++) { - if (!b.getBoard().containsKey(c.Row() + i)) { // if doesn`t exist -> not enough vertical space + if (!b.getBoard().containsKey(c.row() + i)) { // if doesn`t exist -> not enough vertical space return false; } - currentRow = b.getBoard().get(c.Row() + i); - for (int col = c.Col() - 1; col <= c.Col() + horizSize; col++) { // check all cols from current -1 to current + horiz size + currentRow = b.getBoard().get(c.row() + i); + for (int col = c.col() - 1; col <= c.col() + horizSize; col++) { // check all cols from current -1 to current + horiz size if (col >= 0 && col < 10) { // if mainBoard contains such col if (!currentRow.get(col).equals(" ")) { // cell must be empty return false; @@ -58,9 +58,9 @@ public static boolean possibleToPlace(Board b, Coordinate c, int size, String mo // Checking lower row - if (b.getBoard().containsKey(c.Row() + vertSize)) { // if it exist - lowerRow = b.getBoard().get(c.Row() + vertSize); - for (int col = c.Col() - 1; col <= c.Col() + horizSize; col++) { // check all cols from current -1 to current + size + if (b.getBoard().containsKey(c.row() + vertSize)) { // if it exist + lowerRow = b.getBoard().get(c.row() + vertSize); + for (int col = c.col() - 1; col <= c.col() + horizSize; col++) { // check all cols from current -1 to current + size if (col >= 0 && col < 10) { // if mainBoard contains such col if (!lowerRow.get(col).equals(" ")) { // cell must be empty return false; diff --git a/src/main/java/course_project/engine/ShipPlacer.java b/src/main/java/course_project/engine/ShipPlacer.java index 6054b1af..b2807e7d 100644 --- a/src/main/java/course_project/engine/ShipPlacer.java +++ b/src/main/java/course_project/engine/ShipPlacer.java @@ -12,7 +12,7 @@ public class ShipPlacer { public static void placement(Ship ship, Player p) throws IOException { - Board b = p.MainBoard(); + Board b = p.mainBoard(); while (true) { BoardPrinter.printMainBoard(p); System.out.println("It`s time to place a ship."); @@ -22,18 +22,18 @@ public static void placement(Ship ship, Player p) throws IOException { if (PositionChecker.possibleToPlace(b, c, size, "v") && PositionChecker.possibleToPlace(b, c, size, "h")) { if (size == 1) { //scout does not need direction - placeShip(p,c,ship,"h"); + placeShip(p, c, ship, "h"); break; } mode = Input.getRightMode(); - placeShip(p,c,ship,mode); + placeShip(p, c, ship, mode); break; } else if (PositionChecker.possibleToPlace(b, c, size, "v")) { - placeShip(p,c,ship,"v"); + placeShip(p, c, ship, "v"); break; } else if (PositionChecker.possibleToPlace(b, c, size, "h")) { - placeShip(p,c,ship,"h"); + placeShip(p, c, ship, "h"); break; } else { System.out.println("Impossible to place it here!"); @@ -41,11 +41,11 @@ public static void placement(Ship ship, Player p) throws IOException { } } - private static void placeShip(Player p, Coordinate c, Ship ship, String mode ) { - Board b = p.MainBoard(); + public static void placeShip(Player p, Coordinate c, Ship ship, String mode) { + Board b = p.mainBoard(); int size = ship.getSize(); - int cCol = c.Col(); // current col & row - int cRow = c.Row(); + int cCol = c.col(); // current col & row + int cRow = c.row(); ArrayList shipCoords = new ArrayList<>(); for (int i = 0; i < size; i++) { if (mode.equalsIgnoreCase("h")) { @@ -58,7 +58,7 @@ private static void placeShip(Player p, Coordinate c, Ship ship, String mode ) { b.changeCell(coordinate, "H"); } ship.setCoords(shipCoords); - p.Ships().add(ship); + p.ships().add(ship); BoardPrinter.printMainBoard(p); } } diff --git a/src/main/java/course_project/engine/Shooter.java b/src/main/java/course_project/engine/Shooter.java index c0a6677a..8a703f12 100644 --- a/src/main/java/course_project/engine/Shooter.java +++ b/src/main/java/course_project/engine/Shooter.java @@ -11,51 +11,59 @@ public class Shooter { public static void Shoot(Player currentPlayer, Player enemyPlayer) throws IOException { - boolean shootMore = true; - while (shootMore) { - System.out.println(currentPlayer.Name() + " turn! Enter a coordinate to shoot."); + + while (true) { + System.out.println(currentPlayer.name() + " turn! Enter a coordinate to shoot."); BoardPrinter.printBothBoards(currentPlayer); Coordinate c = getUniqueShoot(currentPlayer); + if (!makeOneShoot(currentPlayer, enemyPlayer, c)) { //if miss - no other try + break; + } + } + } - for (Ship ship : enemyPlayer.Ships()) { - - if (ship.getCoords().contains(c)) { - shootMore = true; - ship.decreaseHp(); - enemyPlayer.reduceHp(); - addMark(currentPlayer, enemyPlayer, c, "X"); - - if (shipAlive(ship)) { - System.out.println("Successful hit! Shoot one more time!"); - } else { - if (enemyPlayer.Hp() == 0) { - System.out.println("Enemy " + ship + " killed!"); - System.out.println(currentPlayer.Name() + " won! Congratulations!!!"); - shootMore = false; - break; - } - System.out.println("Enemy " + ship + " killed! Shoot one more time!"); - //TODO get oriole coordinates and fill - } - break; //another ships cannot contain that coordinate + public static boolean makeOneShoot(Player currentPlayer, Player enemyPlayer, Coordinate c) { + + boolean shootMore = true; + for (Ship ship : enemyPlayer.ships()) { + + if (ship.getCoords().contains(c)) { + shootMore = true; + ship.reduceHp(); + enemyPlayer.reduceHp(); + addMark(currentPlayer, enemyPlayer, c, "X"); + + if (shipAlive(ship)) { + System.out.println("Successful hit! Shoot one more time!"); } else { - shootMore = false; + if (enemyPlayer.hp() == 0) { + System.out.println("Enemy " + ship + " killed!"); + System.out.println(currentPlayer.name() + " won! Congratulations!!!"); + shootMore = false; + break; + } + System.out.println("Enemy " + ship + " killed! Shoot one more time!"); + //TODO get oriole coordinates and fill } + break; //another ships cannot contain that coordinate + } else { + shootMore = false; } - if (!shootMore && enemyPlayer.Hp() > 0) { - System.out.println("Miss!"); - addMark(currentPlayer, enemyPlayer, c, "*"); - } } + if (!shootMore && enemyPlayer.hp() > 0) { + System.out.println("Miss!"); + addMark(currentPlayer, enemyPlayer, c, "*"); + } + return shootMore; } private static Coordinate getUniqueShoot(Player currentPlayer) throws IOException { while (true) { Coordinate c = new Coordinate(Input.getRightCoordinate()); - if (currentPlayer.CheckedCells().contains(c)) { + if (currentPlayer.checkedCells().contains(c)) { System.out.println("That cell is already checked, choose another one"); } else { - currentPlayer.CheckedCells().add(c); + currentPlayer.checkedCells().add(c); System.out.println("Shooting at cell " + c + "..."); return c; } @@ -67,17 +75,18 @@ private static boolean shipAlive(Ship ship) { } private static void addMark(Player currentPlayer, Player enemyPlayer, Coordinate c, String sign) { - enemyPlayer.MainBoard().changeCell(c, sign); - currentPlayer.ScanBoard().changeCell(c, sign); + enemyPlayer.mainBoard().changeCell(c, sign); + currentPlayer.scanBoard().changeCell(c, sign); } private static void addMark(Player currentPlayer, Player enemyPlayer, List coordinateList, String sign) { for (Coordinate c : coordinateList) { - enemyPlayer.MainBoard().changeCell(c, sign); - currentPlayer.ScanBoard().changeCell(c, sign); + enemyPlayer.mainBoard().changeCell(c, sign); + currentPlayer.scanBoard().changeCell(c, sign); } } -// private static ArrayList oreole + //TODO +// private static ArrayList oreole(){} } diff --git a/src/main/java/course_project/models/Board.java b/src/main/java/course_project/models/Board.java index 611a919c..17b787d3 100644 --- a/src/main/java/course_project/models/Board.java +++ b/src/main/java/course_project/models/Board.java @@ -4,9 +4,9 @@ public class Board { private HashMap> board; - private final List rowNames = Arrays.asList(1, 2 , 3, 4, 5, 6, 7, 8, 9, 10); - private final List colNames = Arrays.asList("a", "b" , "c", "d", "e", "f", "g", "h", "i", "j"); - private final List emptyRows = Arrays.asList(" ", " " , " ", " ", " ", " ", " ", " ", " ", " "); + private final List rowNames = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + private final List colNames = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); + private final List emptyRows = Arrays.asList(" ", " ", " ", " ", " ", " ", " ", " ", " ", " "); public Board() { this.board = new HashMap<>(); @@ -15,6 +15,16 @@ public Board() { } } + public void changeCell(Coordinate coordinate, String sign) { + List currentRow = board.get(coordinate.row()); + currentRow.set(coordinate.col(), sign); + board.put(coordinate.row(), currentRow); + } + + public String getCell(Coordinate c) { + return board.get(c.row()).get(c.col()); + } + private List getEmptyRows() { return new ArrayList<>(emptyRows); } @@ -31,13 +41,5 @@ public HashMap> getBoard() { return this.board; } - public void changeCell(Coordinate coordinate, String sign) { - List currentRow = board.get(coordinate.Row()); - currentRow.set(coordinate.Col(),sign); - board.put(coordinate.Row(), currentRow); - } - public String getCell(Coordinate c) { - return board.get(c.Row()).get(c.Col()); - } } diff --git a/src/main/java/course_project/models/Coordinate.java b/src/main/java/course_project/models/Coordinate.java index 35a39713..469561d3 100644 --- a/src/main/java/course_project/models/Coordinate.java +++ b/src/main/java/course_project/models/Coordinate.java @@ -22,14 +22,6 @@ public Coordinate(Coordinate c) { this.col = c.col; } - public int Col() { - return col; - } - - public int Row() { - return row; - } - @Override public String toString() { return "" + (char) (col + 97) + row; @@ -40,12 +32,20 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Coordinate)) return false; Coordinate that = (Coordinate) o; - return Col() == that.Col() && Row() == that.Row(); + return col() == that.col() && row() == that.row(); } @Override public int hashCode() { - return Objects.hash(Col(), Row()); + return Objects.hash(col(), row()); + } + + public int col() { + return col; + } + + public int row() { + return row; } public boolean exists() { diff --git a/src/main/java/course_project/models/Player.java b/src/main/java/course_project/models/Player.java index 406905ee..2dfe32ca 100644 --- a/src/main/java/course_project/models/Player.java +++ b/src/main/java/course_project/models/Player.java @@ -10,7 +10,7 @@ public class Player { private Board mainBoard; private Board scanBoard; private HashSet checkedCells; - private int hp = 20; + private int hp = 20; //default hp for whose set of ships public Player(String name) { this.name = name; @@ -30,36 +30,36 @@ public Player() { count++; } + public void reduceHp() { + hp--; + } - public static void setCount(int count) { - Player.count = count; + public void setHp(int n) { + this.hp = n; + } + + public int hp() { + return hp; } - public String Name() { + public String name() { return name; } - public ArrayList Ships() { + public ArrayList ships() { return ships; } - public Board MainBoard() { + public Board mainBoard() { return mainBoard; } - public Board ScanBoard() { + public Board scanBoard() { return scanBoard; } - public HashSet CheckedCells() { + public HashSet checkedCells() { return checkedCells; } - public void reduceHp() { - hp--; - } - - public int Hp() { - return hp; - } } diff --git a/src/main/java/course_project/models/Ship.java b/src/main/java/course_project/models/Ship.java index 9a0620e3..f17a21c6 100644 --- a/src/main/java/course_project/models/Ship.java +++ b/src/main/java/course_project/models/Ship.java @@ -15,12 +15,13 @@ public Ship(String name, int size) { this.coords = new ArrayList<>(); } - public String getName() { + @Override + public String toString() { return name; } - public void setName(String name) { - this.name = name; + public void reduceHp() { + hp--; } public int getHp() { @@ -31,7 +32,6 @@ public int getSize() { return size; } - public ArrayList getCoords() { return coords; } @@ -40,12 +40,5 @@ public void setCoords(ArrayList coords) { this.coords = coords; } - public void decreaseHp() { - hp--; - } - @Override - public String toString() { - return name; - } } diff --git a/src/test/java/course_project/CoordinateCheckTest.java b/src/test/java/course_project/CoordinateCheckTest.java index 0423b06b..132c7021 100644 --- a/src/test/java/course_project/CoordinateCheckTest.java +++ b/src/test/java/course_project/CoordinateCheckTest.java @@ -2,6 +2,7 @@ import course_project.engine.Input; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; public class CoordinateCheckTest { @@ -77,6 +78,7 @@ void testRightInput_2() { String input = "B6"; assertTrue(Input.checkCoordinate(input)); } + @Test void testRightInput_3() { String input = "j10"; diff --git a/src/test/java/course_project/MakeOneShootTest.java b/src/test/java/course_project/MakeOneShootTest.java new file mode 100644 index 00000000..0313eb9c --- /dev/null +++ b/src/test/java/course_project/MakeOneShootTest.java @@ -0,0 +1,122 @@ +package course_project; + +import course_project.engine.BoardPrinter; +import course_project.engine.ShipPlacer; +import course_project.engine.Shooter; +import course_project.models.Coordinate; +import course_project.models.Player; +import course_project.models.Ship; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class MakeOneShootTest { + + Player currentPlayer = new Player(); + Player enemyPlayer = new Player(); + + @Test + public void oneShipPlacedA1Horizontally_ShootAround_thenMiss() { + Coordinate toPlace = new Coordinate("a1"); + Coordinate toShoot = new Coordinate("a2"); + ShipPlacer.placeShip(enemyPlayer, toPlace, new Ship("Carrier", 4), "h"); + enemyPlayer.setHp(4); + + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("b2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("c2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("d2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("e1"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("e2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + assertEquals(4, enemyPlayer.hp()); + + BoardPrinter.printMainBoard(enemyPlayer); + } + + @Test + public void oneShipPlacedA1Horizontally_ShootAtShip_thenHit() { + Coordinate toPlace = new Coordinate("a1"); + Coordinate toShoot = new Coordinate("a1"); + ShipPlacer.placeShip(enemyPlayer, toPlace, new Ship("Carrier", 4), "h"); + enemyPlayer.setHp(4); + + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("b1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("c1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("d1"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // enemyPlayer has no HP, stop shooting + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + assertEquals(0, enemyPlayer.hp()); + + BoardPrinter.printMainBoard(enemyPlayer); + } + + @Test + public void twoShipsPlacedA1Horizontally_andE2VerticallyShootAtShipsReverseOrder_thenHit() { + Coordinate toPlace1 = new Coordinate("a1"); + Coordinate toPlace2 = new Coordinate("e2"); + + ShipPlacer.placeShip(enemyPlayer, toPlace1, new Ship("Carrier", 4), "h"); + ShipPlacer.placeShip(enemyPlayer, toPlace2, new Ship("Cruiser", 3), "v"); + enemyPlayer.setHp(7); + + Coordinate toShoot = new Coordinate("e4"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("e3"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("e2"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("d1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("c1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("b1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("a1"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // enemyPlayer has no HP, stop shooting + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + assertEquals(0, enemyPlayer.hp()); + + BoardPrinter.printMainBoard(enemyPlayer); + } + +} diff --git a/src/test/java/course_project/ModeCheckTest.java b/src/test/java/course_project/ModeCheckTest.java index 35410400..bcd253dd 100644 --- a/src/test/java/course_project/ModeCheckTest.java +++ b/src/test/java/course_project/ModeCheckTest.java @@ -2,6 +2,7 @@ import course_project.engine.Input; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; public class ModeCheckTest { diff --git a/src/test/java/course_project/ShipPositioningCheckerTest.java b/src/test/java/course_project/ShipPositioningCheckerTest.java index 87c884bb..658d1029 100644 --- a/src/test/java/course_project/ShipPositioningCheckerTest.java +++ b/src/test/java/course_project/ShipPositioningCheckerTest.java @@ -1,8 +1,10 @@ package course_project; + import course_project.models.Board; import course_project.models.Coordinate; import course_project.engine.PositionChecker; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; public class ShipPositioningCheckerTest { @@ -18,7 +20,7 @@ void test_EnoughPlace_VerticalA1() { c = new Coordinate("a1"); size = 4; mode = "v"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -26,7 +28,7 @@ void test_EnoughPlace_Horizontal_A1() { c = new Coordinate("a1"); size = 4; mode = "h"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -34,7 +36,7 @@ void test_EnoughPlace_Vertical_J1() { c = new Coordinate("j1"); size = 4; mode = "v"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -42,7 +44,7 @@ void test_EnoughPlace_Vertical_A6() { c = new Coordinate("a6"); size = 4; mode = "v"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -50,7 +52,7 @@ void test_EnoughPlace_Horizontal_A6() { c = new Coordinate("a6"); size = 4; mode = "h"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -58,7 +60,7 @@ void test_EnoughPlace_Horizontal_A10() { c = new Coordinate("a8"); size = 4; mode = "h"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -66,7 +68,7 @@ void test_NotEnoughPlace_Vertical_A8() { c = new Coordinate("a8"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -74,7 +76,7 @@ void test_NotEnoughPlace_HorizontalJ1() { c = new Coordinate("j1"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -82,7 +84,7 @@ void test_NotEnoughPlace_HorizontalJ8() { c = new Coordinate("j8"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -91,7 +93,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalD1() { c = new Coordinate("d1"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -100,7 +102,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalE1() { c = new Coordinate("e1"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -109,7 +111,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalF1() { c = new Coordinate("f1"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -118,7 +120,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalD5() { c = new Coordinate("d5"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -127,7 +129,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalE5() { c = new Coordinate("e5"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -136,7 +138,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalF5() { c = new Coordinate("f5"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -145,7 +147,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalD6() { c = new Coordinate("d6"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -154,7 +156,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalE6() { c = new Coordinate("e6"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -163,7 +165,7 @@ void test_ObstacleE5NotEnoughPlace_VerticalF6() { c = new Coordinate("f6"); size = 4; mode = "v"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -172,7 +174,7 @@ void test_ObstacleE5NotEnoughPlace_HorizontalA4() { c = new Coordinate("a4"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -181,7 +183,7 @@ void test_ObstacleE5NotEnoughPlace_HorizontalA5() { c = new Coordinate("a5"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -190,7 +192,7 @@ void test_ObstacleE5NotEnoughPlace_HorizontalA6() { c = new Coordinate("a6"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -199,7 +201,7 @@ void test_ObstacleE5NotEnoughPlace_HorizontalF4() { c = new Coordinate("f4"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -208,7 +210,7 @@ void test_ObstacleE5NotEnoughPlace_HorizontalF5() { c = new Coordinate("f5"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -217,7 +219,7 @@ void test_ObstacleE5NotEnoughPlace_HorizontalF6() { c = new Coordinate("f6"); size = 4; mode = "h"; - assertFalse(PositionChecker.possibleToPlace(b,c,size,mode)); + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -226,7 +228,7 @@ void test_ObstacleE5EnoughPlace_HorizontalC3() { c = new Coordinate("c3"); size = 4; mode = "h"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -235,7 +237,7 @@ void test_ObstacleE5EnoughPlace_HorizontalD7() { c = new Coordinate("d7"); size = 4; mode = "h"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -244,7 +246,7 @@ void test_ObstacleE5EnoughPlace_HorizontalG4() { c = new Coordinate("g4"); size = 4; mode = "h"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -253,7 +255,7 @@ void test_ObstacleE5EnoughPlace_VerticalC1() { c = new Coordinate("c1"); size = 4; mode = "v"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -262,7 +264,7 @@ void test_ObstacleE5EnoughPlace_VerticalG1() { c = new Coordinate("g1"); size = 4; mode = "v"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } @Test @@ -271,7 +273,7 @@ void test_ObstacleE5EnoughPlace_VerticalD7() { c = new Coordinate("g1"); size = 4; mode = "v"; - assertTrue(PositionChecker.possibleToPlace(b,c,size,mode)); + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); } } From c9ce529182e7011d658032283b9e79f6d9fea576 Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 20 Sep 2021 00:22:17 +0300 Subject: [PATCH 37/44] removed commented part of Battle --- src/main/java/course_project/Battle.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/course_project/Battle.java b/src/main/java/course_project/Battle.java index 16b31572..c2c60f1a 100644 --- a/src/main/java/course_project/Battle.java +++ b/src/main/java/course_project/Battle.java @@ -34,14 +34,14 @@ public static void run() throws IOException { for (int i = 0; i < 2; i++) { ShipPlacer.placement(new Ship("Cruiser", 3), currentPlayer); } -// System.out.println("Now place 3 Destroyers of size 2"); -// for (int i = 0; i < 3; i++) { -// ShipPlacer.placement(new Ship("Destroyer", 2), currentPlayer); -// } -// System.out.println("And finally place 4 Scout ships of size 1"); -// for (int i = 0; i < 4; i++) { -// ShipPlacer.placement(new Ship("Scout", 1), currentPlayer); -// } + System.out.println("Now place 3 Destroyers of size 2"); + for (int i = 0; i < 3; i++) { + ShipPlacer.placement(new Ship("Destroyer", 2), currentPlayer); + } + System.out.println("And finally place 4 Scout ships of size 1"); + for (int i = 0; i < 4; i++) { + ShipPlacer.placement(new Ship("Scout", 1), currentPlayer); + } } From a5b4ccf515ea439b8e7b5bc592c1eb46aad89b64 Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 20 Sep 2021 23:07:30 +0300 Subject: [PATCH 38/44] HW 4 updated, remade Java 11 based solutions --- .../custom_file_reader/CustomFileReader.java | 21 ++++++++++++------- .../homework_4/custom_file_reader/Main.java | 2 +- 2 files changed, 14 insertions(+), 9 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 7b4a0243..ebd5342b 100644 --- a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -4,14 +4,23 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; public class CustomFileReader { private static final String FILE_PATH = "src/main/resources/custom_file_reader/file.txt"; public static void run1() throws IOException { - String content = Files.readString(Path.of(FILE_PATH)); - printWithoutDotAndComma(content); + StringBuilder content = new StringBuilder(); + FileInputStream fileInputStream = new FileInputStream(FILE_PATH); + int i; + while ((i = fileInputStream.read()) != -1) { + content.append((char) i); + } ; + printWithoutDotAndComma(content.toString()); } @@ -25,12 +34,8 @@ public static void run2() throws IOException { } public static void run3() throws IOException { - FileReader fileReader = new FileReader(FILE_PATH, StandardCharsets.UTF_8); - int i; - while ((i = fileReader.read()) != -1) { - printWithoutDotAndComma((char) i); - } - fileReader.close(); + String content = Files.lines(Paths.get(FILE_PATH), StandardCharsets.UTF_8).reduce((s, s2) -> s + "\n" + s2).orElse(""); + printWithoutDotAndComma(content); } public static void printWithoutDotAndComma(String s) { diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java index 1a9a16bd..87d2a24b 100644 --- a/src/main/java/homework_4/custom_file_reader/Main.java +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -10,7 +10,7 @@ public class Main { public static void main(String[] args) throws IOException { CustomFileReader.run1(); - CustomFileReader.run2(); +// CustomFileReader.run2(); CustomFileReader.run3(); } From 6ca1c87e33e7a40d79fdbdebd2b9e7bb3940668b Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 20 Sep 2021 23:19:57 +0300 Subject: [PATCH 39/44] Hw 5 added examples and description for CustomRegexMatcher --- .../homework_5/custom_regex_matcher/CustomRegexMatcher.java | 2 ++ 1 file changed, 2 insertions(+) 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 8fdd4871..90549c11 100644 --- a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -7,6 +7,8 @@ public class CustomRegexMatcher { final private static String REGEX = "^\\w*@\\w*\\.\\w*"; + // that regex Matches only email-like strings, starting from the beginning of the line + //for example "Allzza4279@gmail.com" or "regex@lul.notmail1", but not " dimatroshkin@mail.ru" public static void run() { try { From 629406f8c526fbf2c9433af3bc51c416c50380dc Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 20 Sep 2021 23:24:27 +0300 Subject: [PATCH 40/44] Hw 5 added examples and description for CustomRegexMatcher --- .../homework_5/custom_regex_matcher/CustomRegexMatcher.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java index 90549c11..d39433d6 100644 --- a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -6,9 +6,9 @@ import java.util.regex.Pattern; public class CustomRegexMatcher { - final private static String REGEX = "^\\w*@\\w*\\.\\w*"; - // that regex Matches only email-like strings, starting from the beginning of the line - //for example "Allzza4279@gmail.com" or "regex@lul.notmail1", but not " dimatroshkin@mail.ru" + final private static String REGEX = "\\w*@\\w*\\.\\w*"; + // that regex Matches only email-like strings + //for example "Allzza4279@gmail.com" or "regex@lul.notmail1", " dimatroshkin@mail.ru" public static void run() { try { From 104f822576f5fd339135f7a14e7772e6d7fde36e Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 20 Sep 2021 23:28:26 +0300 Subject: [PATCH 41/44] removed unnecessary variable --- src/main/java/homework_5/power_of_number/PowerOfNumber.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java index 56f70020..c996cbf7 100644 --- a/src/main/java/homework_5/power_of_number/PowerOfNumber.java +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -41,12 +41,10 @@ public static int[] getNumbers() throws Throwable { } public static int power(int a, int b) { - int result = 1; if (b == 0){ - return result; + return 1; } - result = a * power(a, b - 1); - return result; + return a * power(a, b - 1); } } From ae464c65ddc1c6bd91866724837eea62afe0fd40 Mon Sep 17 00:00:00 2001 From: Allzza Date: Mon, 20 Sep 2021 23:48:14 +0300 Subject: [PATCH 42/44] Fixed ImmutableClassTerminator. Now it`s truly immutable --- .../java/homework_3/ImmutableClassTerminator.java | 13 +++++++++++-- src/main/java/homework_3/Main.java | 14 +++++++++----- src/main/java/homework_7/KittenToCatFunction.java | 4 ++-- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/main/java/homework_3/ImmutableClassTerminator.java b/src/main/java/homework_3/ImmutableClassTerminator.java index 64c0f90b..99c4b4a9 100644 --- a/src/main/java/homework_3/ImmutableClassTerminator.java +++ b/src/main/java/homework_3/ImmutableClassTerminator.java @@ -22,13 +22,13 @@ public final class ImmutableClassTerminator { public ImmutableClassTerminator(int departureYear, String model, Date timeTravelDate) { this.departureYear = departureYear; this.model = model; - this.timeTravelDate = timeTravelDate; + this.timeTravelDate = new Date(timeTravelDate.getTime()); } public ImmutableClassTerminator(int departureYear, Date timeTravelDate) { this.departureYear = departureYear; this.model = "T100"; - this.timeTravelDate = timeTravelDate; + this.timeTravelDate = new Date(timeTravelDate.getTime()); } public ImmutableClassTerminator(int departureYear, String model) { @@ -52,4 +52,13 @@ public Date getTimeTravelDate() { public ImmutableClassTerminator changeTimeTravelDate(Date newTimeTravelDate) { return new ImmutableClassTerminator(departureYear, model, newTimeTravelDate); } + + @Override + public String toString() { + return "ImmutableClassTerminator{" + + "departureYear=" + departureYear + + ", model='" + model + '\'' + + ", timeTravelDate=" + timeTravelDate + + '}'; + } } diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java index 058176b1..4647a60d 100644 --- a/src/main/java/homework_3/Main.java +++ b/src/main/java/homework_3/Main.java @@ -5,13 +5,8 @@ public class Main { public static void main(String[] args) { ImmutableClassTerminator terminator = new ImmutableClassTerminator(2077, "T100"); - int year = terminator.getDepartureYear(); - String model = terminator.getModel(); Date date = terminator.getTimeTravelDate(); - System.out.println(year); - System.out.println(model); - System.out.println(date); date.setTime(0); System.out.println(date); @@ -20,5 +15,14 @@ public static void main(String[] args) { ImmutableClassTerminator newTerminator = terminator.changeTimeTravelDate(new Date(1212121212121L)); Date newDate = newTerminator.getTimeTravelDate(); System.out.println(newDate); + + final Date date1 = new Date(); + final ImmutableClassTerminator t100 = new ImmutableClassTerminator(2077, "T100", date1); + System.out.println(t100); + date1.setTime(111111111111L); + System.out.println(t100); + + t100.getTimeTravelDate().setTime(111111111111L); + System.out.println(t100); } } diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java index 7ff36d0e..9b34aeb1 100644 --- a/src/main/java/homework_7/KittenToCatFunction.java +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -1,6 +1,6 @@ package homework_7; @FunctionalInterface -public interface KittenToCatFunction { - Cat grow(Kitten kitten); +public interface KittenToCatFunction { + Cat grow(K k); } From 4811bf66d579a5794f134fbb97ad3c3c96c45de4 Mon Sep 17 00:00:00 2001 From: Allzza Date: Wed, 22 Sep 2021 16:02:49 +0300 Subject: [PATCH 43/44] hw 6 --- src/main/java/homework_6/Main.java | 16 ++++++++ .../MapProblemsCollisionGenerator.java | 12 ++++++ .../MapProblemsMutableGenerator.java | 39 +++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 src/main/java/homework_6/Main.java create mode 100644 src/main/java/homework_6/MapProblemsCollisionGenerator.java create mode 100644 src/main/java/homework_6/MapProblemsMutableGenerator.java diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..81de344f --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,16 @@ +package homework_6; + +import java.util.HashMap; + +public class Main { + public static void main(String[] args) { + HashMap map = new HashMap(); + MapProblemsMutableGenerator mutableProblemGenerator = new MapProblemsMutableGenerator(0); + + map.put(mutableProblemGenerator, "Some very important information"); + System.out.println(map.get(mutableProblemGenerator)); + mutableProblemGenerator.setSomeNumber(2); + System.out.println(map.get(mutableProblemGenerator)); //got some problem + + } +} diff --git a/src/main/java/homework_6/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..d4608e7e --- /dev/null +++ b/src/main/java/homework_6/MapProblemsCollisionGenerator.java @@ -0,0 +1,12 @@ +package homework_6; + +import java.util.Objects; + +public class MapProblemsCollisionGenerator { + + @Override + public int hashCode() { + return 0; + } +} + diff --git a/src/main/java/homework_6/MapProblemsMutableGenerator.java b/src/main/java/homework_6/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..045c543a --- /dev/null +++ b/src/main/java/homework_6/MapProblemsMutableGenerator.java @@ -0,0 +1,39 @@ +package homework_6; + +import java.util.Objects; + +public class MapProblemsMutableGenerator extends MapProblemsCollisionGenerator{ + private int someNumber; + + public MapProblemsMutableGenerator(int someNumber) { + this.someNumber = someNumber; + } + + public int getSomeNumber() { + return someNumber; + } + + public void setSomeNumber(int someNumber) { + this.someNumber = someNumber; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MapProblemsMutableGenerator)) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return getSomeNumber() == that.getSomeNumber(); + } + + @Override + public int hashCode() { + return Objects.hash(getSomeNumber()); + } + + @Override + public String toString() { + return "MapProblemsMutableGenerator{" + + "someNumber=" + someNumber + + '}'; + } +} From db302d76777065926df7b3b6ad5a9c2f7361a0e9 Mon Sep 17 00:00:00 2001 From: Allzza Date: Wed, 22 Sep 2021 16:10:10 +0300 Subject: [PATCH 44/44] hw 6 readme modified --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 54907e64..e078da7e 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ | | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/singleton/)| An example of singleton class | | HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/custom_regex_matcher/)| An app which takes String from terminal and checks whether given String matches hardcoded regex| | | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/power_of_number/)| An app which calculates a^b for two non-negative integers a and b | +| HW6 | [MapPloblemGenerators](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_6/)| The realisation of two classes which generate problems using hashmap| | HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_7/)| The realisation of @FunctionalInterface KittenToCatFunction with abstract method grow(). From now on we know how does kitten become a cat!| | HW7 | [SeaBattle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/course_project/)| The Sea Battle game 1 by 1 (No AI) | [Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)