diff --git a/README.md b/README.md index 5d686e9f..04fd4c1f 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,24 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Vaschenko Dmitriy* | 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 | +| Course project|[Sea battle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/course_project)| Sea battle realisation, fight VS computer +| HW 1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/DmitriyVaschenko/src/main/java/homework_1/ConsolePrinter.java) | The app that reads input arguments and prints them, until "error" argument | +| HW 2_1 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_2/traffic_light) | Traffic Light app, the simple one. | +| HW 2_2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_2/pyramid_printer) | The Pyramid printer, prints triangles only, btw. | +| HW 2_3| [RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_2/random_chars_table) | Random chars table, prints table with chars and then sorts them by even or odd. +| HW 3, Immutable Class Example| [ImutableClassExample](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_3) | Immutable class. +| HW 4_1| [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_4/custom_annotation)| Annotation for JSON Serialization +| HW 4_2| [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_4/custom_file_reader) | File Reader which removes all full stops and comas from TXT file +| HW 4_3| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_4/singleton)| Three singleton classes +| HW 5_1| [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_5/custom_regex_matcher)| App is checking if input matches moderate password +| HW 5_2| [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_5/power_of_number)|Recursively counts given degree of a given number +| HW 6 |[Map problems](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_6)| Map collision generation and Map with mutable key +| HW 7 |[Kitten to Cat function](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/main/java/homework_7)| Functional interface to map kittens into cats +| Tests|[Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DmitriyVaschenko/src/test/java/homework) | Tests for homework -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to CodingBat](https://codingbat.com/done?user=dvaschenko33@gmail.com&tag=4651459890) + +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/build.gradle b/build.gradle index b91dc843..e52c8a03 100644 --- a/build.gradle +++ b/build.gradle @@ -10,8 +10,8 @@ repositories { } dependencies { - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.0' } test { diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 index 4f906e0c..744e882e --- a/gradlew +++ b/gradlew @@ -72,7 +72,7 @@ case "`uname`" in Darwin* ) darwin=true ;; - MINGW* ) + MSYS* | MINGW* ) msys=true ;; NONSTOP* ) diff --git a/gradlew.bat b/gradlew.bat index 107acd32..ac1b06f9 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,89 +1,89 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle index 61b34d09..f53a86ae 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,3 @@ rootProject.name = 'Java Core June 2021' +include 'test' diff --git a/src/main/java/ConsoleColors/ConsoleColors.java b/src/main/java/ConsoleColors/ConsoleColors.java new file mode 100644 index 00000000..8d3d27de --- /dev/null +++ b/src/main/java/ConsoleColors/ConsoleColors.java @@ -0,0 +1,11 @@ +package ConsoleColors; + +public final class ConsoleColors{ + + public static final String RESET = "\033[0m"; + public static final String RED = "\033[0;31m"; + public static final String GREEN = "\033[0;32m"; + public static final String YELLOW = "\033[0;33m"; + + } + diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..f92d5edf --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,12 @@ +package course_project; + +import course_project.Utils.ConsoleHandling.Printer; +import course_project.components.Field; + +public class Main { + public static void main(String[] args) { + + new SeaBattle().play(); + + } +} diff --git a/src/main/java/course_project/SeaBattle.java b/src/main/java/course_project/SeaBattle.java new file mode 100644 index 00000000..373ad9df --- /dev/null +++ b/src/main/java/course_project/SeaBattle.java @@ -0,0 +1,188 @@ +package course_project; + +import course_project.Utils.ConsoleHandling.InReader; +import course_project.Utils.ConsoleHandling.Printer; +import course_project.Utils.ShipPlacers.ComputerShipPlacer; +import course_project.Utils.ShipPlacers.PlayerShipPlacer; +import course_project.components.Coordinates; +import course_project.components.Field; +import course_project.components.Ship; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class SeaBattle { + final Printer printer = new Printer(); + private final Random random = new Random(); + private final ComputerShipPlacer cPlacer = new ComputerShipPlacer(); + private final PlayerShipPlacer plPlacer = new PlayerShipPlacer(); + private Field playerField = new Field(); + private Field computerField = new Field(); + private List playerShips; + private List compShips; + private List playersShipsCoordinates; + private List computerShipsCoordinates; + private final InReader reader = new InReader(); + private final List allCompShoots = new ArrayList<>(); + + public void play() { + printer.printGreeting(); + + start(); + while (!shipsDestroyed(playerShips, compShips)) { + makeMoves(); + } + + printer.printAskContinue(); + boolean exitGame = reader.getMode(); + if (exitGame) { + printer.printGoodbye(); + } + else { + cPlacer.cleanField(); + plPlacer.cleanField(); + new SeaBattle().play(); + } + } + + public void start() { + printer.printAskHowFill(); + boolean auto = reader.getMode(); + if (!auto) { + playerField = plPlacer.placeShips(reader); + } else { + playerField = plPlacer.placeShips(); //this line does place Ships with ComputerShipPlacer automatically + } + + computerField = cPlacer.placeShips(); + + //Coordinates and ships fields initialization after placing + playerShips = plPlacer.getAllShips(); + compShips = cPlacer.getAllShips(); + playersShipsCoordinates = plPlacer.getAllShipsCoordinates(); + computerShipsCoordinates = cPlacer.getAllShipsCoordinates(); + + System.out.println("Here is yours Playing field :"); + printer.printOpenField(playerField); + System.out.println("And here is yours opponent Playing field :"); + printer.printHiddenField(computerField); + printer.printSep(); + printer.printSep(); + printer.printSep(); + waitASecond(); + } + + private void makeMoves( + ) { + playerMove(computerField, computerShipsCoordinates); + computerMove(playerField, playersShipsCoordinates); + } + + public void playerMove(Field computerField, List computerShipsCoordinates) { + + printer.playerMoves(); + System.out.println("And here is yours opponent Playing field :"); + printer.printHiddenField(computerField); + + printer.askWhereToShoot(); + Coordinates playerShoot = reader.readCoordinates(); + if (computerShipsCoordinates.contains(playerShoot)) { + computerField.placeHit(playerShoot); + for (Ship compShip : compShips + ) { + if (compShip.getCoordinates().contains(playerShoot)) { + compShip.gotShot(); + printer.printYouHit(); + } + } + dealWithShips(compShips); + playerMove(computerField, computerShipsCoordinates); //one more turn after hit + } else { + computerField.placeMiss(playerShoot); + printer.printYouMiss(); + printer.printSep(); + } + + } + + private void computerMove(Field playerField, List playersShipsCoordinates) { + printer.compMoves(); + waitASecond(); + System.out.println("Here is yours Playing field :"); + printer.printOpenField(playerField); + + Coordinates compShoot = getCompShot(); + + if (!allCompShoots.contains(compShoot)) { //not to shot same coordinate again + allCompShoots.add(compShoot); + } else { + compShoot = getCompShot(); + } + printer.printShoot(); + System.out.println((char) (compShoot.getX() + 65) + "" + (compShoot.getY() + 1)); + if (playersShipsCoordinates.contains(compShoot)) { + + playerField.placeHit(compShoot); + for (Ship plShip : playerShips + ) { + if (plShip.getCoordinates().contains(compShoot)) { + plShip.gotShot(); + printer.printYouWasHit(); + waitASecond(); + + } + } + dealWithShips(playerShips); + waitASecond(); + computerMove(playerField, playersShipsCoordinates); //one more turn after hit + } else { + playerField.placeMiss(compShoot); + printer.printPCMiss(); + printer.printSep(); + waitASecond(); + } + } + + private void waitASecond() { + try { + Thread.sleep(1500); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private void dealWithShips(List ships) { + Ship destroyed = null; + for (Ship ship : ships + ) { + if (!ship.isAlive()) { + destroyed = ship; + } + } + if (destroyed != null) { + printer.printDestroyed(destroyed); + ships.remove(destroyed); + } + + } + + private boolean shipsDestroyed(List playerShips, List compShips) { + if (playerShips.isEmpty()) { + printer.printLose(); + return true; + } + if (compShips.isEmpty()) { + printer.printWin(); + return true; + } + return false; + } + + private Coordinates getCompShot() { + int x = random.nextInt(10); + int y = random.nextInt(10); + return new Coordinates(x, y); + } + +} diff --git a/src/main/java/course_project/Utils/ConsoleHandling/InReader.java b/src/main/java/course_project/Utils/ConsoleHandling/InReader.java new file mode 100644 index 00000000..965df2fb --- /dev/null +++ b/src/main/java/course_project/Utils/ConsoleHandling/InReader.java @@ -0,0 +1,99 @@ +package course_project.Utils.ConsoleHandling; + +import course_project.components.Coordinates; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +public class InReader { + Printer printer = new Printer(); + private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + + public Coordinates readCoordinates() { + Coordinates result; + String input = readInput(); + + if (StringIsFine(input)) { + int x; + int y; + int[] coord = parseToCoord(input); + x = coord[0]; + y = coord[1]; + result = new Coordinates(x, y); + return result; + } else { + printer.printInputError(); + } + return readCoordinates(); + } + + public List getCoordinatesByDestination(Coordinates start, int size, String destination) { + List result = new ArrayList<>(); + int startX = start.getX(); + int startY = start.getY(); + //destinations are inverted, only case names + for (int i = 0; i < size; i++) { + switch (destination) { + case "left": + result.add(new Coordinates(startX - i, startY)); + break; + case "right": + result.add(new Coordinates(startX + i, startY)); + break; + case "up": + result.add(new Coordinates(startX, startY - i)); + break; + case "down": + result.add(new Coordinates(startX, startY + i)); + break; + } + } + + return result; + } + + private int[] parseToCoord(String string) { + int[] result = new int[2]; + int first = string.toUpperCase(Locale.ROOT).charAt(0) - 65; + int second = Integer.parseInt(string.substring(1)) - 1; + result[0] = first; + result[1] = second; + + return result; + } + + + private String readInput() { + String input = ""; + { + try { + input = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return input; + } + + private boolean StringIsFine(String str) { + return str.matches("[a-jA-J]([1-9]|10)") && (str.length() == 2 || str.length() == 3); + } + + public String getDestination() { + String result = readInput().toLowerCase(Locale.ROOT).trim(); + if (!result.matches("up") && !result.matches("down") && !result.matches("right") && !result.matches("left")) { + System.out.println("Wrong destination input, try again!"); + result = getDestination(); + } + return result; + } + + public boolean getMode() { + String mode = readInput(); + return mode == null || mode.isEmpty(); + } +} diff --git a/src/main/java/course_project/Utils/ConsoleHandling/Printer.java b/src/main/java/course_project/Utils/ConsoleHandling/Printer.java new file mode 100644 index 00000000..9a09d1b3 --- /dev/null +++ b/src/main/java/course_project/Utils/ConsoleHandling/Printer.java @@ -0,0 +1,184 @@ +package course_project.Utils.ConsoleHandling; + +import ConsoleColors.ConsoleColors; +import course_project.components.Field; +import course_project.components.Ship; +import course_project.enums.ShipType; + +public class Printer { + + + public void printGreeting() { + String GREETING = "Welcome to Sea Battle, stranger!"; + System.out.println(GREETING); + } + + public void printAskHowFill() { + String ASK_HOW_TO_FILL = "How Would you like to place your ships? " + + "Please, enter \" anything \" to place them manually or just press enter to place them automatically \n" + + ConsoleColors.RED + "Bear in mind, that any input will be counted like manual mode!" + ConsoleColors.RESET; + System.out.println(ASK_HOW_TO_FILL); + } + + public void printHeader() { + String HEADER = " A B C D E F G H I J "; + + System.out.println(HEADER); + } + + public void printYouMiss() { + String YOU_MISS = "Oh no, you missed :("; + System.out.println(YOU_MISS); + } + + public void printPCMiss() { + String AI_MISSED = "Computer missed, thank goodness!"; + System.out.println(AI_MISSED); + } + + public void printYouHit() { + String YOU_HIT = "What a shoot, you hit it!"; + System.out.println(YOU_HIT); + } + + public void printYouWasHit() { + String YOU_WAS_HIT = "Uh, oh, your ship is falling apart!"; + System.out.println(YOU_WAS_HIT); + } + + public void printDestroyed(Ship ship) { + String DESTROYED = "Ship " + ship.getType() + " at " + ship.getCoordinates() + " is destroyed, did you see that explosion? Huge, ain't it?"; + System.out.println(DESTROYED); + } + + public void printWin() { + String WON = "Oh yes, you are a winner! Never doubt it."; + System.out.println(WON); + } + + public void printLose() { + String LOSE = "What a shame, you lose!"; + System.out.println(LOSE); + } + + public void printShoot() { + String SHOOT = "Piu piu piu"; + System.out.println(SHOOT); + } + + public void askShipHead() { + String ASK_PLACE_SHIP_HEAD = "Insert ship head coordinates, insert column and row, like A1 or c4"; + System.out.println(ASK_PLACE_SHIP_HEAD); + } + + public void printAskDestination() { + String ASK_DESTINATION = "Which side would you like a Ship to be turned? Enter \"up\" , \"down\", \"left\" or \"right\""; + System.out.println(ASK_DESTINATION); + } + + public void printAskContinue() { + String ASK_CONTINUE = "How about one more game?" + "Please, enter \" anything \" to play one more time or just press enter to exit \n" + + ConsoleColors.RED + "Bear in mind, that any input will be counted like continue mode!" + ConsoleColors.RESET; + System.out.println(ASK_CONTINUE); + } + + public void printGoodbye() { + String SAY_GOODBYE = "Thanks for a playing and have a nice day!"; + System.out.println(SAY_GOODBYE); + } + + public void printSep() { + String SEPARATOR = "---------------------------------"; + System.out.println(SEPARATOR); + } + + public void printInputError() { + String INPUT_ERROR_MESSAGE = "Something is wrong with input, try again"; + System.out.println(INPUT_ERROR_MESSAGE); + } + + public void printPlacing(ShipType type) { + String PLACING = "Now Placing : "; + System.out.println(PLACING + type.getType()); + } + + public void printPlaced(ShipType type) { + String PLACED = "Correctly placed : "; + System.out.println(PLACED + type.getType()); + } + + public void compMoves() { + String COMP_MOVES = "Now is a computer move: "; + System.out.println(COMP_MOVES); + } + + public void playerMoves() { + String PLAYER_MOVES = "Now is your move: "; + System.out.println(PLAYER_MOVES); + } + + public void askWhereToShoot() { + String ASK_WHERE_TO_SHOOT = "Insert shot coordinates, insert column and row, like A1 or c4"; + System.out.println(ASK_WHERE_TO_SHOOT); + } + + public void printOpenField(Field field) { + printHeader(); + int[][] rawMatrix = field.getField(); + int[][] toPrint = turnMatrix(rawMatrix); + + int rowNumber = 1; + for (int[] row : toPrint + ) { + if (rowNumber < 10) { + System.out.print(rowNumber + " "); + } else { + System.out.print(rowNumber + " "); + } + for (int i : row + ) { + if (i == 0) { + i += 126; + } + System.out.print(" " + (char) i + " "); + } + System.out.println(); + ++rowNumber; + } + } + + public void printHiddenField(Field field) { + printHeader(); + int[][] rawMatrix = field.getField(); + int[][] toPrint = turnMatrix(rawMatrix); + int rowNumber = 1; + for (int[] row : toPrint + ) { + if (rowNumber < 10) { + System.out.print(rowNumber + " "); + } else { + System.out.print(rowNumber + " "); + } + for (int i : row + ) { + if (i == 0 || i == '#') { + i = 126; + } + + System.out.print(" " + (char) i + " "); + } + System.out.println(); + ++rowNumber; + } + } + + private int[][] turnMatrix(int[][] rawMatrix) { + int[][] result = new int[10][10]; + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + result[i][j] = rawMatrix[j][i]; + } + } + return result; + } +} diff --git a/src/main/java/course_project/Utils/ShipPlacers/ComputerShipPlacer.java b/src/main/java/course_project/Utils/ShipPlacers/ComputerShipPlacer.java new file mode 100644 index 00000000..29b81290 --- /dev/null +++ b/src/main/java/course_project/Utils/ShipPlacers/ComputerShipPlacer.java @@ -0,0 +1,115 @@ +package course_project.Utils.ShipPlacers; + +import course_project.Utils.ConsoleHandling.InReader; +import course_project.components.Coordinates; +import course_project.components.Field; +import course_project.components.Ship; +import course_project.enums.ShipType; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class ComputerShipPlacer implements Placer { + private final Random random = new Random(); + private Field computerField = new Field(); + private final List allShipsCoordinates = new ArrayList<>(); + private final List notAllowed = new ArrayList<>(); + private List allShips = new ArrayList<>(10); + + public List getAllShipsCoordinates() { + return allShipsCoordinates; + } + + public List getAllShips() { + return allShips; + } + + private List createAllShips() { + + for (ShipType type : ShipType.values() + ) { + for (int i = 1; i <= type.getCount(); i++) { + List coordinates; + int size = type.getSize(); + do { + coordinates = new ArrayList<>(generateShipCoordinates(size)); + } while (!isValidCoordinatesOfList(allShipsCoordinates, notAllowed, coordinates)); + + Ship ship = new Ship(i, type, type.getSize(), coordinates); + + allShips.add(ship); + allShipsCoordinates.addAll(coordinates); + fillForbiddenCoordinates(coordinates, notAllowed); + } + } + return allShips; + } + + @Override + public Field placeShips() { + allShips = createAllShips(); + for (Ship ship : allShips + ) { + computerField.placeShip(ship); + } + + return computerField; + } + + @Override + public Field placeShips(InReader reader) { + throw new UnsupportedOperationException("Not supported for ComputerShipPlacer!"); + } + + + private ArrayList generateShipCoordinates(int size) { + ArrayList shipCoordinates = new ArrayList<>(); + Coordinates start = getFirstDeck(); + if (size == 1) { + shipCoordinates.add(start); + return shipCoordinates; + } else { + shipCoordinates = createRest(start, size); + } + return shipCoordinates; + + } + + private Coordinates getFirstDeck() { + Coordinates firstDeck; + do { + int x = random.nextInt(10); + int y = random.nextInt(10); + + firstDeck = new Coordinates(x, y); + } + while (!isValidCoordinatesOfPoint(allShipsCoordinates, notAllowed, firstDeck)); + return firstDeck; + } + + + private ArrayList createRest(Coordinates start, int size) { + ArrayList coordinatesList = new ArrayList<>(); + coordinatesList.add(start); + + if (random.nextBoolean()) { + for (int i = 1; i < size; i++) { + coordinatesList.add(new Coordinates(start.getX() + i, start.getY())); + } + } else for (int i = 1; i < size; i++) { + coordinatesList.add(new Coordinates(start.getX(), start.getY() + i)); + } + return coordinatesList; + } + + public Field cleanField() { + allShips.clear(); + allShipsCoordinates.clear(); + notAllowed.clear(); + computerField = new Field(); + return computerField; + } + +} + diff --git a/src/main/java/course_project/Utils/ShipPlacers/Placer.java b/src/main/java/course_project/Utils/ShipPlacers/Placer.java new file mode 100644 index 00000000..7188c545 --- /dev/null +++ b/src/main/java/course_project/Utils/ShipPlacers/Placer.java @@ -0,0 +1,64 @@ +package course_project.Utils.ShipPlacers; + +import course_project.Utils.ConsoleHandling.InReader; +import course_project.components.Coordinates; +import course_project.components.Field; + +import java.util.ArrayList; +import java.util.List; + +public interface Placer { + Field placeShips(); + + Field placeShips(InReader reader); + + default boolean isValidCoordinatesOfPoint(List listShips, List listAdjusted, Coordinates point) { + return !listShips.contains(point) && !listAdjusted.contains(point) && + (point.getY() >= 0 && point.getY() <= 9) && (point.getX() >= 0 && point.getX() <= 9); + } + + default boolean isValidCoordinatesOfList(List listShips, List listAdjusted, List coordinates) { + for (Coordinates point : coordinates + ) { + if (!isValidCoordinatesOfPoint(listShips, listAdjusted, point)) { + return false; + } + } + return true; + } + + default List fillForbiddenCoordinates(List shipCoordinates, List notAllowed) { + for (Coordinates coord : shipCoordinates + ) { + int x = coord.getX(); + int y = coord.getY(); + List rawNotAdd = new ArrayList<>(); + Coordinates c1 = new Coordinates(x + 1, y + 1); + rawNotAdd.add(c1); + Coordinates c2 = new Coordinates(x + 1, y); + rawNotAdd.add(c2); + Coordinates c3 = new Coordinates(x + 1, y - 1); + rawNotAdd.add(c3); + Coordinates c4 = new Coordinates(x, y + 1); + rawNotAdd.add(c4); + Coordinates c5 = new Coordinates(x, y - 1); + rawNotAdd.add(c5); + Coordinates c6 = new Coordinates(x - 1, y + 1); + rawNotAdd.add(c6); + Coordinates c7 = new Coordinates(x - 1, y); + rawNotAdd.add(c7); + Coordinates c8 = new Coordinates(x - 1, y - 1); + rawNotAdd.add(c8); + + for (Coordinates c : rawNotAdd + ) { + if (!notAllowed.contains(c)) { + notAllowed.add(c); + } + } + } + return notAllowed; + } + + +} diff --git a/src/main/java/course_project/Utils/ShipPlacers/PlayerShipPlacer.java b/src/main/java/course_project/Utils/ShipPlacers/PlayerShipPlacer.java new file mode 100644 index 00000000..79712379 --- /dev/null +++ b/src/main/java/course_project/Utils/ShipPlacers/PlayerShipPlacer.java @@ -0,0 +1,130 @@ +package course_project.Utils.ShipPlacers; + + +import course_project.Utils.ConsoleHandling.InReader; +import course_project.Utils.ConsoleHandling.Printer; +import course_project.components.Coordinates; +import course_project.components.Field; +import course_project.components.Ship; +import course_project.enums.ShipType; + +import java.util.ArrayList; +import java.util.List; + +public class PlayerShipPlacer implements Placer { + + private final Printer printer = new Printer(); + private Field playerField = new Field(); + private List allShipsCoordinates = new ArrayList<>(); + private final List notAllowed = new ArrayList<>(); + private List playerShips = new ArrayList<>(10); + private ComputerShipPlacer computerShipPlacer = new ComputerShipPlacer(); + + public List getAllShipsCoordinates() { + return allShipsCoordinates; + } + + public List getAllShips() { + return playerShips; + } + + // field auto creating in the auto case, no reader send in method + @Override + public Field placeShips() { + playerField = computerShipPlacer.placeShips(); + playerShips = computerShipPlacer.getAllShips(); + allShipsCoordinates = computerShipPlacer.getAllShipsCoordinates(); + return playerField; + } + + @Override + public Field placeShips(InReader reader) { + return placeShipsManually(reader); + } + + + private Field placeShipsManually(InReader reader) { + Ship ship; + + for (ShipType type : ShipType.values() + ) { + for (int i = 1; i <= type.getCount(); i++) { + ship = createShip(type, reader); + playerShips.add(ship); + playerField.placeShip(ship); + printer.printOpenField(playerField); + printer.printSep(); + } + } + + + return playerField; + } + + private Ship createShip(ShipType type, InReader reader) { + Ship ship; + int size = type.getSize(); + + List coordinates; + printer.printPlacing(type); + coordinates = new ArrayList<>(getShipCoordinates(size, reader)); + ship = new Ship(type.getCount(), type, type.getSize(), coordinates); + printer.printPlaced(type); + allShipsCoordinates.addAll(coordinates); + fillForbiddenCoordinates(coordinates, notAllowed); + + return ship; + } + + private List getShipCoordinates(int size, InReader reader) { + List shipCoordinates = new ArrayList<>(); + + Coordinates firstDeck = getFirstDeck(reader); + if (size == 1) { + shipCoordinates.add(firstDeck); + return shipCoordinates; + } else { + shipCoordinates = createRest(firstDeck, size, reader); + } + return shipCoordinates; + + } + + private Coordinates getFirstDeck(InReader reader) { + + Coordinates firstDeck; + do { + printer.askShipHead(); + firstDeck = reader.readCoordinates(); + if (!isValidCoordinatesOfPoint(allShipsCoordinates, notAllowed, firstDeck)) { + printer.printInputError(); + printer.printSep(); + } + } + while (!isValidCoordinatesOfPoint(allShipsCoordinates, notAllowed, firstDeck)); + return firstDeck; + } + + private List createRest(Coordinates start, int size, InReader reader) { + printer.printAskDestination(); + String destination = reader.getDestination(); + List coordinatesList = new ArrayList<>(); + coordinatesList.add(start); + + coordinatesList = reader.getCoordinatesByDestination(start, size, destination); + + if (isValidCoordinatesOfList(allShipsCoordinates, notAllowed, coordinatesList)) { + return coordinatesList; + } + System.out.println("Can not fill the ship in there, try again!"); + return createRest(start, size, reader); + } + + public Field cleanField() { + playerShips.clear(); + allShipsCoordinates.clear(); + notAllowed.clear(); + playerField = new Field(); + return playerField; + } +} diff --git a/src/main/java/course_project/components/Coordinates.java b/src/main/java/course_project/components/Coordinates.java new file mode 100644 index 00000000..142e46c9 --- /dev/null +++ b/src/main/java/course_project/components/Coordinates.java @@ -0,0 +1,42 @@ +package course_project.components; + +public class Coordinates { + + private final int x; + private final int y; + + public Coordinates(int row, int column) { + this.x = row; + this.y = column; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + // For print A1 C7 etc. + @Override + public String toString() { + return "Coordinates{" + + "x=" + (char) (x + 65) + + ", y=" + (y + 1) + + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Coordinates that = (Coordinates) o; + return x == that.x && y == that.y; + } + + @Override + public int hashCode() { + return super.hashCode(); + } +} diff --git a/src/main/java/course_project/components/Field.java b/src/main/java/course_project/components/Field.java new file mode 100644 index 00000000..194d1553 --- /dev/null +++ b/src/main/java/course_project/components/Field.java @@ -0,0 +1,27 @@ +package course_project.components; + +import course_project.enums.State; + +public class Field { + final private int SIZE = 10; + private final int[][] field = new int[SIZE][SIZE]; + + public void placeShip(Ship ship) { + for (Coordinates point : ship.getCoordinates() + ) { + field[point.getX()][point.getY()] = State.DECK.getState(); + } + } + + public void placeMiss(Coordinates missCoordinate) { + field[missCoordinate.getX()][missCoordinate.getY()] = State.MISS.getState(); + } + + public void placeHit(Coordinates hitCoordinate) { + field[hitCoordinate.getX()][hitCoordinate.getY()] = State.HIT.getState(); + } + + public int[][] getField() { + return field; + } +} diff --git a/src/main/java/course_project/components/Ship.java b/src/main/java/course_project/components/Ship.java new file mode 100644 index 00000000..a524372c --- /dev/null +++ b/src/main/java/course_project/components/Ship.java @@ -0,0 +1,61 @@ +package course_project.components; + +import course_project.enums.ShipType; + +import java.util.ArrayList; +import java.util.List; + +public class Ship { + private final List coordinates; + private final int count; + private final ShipType type; + private final int size; + private int health; + private boolean alive = true; + + + public Ship(int count, ShipType type, int size, List coordinates) { + this.count = count; + this.type = type; + this.size = size; + this.health = size; + this.coordinates = new ArrayList<>(coordinates); + + } + + public List getCoordinates() { + return new ArrayList<>(coordinates); + } + + public void gotShot() { + health--; + if (health == 0) { + alive = false; + } + } + + @Override + public String toString() { + return "Ship{" + + "coordinates=" + coordinates + + ", count=" + count + + ", type=" + type + + ", size=" + size + + ", health=" + health + + ", alive=" + alive + + '}'; + } + + public ShipType getType() { + return type; + } + + public boolean isAlive() { + return alive; + } + + public void setHealth(int health) { + this.health = health; + } + +} diff --git a/src/main/java/course_project/enums/ShipType.java b/src/main/java/course_project/enums/ShipType.java new file mode 100644 index 00000000..27f86a09 --- /dev/null +++ b/src/main/java/course_project/enums/ShipType.java @@ -0,0 +1,31 @@ +package course_project.enums; + +public enum ShipType { + AIR_CARRIER(1, "Huge air-carrier", 4), + CRUISER(2, "Cruiser, big one", 3), + DESTROYER(3, "Destroyer, not a big one", 2), + TORPEDO0_BOAT(4, "Nothing but a small bot", 1); + + private final int count; + private final String type; + private final int size; + + ShipType(int count, String type, int size) { + this.count = count; + this.type = type; + this.size = size; + } + + public int getSize() { + return size; + } + + public int getCount() { + return count; + } + + public String getType() { + return type; + } + +} diff --git a/src/main/java/course_project/enums/State.java b/src/main/java/course_project/enums/State.java new file mode 100644 index 00000000..c5a2af3d --- /dev/null +++ b/src/main/java/course_project/enums/State.java @@ -0,0 +1,23 @@ +package course_project.enums; + +public enum State { + DECK('#'), + MISS('*'), + HIT('X'); + + private final char state; + + State(char state) { + this.state = state; + } + + public char getState() { + return state; + } + + @Override + public String toString() { + return String.valueOf(state); + } +} + diff --git a/src/main/java/homework_1/ConsolePrinter.java b/src/main/java/homework_1/ConsolePrinter.java new file mode 100644 index 00000000..b84f8fa5 --- /dev/null +++ b/src/main/java/homework_1/ConsolePrinter.java @@ -0,0 +1,22 @@ +package homework_1; + +import ConsoleColors.ConsoleColors; + +public class ConsolePrinter { + public static void main(String[] args) { + + if (args.length > 0) { + for (int i = 0; i < args.length; i++) { + + String toPrint = args[i]; + if (toPrint.equalsIgnoreCase("error")) { + System.out.println(ConsoleColors.RED + "Alarm!" + ConsoleColors.RESET); + break; + } + + System.out.println(toPrint + ": " + toPrint.length() + " letter(s)"); + } + } + } + +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java deleted file mode 100644 index 07c029a2..00000000 --- a/src/main/java/homework_1/Main.java +++ /dev/null @@ -1,9 +0,0 @@ -package homework_1; - -public class Main { - - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - -} 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 new file mode 100644 index 00000000..52fcef0d --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,54 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + private final String ERR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + String sizeOfPyramid = getInput(); + + if (isValid(sizeOfPyramid)) { + printPyramid(Integer.parseInt(sizeOfPyramid)); + } else { + System.out.println(ERR_MSG); + } + } + + private String getInput() { + String result = null; + System.out.println("Enter the Pyramid size. please: "); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + result = reader.readLine(); + } catch (IOException e) { + System.out.println(ERR_MSG); + } + return result; + } + + private void printPyramid(int i) { + for (int j = 0; j < i; j++) { + System.out.println(getRow(j)); + } + } + + private String getRow(int i) { + StringBuilder row = new StringBuilder(); + for (int j = 0; j <= i; j++) { + row.append('x'); + } + return row.toString(); + } + + private boolean isValid(String input) { + + if (input != null && input.chars().allMatch(Character::isDigit)){ + long intRes = Long.parseLong(input); + return intRes >= 0 && intRes < Integer.MAX_VALUE; + } + return false; + } +} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..0deac1b2 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,9 @@ +package homework_2.random_chars_table; + +import java.io.IOException; + +public class Main { + public static void main(String[] args) throws IOException { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..9b40317d --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,138 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Locale; + +public class RandomCharsTable { + private static final String ERR_MSG = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + public void run() { + + RandomCharsTable table = new RandomCharsTable(); + String lenStr, widStr, method; + + String[] strings = table.getInput(); + + if (isValid(strings)) { + + lenStr = strings[0]; + widStr = strings[1]; + method = strings[2].toLowerCase(Locale.ROOT); + + char[][] toPrint = table.getTable(lenStr, widStr); + if (toPrint.length <= 1) { + System.out.println(ERR_MSG); + return; + } + + System.out.println("There is an unsorted table:"); + + for (char[] ch : toPrint + ) { + for (char character : ch + ) { + System.out.print("|" + character); + } + System.out.print("|"); + System.out.println(); + } + table.printSorted(toPrint, method); + } else { + System.out.println(ERR_MSG); + } + } + + private String[] getInput() { + + String[] result = new String[3]; + + System.out.println("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + + String rawInput = reader.readLine(); + return rawInput.split(" "); + + } catch (IOException e) { + System.out.println(ERR_MSG); + } + return result; + } + + private boolean isValid(String[] strings) { + + boolean firstDigit = false; + boolean secondDigit = false; + boolean oddOrEven = false; + + if (strings.length < 3) { + return false; + } else if (strings.length == 3) { + if(strings[0].chars().allMatch(Character::isDigit)){ + long intResFirst = Long.parseLong(strings[0]); + firstDigit = intResFirst > 0 && intResFirst < Integer.MAX_VALUE; + } + if(strings[1].chars().allMatch(Character::isDigit)){ + long intResSecond = Long.parseLong(strings[0]); + secondDigit = intResSecond > 0 && intResSecond < Integer.MAX_VALUE; + } + oddOrEven = (strings[2].equals("odd") || strings[2].equals("even")); + } + return (firstDigit && secondDigit && oddOrEven); + } + + private char[][] getTable(String length, String width) { + + int len = Integer.parseInt(length); + int wid = Integer.parseInt(width); + char[][] res = new char[len][wid]; + + for (int i = 0; i < len; i++) { + for (int j = 0; j < wid; j++) { + res[i][j] = (char) ((Math.random() * (91 - 65) + 65)); + } + } + return res; + } + + private void printSorted(char[][] table, String method) { + + StringBuilder result = new StringBuilder(); + + switch (method) { + case ("odd"): + result.append("Odd letters - "); + for (char[] ch : table + ) + for (char c : ch + ) { + + if ((c % 2) != 0) { + result.append(c); + result.append(','); + } + } + String res = result.toString(); + System.out.println(res.substring(0, res.length() - 1) + "."); + break; + case ("even"): + result.append("Even letters - "); + for (char[] ch : table + ) + for (char c : ch + ) { + if ((c % 2) == 0) { + + result.append(c); + result.append(','); + } + } + String res1 = result.toString(); + System.out.println(res1.substring(0, res1.length() - 1) + "."); + break; + } + } +} diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..fa033081 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,7 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args) { + new TrafficLight().run(); + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..caefd4ad --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,64 @@ +package homework_2.traffic_light; + +import ConsoleColors.ConsoleColors; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + private final String ERR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + + System.out.println("Enter the number, please."); + String stringSeconds = getInput(); + if (isValid(stringSeconds)) { + int seconds = Integer.parseInt(stringSeconds); + getLight(seconds); + } + } + + private String getInput() { + String result = null; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + result = reader.readLine(); + } catch (IOException e) { + System.out.println(ERR_MSG); + } + return result; + } + + + private void getLight(int seconds) { + + if (seconds < 0) { + System.out.println(ERR_MSG); + } else if (seconds > 86399) { + System.out.println("The day is over"); + return; + } + + int justSeconds = seconds % 60; + + if (justSeconds < 35) { + System.out.println(ConsoleColors.GREEN + "GREEN" + ConsoleColors.RESET); + } else if ((justSeconds < 40) || (justSeconds >= 55)) { + System.out.println(ConsoleColors.YELLOW + "YELLOW" + ConsoleColors.RESET); + } else { + System.out.println(ConsoleColors.RED + "RED" + ConsoleColors.RESET); + } + + } + + private boolean isValid(String str) { + + if (str == null || !str.chars().allMatch(Character::isDigit)) { + System.out.println(ERR_MSG); + return false; + } + + return true; + } +} diff --git a/src/main/java/homework_3/ImmutableClassExample.java b/src/main/java/homework_3/ImmutableClassExample.java new file mode 100644 index 00000000..23b9285f --- /dev/null +++ b/src/main/java/homework_3/ImmutableClassExample.java @@ -0,0 +1,54 @@ +package homework_3; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +// 1) The class must be declared as final so it can’t be extended. +// 2) All fields have to be private so that direct access is not allowed. +// 3) Setter methods for variables must not be provided. +// 4) All mutable fields must be final so that its value can be assigned only once. +// 5) All the fields must be initialized via a constructor performing deep copy. +// 6) Cloning of objects in the getter methods should be used to return a copy rather than returning the actual object reference. + +public final class ImmutableClassExample { + private final int id; + private final String name; + private final HashMap testMap; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public HashMap getTestMap() { + return new HashMap<>(testMap); + } + + public ImmutableClassExample(int id, String name, HashMap testMap) { + this.id = id; + this.name = name; + this.testMap = new HashMap<>(testMap); + } + + public ImmutableClassExample(int id, String name){ + this.id = id; + this.name = name; + this.testMap = new HashMap<>(); + } + + public ImmutableClassExample(int id){ + this.id = id; + this.name = "some name"; + this.testMap = new HashMap<>(); + } + + public ImmutableClassExample(){ + this.id = -1; + this.name = "name"; + this.testMap = new HashMap<>(); + } +} diff --git a/src/main/java/homework_4/custom_annotation/Init.java b/src/main/java/homework_4/custom_annotation/Init.java new file mode 100644 index 00000000..1ae28e1b --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Init.java @@ -0,0 +1,9 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) + +public @interface Init { +} diff --git a/src/main/java/homework_4/custom_annotation/JsonElement.java b/src/main/java/homework_4/custom_annotation/JsonElement.java new file mode 100644 index 00000000..c5612895 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/JsonElement.java @@ -0,0 +1,9 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface JsonElement { + String key() default ""; +} diff --git a/src/main/java/homework_4/custom_annotation/JsonSerializable.java b/src/main/java/homework_4/custom_annotation/JsonSerializable.java new file mode 100644 index 00000000..58300247 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/JsonSerializable.java @@ -0,0 +1,9 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) + +public @interface JsonSerializable { +} diff --git a/src/main/java/homework_4/custom_annotation/JsonSerializationException.java b/src/main/java/homework_4/custom_annotation/JsonSerializationException.java new file mode 100644 index 00000000..61b2be3f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/JsonSerializationException.java @@ -0,0 +1,10 @@ +package homework_4.custom_annotation; + +public class JsonSerializationException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public JsonSerializationException(String message) { + super(message); + } +} diff --git a/src/main/java/homework_4/custom_annotation/ObjectToJsonConverter.java b/src/main/java/homework_4/custom_annotation/ObjectToJsonConverter.java new file mode 100644 index 00000000..4ba3f671 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/ObjectToJsonConverter.java @@ -0,0 +1,68 @@ +package homework_4.custom_annotation; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +public class ObjectToJsonConverter { + public String convertToJson(Object object) throws JsonSerializationException { + try { + + checkIfSerializable(object); + initializeObject(object); + return getJsonString(object); + + } catch (JsonSerializationException | IllegalAccessException | InvocationTargetException e) { + throw new JsonSerializationException(e.getMessage()); + } + } + + private void checkIfSerializable(Object object) { + if (Objects.isNull(object)) { + throw new JsonSerializationException("Can't serialize a null object"); + } + + Class clazz = object.getClass(); + if (!clazz.isAnnotationPresent(JsonSerializable.class)) { + throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable"); + } + } + + private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class clazz = object.getClass(); + for (Method method : clazz.getDeclaredMethods()) { + if (method.isAnnotationPresent(Init.class)) { + method.setAccessible(true); + method.invoke(object); + } + } + } + + private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException { + Class clazz = object.getClass(); + Map jsonElementsMap = new HashMap<>(); + for (Field field : clazz.getDeclaredFields()) { + field.setAccessible(true); + if (field.isAnnotationPresent(JsonElement.class)) { + jsonElementsMap.put(getKey(field), (String) field.get(object)); + } + } + + String jsonString = jsonElementsMap.entrySet() + .stream() + .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"") + .collect(Collectors.joining(",")); + return "{" + jsonString + "}"; + } + + private String getKey(Field field) { + String value = field.getAnnotation(JsonElement.class) + .key(); + return value.isEmpty() ? field.getName() : value; + } + +} \ No newline at end of file diff --git a/src/main/java/homework_4/custom_annotation/Person.java b/src/main/java/homework_4/custom_annotation/Person.java new file mode 100644 index 00000000..3fc2c248 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Person.java @@ -0,0 +1,66 @@ +package homework_4.custom_annotation; + +@JsonSerializable +public class Person { + @JsonElement + private String firstName; + @JsonElement + private String lastName; + @JsonElement(key = "personAge") + private String age; + + private String address; + + public Person(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Person(String firstName, String lastName, String age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + @Init + private void initNames() { + this.firstName = this.firstName.substring(0, 1) + .toUpperCase() + this.firstName.substring(1); + this.lastName = this.lastName.substring(0, 1) + .toUpperCase() + this.lastName.substring(1); + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAge() { + return age; + } + + public void setAge(String age) { + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + +} 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..7a9794d4 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,90 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class CustomFileReader { + private final String ERR_MSG = "File by the path doesn't exists!"; + private String content; + private File source; + private String filePath = "./src/main/resources/custom_file_reader/file.txt"; + + // Using InputStreams - binary stream + public void run1() { + if (fileExists(filePath)) { + + source = new File(filePath); + StringBuilder stringBuilder = new StringBuilder(); + try (FileInputStream fis = new FileInputStream(filePath)) { + int i; + while ((i = fis.read()) != -1) { + if (i <= 127) { + stringBuilder.append((char) i); + } + } + content = stringBuilder.toString(); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + System.out.println(ERR_MSG); + } + printResult(content); + } + + // Using Reader - character stream + public void run2() { + if (fileExists(filePath)) { + StringBuilder stringBuilder = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + while (reader.ready()) { + int read = reader.read(); + if (read >= 0 && read <= 127) { + stringBuilder.append((char) read); + } + } + content = stringBuilder.toString(); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + System.out.println(ERR_MSG); + } + printResult(content); + } + + // Using NIO, read bytes from path. + public void run3() { + if (fileExists(filePath)) { + Path path = Paths.get(filePath); + try { + byte[] characters = Files.readAllBytes(path); + StringBuilder stringBuilder = new StringBuilder(); + for (byte by : characters + ) { + if (by >= 0 && by <= 127) { + stringBuilder.append((char) by); + } + } + content = stringBuilder.toString(); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + System.out.println(ERR_MSG); + } + printResult(content); + } + + private boolean fileExists(String filePath) { + return new File(filePath).exists(); + } + + private void printResult(String content) { + System.out.println(content.replaceAll("(\\.)|(,)", "").trim()); + } + + +} 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..01087a42 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,9 @@ +package homework_4.custom_file_reader; + +public class Main { + public static void main(String[] args) { + new CustomFileReader().run1(); + new CustomFileReader().run2(); + new CustomFileReader().run3(); + } +} diff --git a/src/main/java/homework_4/singleton/EnumSingleton.java b/src/main/java/homework_4/singleton/EnumSingleton.java new file mode 100644 index 00000000..52194de3 --- /dev/null +++ b/src/main/java/homework_4/singleton/EnumSingleton.java @@ -0,0 +1,18 @@ +package homework_4.singleton; + +public enum EnumSingleton { + + //This approach has serialization and thread-safety guaranteed by the enum implementation itself, + // which ensures internally that only the single instance is available, + // correcting the problems pointed out in the class-based implementation. + + INSTANCE; + + EnumSingleton() { + } + + public static EnumSingleton getInstance() { + return INSTANCE; + } + +} diff --git a/src/main/java/homework_4/singleton/NaiveSingleton.java b/src/main/java/homework_4/singleton/NaiveSingleton.java new file mode 100644 index 00000000..232dd728 --- /dev/null +++ b/src/main/java/homework_4/singleton/NaiveSingleton.java @@ -0,0 +1,22 @@ +package homework_4.singleton; + +public final class NaiveSingleton { + + //A private constructor + //A static field containing its only instance + //A static factory method for obtaining the instance + //Note that it can be problematic in multithreading scenarios. + private static NaiveSingleton INSTANCE; + + private NaiveSingleton() { + } + + public static NaiveSingleton getInstance() { + if (INSTANCE == null) { + INSTANCE = new NaiveSingleton(); + } + + return INSTANCE; + } + +} 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..21d84934 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,17 @@ +package homework_4.singleton; + +public class Singleton { + + private static volatile Singleton INSTANCE; + private Singleton(){} + public static Singleton getInstance(){ + if (INSTANCE == null){ + synchronized (Singleton.class) { + if (INSTANCE == null){ + INSTANCE = new Singleton(); + } + } + } + return INSTANCE; + } +} 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..bca7f8b8 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,25 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +//Moderate password matcher +public class CustomRegexMatcher { + private final String regex = "(?=(.*[0-9]))((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.{8,}$"; + public void run(){ + System.out.println("Enter password-ish string, should have 1 lowercase letter, 1 uppercase letter, 1 number, and be at least 8 characters long"); + String input = getInput(); + System.out.println(input.matches(regex)); + } + + private String getInput() { + String result = "defaultString"; + try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){ + result = reader.readLine(); + } + catch (IOException e){ + e.printStackTrace(); + } + return result; + } +} 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..e1e20462 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,8 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..89300565 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,8 @@ +package homework_5.power_of_number; + +public class Main { + + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..3f0055e1 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,63 @@ +package homework_5.power_of_number; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.math.BigInteger; + +public class PowerOfNumber { + private final String ERR_MSG = "Only 2 non-negative integers are allowed"; + + public void run() { + System.out.println("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + String[] input = getInput(); + if (isValid(input)) { + BigInteger val = BigInteger.valueOf(Integer.parseInt(input[0])); + BigInteger pow = BigInteger.valueOf(Integer.parseInt(input[1])); + System.out.println(recPow(val, pow)); + } + } + + + private String[] getInput() { + String[] result = new String[2]; //only 2 arguments are allowed + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + try { + String rawInput = reader.readLine().trim(); + String[] toMeasure = rawInput.split("\\s"); + if (toMeasure.length != 2) { + System.out.println(ERR_MSG); + return result; + } else { + result = rawInput.split("\\s"); + } + + } catch (IOException e) { + System.out.println(ERR_MSG); + } + return result; + } + + private boolean isValid(String[] input) { + if (input[0] != null && input[1] != null) { + if (input[0].chars().allMatch(Character::isDigit) && + input[1].chars().allMatch(Character::isDigit)) { + return true; + } + System.out.println(ERR_MSG); + } + return false; + } + + public BigInteger recPow(BigInteger val, BigInteger pow) { + + if (pow.compareTo(BigInteger.valueOf(0)) == 0) { + return BigInteger.valueOf(1); + } + pow = pow.subtract(BigInteger.valueOf(1)); + val = val.multiply(recPow(val, pow)); //recursion + + return val; + } + +} diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..b6915509 --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,31 @@ +package homework_6; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + public static void main(String[] args) { + + HashMap mutableMap = new HashMap<>(); + + MapProblemsMutableGenerator first = new MapProblemsMutableGenerator(new StringBuilder("first")); + MapProblemsMutableGenerator second = new MapProblemsMutableGenerator(new StringBuilder("second")); + + mutableMap.put(first, 1); + mutableMap.put(second, 2); + + System.out.println("Before key mutation: "); + System.out.println("mutableMap.get(first) = " + mutableMap.get(first)); + System.out.println("mutableMap.get(second) = " + mutableMap.get(second)); + + + first.getMapKey().append("a"); + second.getMapKey().append("a"); + + System.out.println("After key mutation: "); + System.out.println("mutableMap.get(first) = " + mutableMap.get(first)); + System.out.println("mutableMap.get(second) = " + mutableMap.get(second)); + + } + +} diff --git a/src/main/java/homework_6/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..6ad9f1d8 --- /dev/null +++ b/src/main/java/homework_6/MapProblemsCollisionGenerator.java @@ -0,0 +1,32 @@ +package homework_6; + +import java.util.Objects; + +public class MapProblemsCollisionGenerator { + + private final String name; + + public MapProblemsCollisionGenerator(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsCollisionGenerator that = (MapProblemsCollisionGenerator) o; + return Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return 2; // collision generation + } + + @Override + public String toString() { + return "MapProblemsCollisionGenerator{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/src/main/java/homework_6/MapProblemsMutableGenerator.java b/src/main/java/homework_6/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..2f328318 --- /dev/null +++ b/src/main/java/homework_6/MapProblemsMutableGenerator.java @@ -0,0 +1,28 @@ +package homework_6; + +import java.util.Objects; + +public class MapProblemsMutableGenerator { + private StringBuilder mapKey; + + public MapProblemsMutableGenerator(StringBuilder mapKey) { + this.mapKey = mapKey; + } + + public StringBuilder getMapKey() { + return mapKey; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return mapKey.equals(that.mapKey); //suspicious it is, indeed + } + + @Override + public int hashCode() { + return mapKey.toString().hashCode(); + } +} diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..21c2ff34 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,35 @@ +package homework_7; + +public class Cat { + private String name; + private int age; + + public Cat(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..c9939f4e --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,34 @@ +package homework_7; + +public class Kitten { + private String name; + private int age = 0; + private double tailLength; + + public Kitten(String name, int age, double tailLength) { + this.name = name; + this.age = 0; // kittens are small + this.tailLength = tailLength; + } + + public String getName() { + return name; + } + + public int getAge() { + return 0; + } + + public double getTailLength() { + return tailLength; + } + + @Override + public String toString() { + return "Kitten{" + + "name='" + name + '\'' + + ", age=" + age + + ", tailLength=" + tailLength + + '}'; + } +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..74e872b9 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,5 @@ +package homework_7; + +public interface KittenToCatFunction { + Cat grow(Kitten kitten); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..65122b71 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,12 @@ +package homework_7; + +public class Main { + public static void main(String[] args) { + Kitten kitten = new Kitten("Pupa", 0, 2.5); + + KittenToCatFunction function = (k) -> new Cat(k.getName(), k.getAge() + 4); + Cat cat = function.grow(kitten); + System.out.println("kitten = " + kitten); + System.out.println("cat = " + cat); + } +} 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..775149f9 --- /dev/null +++ b/src/main/resources/custom_file_reader/file.txt @@ -0,0 +1,3 @@ +Simple text that contains comas - ,,, , dots - ... and some more punctuation marks like "" '' () ? ! : ;/ Comas and dots must be gone after run1() or run2() or run3(). + + diff --git a/src/test/java/homework/course_project/SeaBattleTest.java b/src/test/java/homework/course_project/SeaBattleTest.java new file mode 100644 index 00000000..5bb0982b --- /dev/null +++ b/src/test/java/homework/course_project/SeaBattleTest.java @@ -0,0 +1,4 @@ +package homework.course_project; + +public class SeaBattleTest { +} diff --git a/src/test/java/homework/course_project/component_tests/CoordinatesTest.java b/src/test/java/homework/course_project/component_tests/CoordinatesTest.java new file mode 100644 index 00000000..9752f07a --- /dev/null +++ b/src/test/java/homework/course_project/component_tests/CoordinatesTest.java @@ -0,0 +1,44 @@ +package homework.course_project.component_tests; +import course_project.components.Coordinates; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CoordinatesTest { + + + @Test + void givenTwoInts_whenCreateCoordinates_thenCreated(){ + int x = 1; + int y = 1; + + Coordinates coordinates = new Coordinates(x,y); + assertNotNull(coordinates); + } + + @Test + void givenTwoDifferentCoordinates_whenCompare_thenNotSame(){ + int x1 = 1; + int y1 = 1; + int x2 = 2; + int y2 = 2; + + Coordinates coordinatesFirst = new Coordinates(x1,y2); + Coordinates coordinatesSecond = new Coordinates(x2, y2); + + assertNotSame(coordinatesFirst, coordinatesSecond); + } + + @Test + void givenTwoSameCoordinates_whenCompare_thenSame(){ + int x1 = 1; + int y1 = 1; + int x2 = 1; + int y2 = 1; + + Coordinates coordinatesFirst = new Coordinates(x1,y2); + Coordinates coordinatesSecond = new Coordinates(x2, y2); + + assertEquals(coordinatesFirst, coordinatesSecond); + } +} diff --git a/src/test/java/homework/course_project/component_tests/FieldTest.java b/src/test/java/homework/course_project/component_tests/FieldTest.java new file mode 100644 index 00000000..28b43d3b --- /dev/null +++ b/src/test/java/homework/course_project/component_tests/FieldTest.java @@ -0,0 +1,106 @@ +package homework.course_project.component_tests; + +import course_project.components.Coordinates; +import course_project.components.Field; +import course_project.components.Ship; +import course_project.enums.ShipType; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class FieldTest { + final Field field = new Field(); + + + @Test + void givenFieldCreated_whenCheckCells_thenItIsEmpty(){ + for (int[] row: field.getField() + ) { + for (int i: row + ) { + assertEquals(0, i); + } + } + } + @Test + void givenShipPlaced_whenCheckCells_thenContainsDecks(){ + List shipCoords = new ArrayList<>(); + shipCoords.add(new Coordinates(1,1)); + shipCoords.add(new Coordinates(1,2)); + shipCoords.add(new Coordinates(1,3)); + shipCoords.add(new Coordinates(1,4)); + Ship ship = new Ship(1, ShipType.AIR_CARRIER, 4, shipCoords); + + field.placeShip(ship); + int countDecks = 0; + for (int[] row: field.getField() + ) { + for (int i: row + ) { + if (i == '#'){ + countDecks++; + } + } + } + assertEquals(4, countDecks); + } + + @Test + void givenHitPlaced_whenCheckCells_thenContainsDecks(){ + Coordinates hitCoordinates1 = new Coordinates(2,3); + Coordinates hitCoordinates2 = new Coordinates(1,3); + Coordinates hitCoordinates3 = new Coordinates(5,3); + Coordinates hitCoordinates4 = new Coordinates(2,5); + + field.placeHit(hitCoordinates1); + field.placeHit(hitCoordinates2); + field.placeHit(hitCoordinates3); + field.placeHit(hitCoordinates4); + + int countHits = 0; + for (int[] row: field.getField() + ) { + for (int i: row + ) { + if (i == 'X'){ + countHits++; + } + } + } + assertEquals(4, countHits); + } + @Test + void givenMissPlaced_whenCheckCells_thenContainsDecks(){ + Coordinates missCoordinates1 = new Coordinates(2,3); + Coordinates missCoordinates2 = new Coordinates(1,3); + Coordinates missCoordinates3 = new Coordinates(5,3); + Coordinates missCoordinates4 = new Coordinates(2,5); + + field.placeMiss(missCoordinates1); + field.placeMiss(missCoordinates2); + field.placeMiss(missCoordinates3); + field.placeMiss(missCoordinates4); + + int countMisses = 0; + for (int[] row: field.getField() + ) { + for (int i: row + ) { + if (i == '*'){ + countMisses++; + } + } + } + assertEquals(4, countMisses); + } + +} + + + + + + diff --git a/src/test/java/homework/course_project/component_tests/ShipTest.java b/src/test/java/homework/course_project/component_tests/ShipTest.java new file mode 100644 index 00000000..1d12fcc8 --- /dev/null +++ b/src/test/java/homework/course_project/component_tests/ShipTest.java @@ -0,0 +1,46 @@ +package homework.course_project.component_tests; + +import course_project.components.Coordinates; +import course_project.components.Ship; +import course_project.enums.ShipType; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +public class ShipTest { + + + @Test + void givenNewShip_whenCreate_thenItIsExist(){ + List shipCoords = new ArrayList<>(); + shipCoords.add(new Coordinates(1,1)); + shipCoords.add(new Coordinates(1,2)); + shipCoords.add(new Coordinates(1,3)); + shipCoords.add(new Coordinates(1,4)); + Ship ship = new Ship(1, ShipType.AIR_CARRIER, 4, shipCoords); + + assertNotNull(ship); + } + + @Test + void whenShipGetEnoughShots_thenItDies(){ + List shipCoords = new ArrayList<>(); + shipCoords.add(new Coordinates(1,1)); + shipCoords.add(new Coordinates(1,2)); + shipCoords.add(new Coordinates(1,3)); + + Ship ship = new Ship(1, ShipType.CRUISER, 3, shipCoords); + ship.gotShot(); + ship.gotShot(); + ship.gotShot(); + System.out.println(ship.isAlive()); + assertFalse(ship.isAlive()); + } + + + + +} diff --git a/src/test/java/homework/course_project/util_tests/console_handling_tests/InReaderTest.java b/src/test/java/homework/course_project/util_tests/console_handling_tests/InReaderTest.java new file mode 100644 index 00000000..afdeb2da --- /dev/null +++ b/src/test/java/homework/course_project/util_tests/console_handling_tests/InReaderTest.java @@ -0,0 +1,114 @@ +package homework.course_project.util_tests.console_handling_tests; + +import course_project.Utils.ConsoleHandling.InReader; +import course_project.components.Coordinates; +import homework.unit_base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + + +public class InReaderTest extends UnitBase { + final String ERR_MSG = "Something is wrong with input, try again"; + final String WRONG_DESTINATION = "Wrong destination input, try again!"; + @Test + void givenString_whenStringA1_thenCoordinateReturned() { + String input = "A1"; + Coordinates result; + setInput(input); + result = new InReader().readCoordinates(); + + assertNotNull(result); + } + + @Test + void givenBadString_whenStringSTR_thenErrorPrinted() { + String input = "String\n" + "a1"; + + setInput(input); + new InReader().readCoordinates(); //recursively called, need second argument in case of mistaken input + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + void givenNothing_whenStringIsEmpty_thenErrorPrinted() { + String input = "\n" + "a1"; + + setInput(input); + new InReader().readCoordinates(); //recursively called, need second argument in case of mistaken input + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + void givenArguments_whenGetCoordinatesByDestinationCalled_thenCoordinatesListReturned(){ + Coordinates start = new Coordinates(1,1); + int size = 4; + String destination = "right"; + + List expected = new ArrayList<>(); + expected.add(start); + Coordinates c1 = new Coordinates(2,1); + expected.add(c1); + Coordinates c2 = new Coordinates(3,1); + expected.add(c2); + Coordinates c3 = new Coordinates(4,1); + expected.add(c3); + + List result = new InReader().getCoordinatesByDestination(start, size, destination); + + assertEquals(expected, result); + } + + @Test + void givenBadString_whenGetDestinationCalled_thenErrorPrinted() { + String input = "String\n" + "left"; + + setInput(input); + new InReader().getDestination(); //recursively called, need second argument in case of mistaken input + + assertEquals(WRONG_DESTINATION, getOutputLines()[0]); + } + + @Test + void givenEmptyString_whenGetDestinationCalled_thenErrorPrinted() { + String input = "\n" + "left"; + + setInput(input); + new InReader().getDestination(); //recursively called, need second argument in case of mistaken input + + assertEquals(WRONG_DESTINATION, getOutputLines()[0]); + } + + @Test + void givenCorrectInput_whenGetDestinationCalled_thenStringReturned() { + String input = "LefT"; + String expected = "left"; + setInput(input); + String result = new InReader().getDestination(); + + assertEquals(expected, result); + } + + @Test + void givenSomeInput_whenGetModeCalled_thenFalseReturned() { + String input = "anything"; + setInput(input); + + assertFalse(new InReader().getMode()); + } + + @Test + void givenNoInput_whenGetModeCalled_thenTrueReturned() { + String input = ""; + setInput(input); + + assertTrue(new InReader().getMode()); + } + + +} diff --git a/src/test/java/homework/course_project/util_tests/console_handling_tests/PrinterTest.java b/src/test/java/homework/course_project/util_tests/console_handling_tests/PrinterTest.java new file mode 100644 index 00000000..b4d74170 --- /dev/null +++ b/src/test/java/homework/course_project/util_tests/console_handling_tests/PrinterTest.java @@ -0,0 +1,46 @@ +package homework.course_project.util_tests.console_handling_tests; +import course_project.Utils.ConsoleHandling.Printer; +import course_project.components.Field; +import homework.unit_base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +public class PrinterTest extends UnitBase{ + + @Test + void givenNewField_whenPrintAnyway_thenPrinted(){ + Field testFieldEmpty = new Field(); + String expected = " A B C D E F G H I J \n" + + "1 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "2 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "3 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "4 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "5 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "6 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "7 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "8 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ \n" + + "10 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~"; + new Printer().printOpenField(testFieldEmpty); + assertEquals(expected, " " + getOutput()); + + + + new Printer().printHiddenField(testFieldEmpty); + + + + + + + + + + + + } + +} diff --git a/src/test/java/homework/course_project/util_tests/placer_tests/ComputerShipPlacerTest.java b/src/test/java/homework/course_project/util_tests/placer_tests/ComputerShipPlacerTest.java new file mode 100644 index 00000000..195f14d1 --- /dev/null +++ b/src/test/java/homework/course_project/util_tests/placer_tests/ComputerShipPlacerTest.java @@ -0,0 +1,4 @@ +package homework.course_project.util_tests.placer_tests; + +public class ComputerShipPlacerTest { +} diff --git a/src/test/java/homework/course_project/util_tests/placer_tests/PlayerShipPlacerTest.java b/src/test/java/homework/course_project/util_tests/placer_tests/PlayerShipPlacerTest.java new file mode 100644 index 00000000..b438e03d --- /dev/null +++ b/src/test/java/homework/course_project/util_tests/placer_tests/PlayerShipPlacerTest.java @@ -0,0 +1,4 @@ +package homework.course_project.util_tests.placer_tests; + +public class PlayerShipPlacerTest { +} diff --git a/src/test/java/homework/homework_1/ConsolePrinterTest.java b/src/test/java/homework/homework_1/ConsolePrinterTest.java new file mode 100644 index 00000000..d7a8b7f4 --- /dev/null +++ b/src/test/java/homework/homework_1/ConsolePrinterTest.java @@ -0,0 +1,53 @@ +package homework.homework_1; + +import ConsoleColors.ConsoleColors; +import homework.unit_base.UnitBase; +import homework_1.ConsolePrinter; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class ConsolePrinterTest extends UnitBase { + + @Test + void givenNoArgs_whenRun_thenExitWOPrint() { + String[] args = new String[]{}; + ConsolePrinter.main(args); + assertEquals("", getOutputLines()[0]); + } + + @Test + void givenNullArg_whenRun_thenNPEThrown() { + String[] args = new String[]{null}; + assertThrows(NullPointerException.class, () -> { + ConsolePrinter.main(args); + }); + } + + @Test + void givenOne_NOT_ERROR_Line_whenRun_thenPrintsOneLine() { + String[] args = new String[]{"oneNotErrorLine"}; + ConsolePrinter.main(args); + String expected = args[0] + ": " + args[0].length() + " letter(s)" ; + assertEquals(expected, getOutputLines()[0]); + } + + @Test + void givenError_whenRun_thenRedAlarmPrinted() { + String[] args = new String[]{"error"}; + ConsolePrinter.main(args); + String expected = "[0;31mAlarm!"; + assertEquals(expected, getOutputLines()[0]); + } + + @Test + void givenThreeStringsAndError_whenRun_thenStringsPrintedAndRedAlarmPrinted() { + String[] args = new String[]{"first","second","third","error"}; + ConsolePrinter.main(args); + assertEquals(getOutputLines()[0], "first" + ": " + "first".length() + " letter(s)"); + assertEquals(getOutputLines()[1], "second" + ": " + "second".length() + " letter(s)"); + assertEquals(getOutputLines()[2], "third" + ": " + "third".length() + " letter(s)"); + assertTrue(getOutputLines()[3].contains("Alarm!")); + } + +} diff --git a/src/test/java/homework/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..54776ea2 --- /dev/null +++ b/src/test/java/homework/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,107 @@ +package homework.homework_2.pyramid_printer; + +import homework.unit_base.UnitBase; +import homework_2.pyramid_printer.PyramidPrinter; +import org.junit.jupiter.api.Test; + + +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterTest extends UnitBase { + + final String ERR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + + //tested cases correct input 3 + // zero input + // empty input + // string input + // input bigger INT_MAX.VALUE + // negative number + // more that one argument + // 8 double value + + @Test + void givenPositiveInt_whenRun_thenPrintPyramid() { + setInput("3"); + + new PyramidPrinter().run(); + removeFromOutput("Enter the Pyramid size. please: "); + printOut(); + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + + } + + @Test + void givenZero_whenRun_thenDoNothing() { + setInput("0"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Enter the Pyramid size. please: "); + assertEquals("", getOutputLines()[0]); + } + + @Test + void givenNothing_whenRun_thenWriteErrMsgAndStop() { + setInput(""); + + new PyramidPrinter().run(); + removeFromOutput("Enter the Pyramid size. please: "); + printOut(); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + void givenString_whenRun_thenWriteErrMsgAndStop() { + setInput("Some string"); + + new PyramidPrinter().run(); + removeFromOutput("Enter the Pyramid size. please: "); + printOut(); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + void givenToBigNumber_whenRun_thenWriteErrMsgAndStop() { + setInput("999999999999"); + + new PyramidPrinter().run(); + removeFromOutput("Enter the Pyramid size. please: "); + printOut(); + assertTrue(getOutput().contains(ERR_MSG)); + } + + @Test + void givenNegativeNumber_whenRun_thenWriteErrMsgAndStop() { + setInput("-1"); + + new PyramidPrinter().run(); + removeFromOutput("Enter the Pyramid size. please: "); + printOut(); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + void givenMoreThatOne_whenRun_thenWriteErrMsgAndStop() { + setInput("2 3"); + + new PyramidPrinter().run(); + removeFromOutput("Enter the Pyramid size. please: "); + printOut(); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + void givenNotAnInteger_whenRun_thenWriteErrMsgAndStop() { + setInput("0.6"); + + new PyramidPrinter().run(); + removeFromOutput("Enter the Pyramid size. please: "); + printOut(); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..370355bc --- /dev/null +++ b/src/test/java/homework/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,196 @@ +package homework.homework_2.random_chars_table; + +import homework.unit_base.UnitBase; +import homework_2.random_chars_table.RandomCharsTable; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class RandomCharsTableTest extends UnitBase { + final String ERR_MSG = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + // tested cases : correct odd + // correct even + // one arg + // two args + // three args, wrong method string + // empty input + // more than 3 args + // three args, wrong order + // 0 0 odd table + // 0 0 even table + // 0 1 even table + //12 1 0 even table + + + @Test + public void givenCorrectInputOddMethod_whenRun_thenAllGood() { + setInput("4 4 odd"); + boolean isOddInOutput; + boolean areCharsOdd = false; + String expected = "Odd letters - "; + + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + removeFromOutput("There is an unsorted table:"); + String[] inOutput = getOutputLines(); + + for (String str : inOutput + ) { + if (str.contains("|")) { + removeFromOutput(str); + } + } + + String[] rest = getOutputLines(); + String restedString = rest[0]; + String beginning = restedString.substring(0, 14); + isOddInOutput = expected.equals(beginning); + + String restedChars = restedString.substring(14); + restedChars.replaceAll("\\p{P}", ""); + char[] charsRest = restedChars.toCharArray(); + for (char ch : charsRest + ) { + areCharsOdd = (ch / 2) != 0; + } + assertTrue(isOddInOutput && areCharsOdd); + } + + @Test + public void givenCorrectInputEvenMethod_whenRun_thenAllGood() { + setInput("4 4 even"); + boolean isEvenInOutput; + boolean areCharsEven = false; + String expected = "Even letters - "; + + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + removeFromOutput("There is an unsorted table:"); + String[] inOutput = getOutputLines(); + + for (String str : inOutput + ) { + if (str.contains("|")) { + removeFromOutput(str); + } + } + + String[] rest = getOutputLines(); + String restedString = rest[0]; + String beginning = restedString.substring(0, 15); + isEvenInOutput = expected.equals(beginning); + + String restedChars = restedString.substring(15); + restedChars.replaceAll("\\p{P}", ""); + char[] charsRest = restedChars.toCharArray(); + for (char ch : charsRest + ) { + areCharsEven = (ch % 2) == 0; + } + assertTrue(isEvenInOutput && areCharsEven); + } + + @Test + void givenOneArgument_whenRun_thenErrorOccurs() { + setInput("4"); + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + String inOutput = getOutput(); + + assertEquals(ERR_MSG, inOutput); + } + + @Test + void givenTwoArguments_whenRun_thenErrorOccurs() { + setInput("4 4"); + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + String inOutput = getOutput(); + + assertEquals(ERR_MSG, inOutput); + } + + @Test + void givenThreeArgsMethodIsWrong_whenRun_thenErrorOccurs() { + setInput("4 4 string"); + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + String inOutput = getOutput(); + + assertEquals(ERR_MSG, inOutput); + } + + @Test + void givenEmptyInput_whenRun_thenErrorOccurs() { + setInput(""); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + String inOutput = getOutput(); + + assertThrows(NullPointerException.class, () -> + new RandomCharsTable().run()); + } + + @Test + void givenMoreThenThreeArgs_whenRun_thenErrorOccurs() { + setInput("4 4 odd string"); + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + String inOutput = getOutput(); + + assertEquals(ERR_MSG, inOutput); + } + + @Test + void givenThreeArgsOrderIsWrong_whenRun_thenErrorOccurs() { + setInput("4 odd 4"); + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + String inOutput = getOutput(); + + assertEquals(ERR_MSG, inOutput); + } + + @Test + public void givenZeroZeroOddMethod_whenRun_thenAllGood() { + setInput("0 0 odd"); + + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenZeroZeroEvenMethod_whenRun_thenAllGood() { + setInput("0 0 even"); + + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenZeroOneEvenMethod_whenRun_thenAllGood() { + setInput("0 1 even"); + + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenOneZeroEvenMethod_whenRun_thenAllGood() { + setInput("1 0 even"); + + new RandomCharsTable().run(); + removeFromOutput("Enter two Integers and sorting method, even or odd, e.g. 12 12 odd"); + + assertEquals(ERR_MSG, getOutput()); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework/homework_2/traffic_light/TrafficLightTest.java new file mode 100644 index 00000000..ab55fd0b --- /dev/null +++ b/src/test/java/homework/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,138 @@ +package homework.homework_2.traffic_light; + +import homework.unit_base.UnitBase; +import homework_2.traffic_light.TrafficLight; +import org.junit.jupiter.api.Test; + + +import static org.junit.jupiter.api.Assertions.*; + +class TrafficLightTest extends UnitBase { + + final String ERR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + + //tested cases negative + // string + // more than 86399 + // 0 + // 60 + // 5 + // 30 + // 35 + // 57 + // 45 + // 11 52 seconds + + + @Test + public void givenNegative_whenRun_thenErrOccurs() { + setInput("-1"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenString_whenRun_thenErrOccurs() { + setInput("string"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenBiggerThen86399_whenRun_thenDayIsOver() { + setInput("86400"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertEquals("The day is over", getOutput()); + } + + @Test + public void givenZero_whenRun_thenIsGREEN() { + setInput("0"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("GREEN")); + } + + @Test + public void givenSixty_whenRun_thenIsGREEN() { + setInput("60"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("GREEN")); + } + + @Test + public void givenFive_whenRun_thenIsGREEN() { + setInput("5"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("GREEN")); + } + + @Test + public void givenThirty_whenRun_thenIsGREEN() { + setInput("30"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("GREEN")); + } + + @Test + public void givenThirtyFive_whenRun_thenIsYELLOW() { + setInput("35"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + public void givenFiftySeven_whenRun_thenIsYELLOW() { + setInput("57"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + public void givenFoutryFive_whenRun_thenIsRED() { + setInput("45"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("RED")); + } + + @Test + public void givenFiftyTwo_whenRun_thenIsRED() { + setInput("52"); + + new TrafficLight().run(); + removeFromOutput("Enter the number, please."); + printOut(); + assertTrue(getOutput().contains("RED")); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework/homework_4/CustomFileReaderTest.java b/src/test/java/homework/homework_4/CustomFileReaderTest.java new file mode 100644 index 00000000..fc0f03dc --- /dev/null +++ b/src/test/java/homework/homework_4/CustomFileReaderTest.java @@ -0,0 +1,56 @@ +package homework.homework_4; + +import homework.unit_base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CustomFileReaderTest extends UnitBase { + + @Test + public void givenRunAllThree_whenRun_thenResultsAreTheSame() { + new CustomFileReader().run1(); + new CustomFileReader().run2(); + new CustomFileReader().run3(); + + String[] resultStrings = getOutputLines(); + String resultAfterRun1 = resultStrings[0]; + String resultAfterRun2 = resultStrings[1]; + String resultAfterRun3 = resultStrings[2]; + + assertEquals(resultAfterRun1, resultAfterRun2); + assertEquals(resultAfterRun1, resultAfterRun3); + } + + @Test + public void givenRun1_whenRun_thenOutputDoesntContainsComasAndDots() { + new CustomFileReader().run1(); + + String[] resultStrings = getOutputLines(); + String result = resultStrings[0]; + + assertFalse(result.contains("(\\.)|(,)")); + } + + @Test + public void givenRun2_whenRun_thenOutputDoesntContainsComasAndDots() { + new CustomFileReader().run2(); + + String[] resultStrings = getOutputLines(); + String result = resultStrings[0]; + + assertFalse(result.contains("(\\.)|(,)")); + } + + @Test + public void givenRun3_whenRun_thenOutputDoesntContainsComasAndDots() { + new CustomFileReader().run3(); + + String[] resultStrings = getOutputLines(); + String result = resultStrings[0]; + + assertFalse(result.contains("(\\.)|(,)")); + } + +} diff --git a/src/test/java/homework/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..5766010c --- /dev/null +++ b/src/test/java/homework/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,33 @@ +package homework.homework_4.custom_annotation; + +import homework_4.custom_annotation.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CustomAnnotationTest { + + + @Test + public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException { + Object object = new Object(); + ObjectToJsonConverter serializer = new ObjectToJsonConverter(); + assertThrows(JsonSerializationException.class, () -> serializer.convertToJson(object)); + } + + @Test + public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException { + Person dvasch = new Person("dima", "vaschenko", "35"); + ObjectToJsonConverter converter = new ObjectToJsonConverter(); + String jsonString = converter.convertToJson(dvasch); + System.out.println(jsonString); + assertEquals("{\"personAge\":\"35\",\"firstName\":\"Dima\",\"lastName\":\"Vaschenko\"}", jsonString); + } + + + + + + + +} diff --git a/src/test/java/homework/homework_4/singleton/EnumSingletonTest.java b/src/test/java/homework/homework_4/singleton/EnumSingletonTest.java new file mode 100644 index 00000000..c64309e8 --- /dev/null +++ b/src/test/java/homework/homework_4/singleton/EnumSingletonTest.java @@ -0,0 +1,19 @@ +package homework.homework_4.singleton; + +import homework_4.singleton.EnumSingleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class EnumSingletonTest { + + @Test + public void compareInstances(){ + + EnumSingleton singleton1 = EnumSingleton.getInstance(); + EnumSingleton singleton2 = EnumSingleton.getInstance(); + + assertSame(singleton1, singleton2); + } + +} diff --git a/src/test/java/homework/homework_4/singleton/NaiveSingletonTest.java b/src/test/java/homework/homework_4/singleton/NaiveSingletonTest.java new file mode 100644 index 00000000..02168cb9 --- /dev/null +++ b/src/test/java/homework/homework_4/singleton/NaiveSingletonTest.java @@ -0,0 +1,32 @@ +package homework.homework_4.singleton; + +import homework_4.singleton.NaiveSingleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class NaiveSingletonTest { + + @Test + public void compareInstancesWithEqualSign(){ + NaiveSingleton singleton1 = NaiveSingleton.getInstance(); + NaiveSingleton singleton2 = NaiveSingleton.getInstance(); + NaiveSingleton singletonX = NaiveSingleton.getInstance(); + + assertSame(singleton1, singleton2); + assertSame(singleton1, singletonX); + + } + + @Test + public void compareInstancesWithEqualsMethod(){ + NaiveSingleton singleton1 = NaiveSingleton.getInstance(); + NaiveSingleton singleton2 = NaiveSingleton.getInstance(); + NaiveSingleton singletonX = NaiveSingleton.getInstance(); + + assertEquals(singleton2, singleton1); + assertSame(singleton1, singletonX); + + } + +} diff --git a/src/test/java/homework/homework_4/singleton/SingletonTest.java b/src/test/java/homework/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..1e036897 --- /dev/null +++ b/src/test/java/homework/homework_4/singleton/SingletonTest.java @@ -0,0 +1,28 @@ +package homework.homework_4.singleton; + +import homework_4.singleton.Singleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class SingletonTest { + + @Test + public void compareInstances() { + + Singleton singleton1 = Singleton.getInstance(); + Singleton singleton2 = Singleton.getInstance(); + + assertSame(singleton1, singleton2); +} + @Test + public void compareWithNull(){ + + Singleton singleton1 = null; + Singleton singleton2 = Singleton.getInstance(); + + assertNotSame(singleton1, singleton2); + } + + +} diff --git a/src/test/java/homework/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..6c8f14ef --- /dev/null +++ b/src/test/java/homework/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,89 @@ +package homework.homework_5.custom_regex_matcher; +import homework.unit_base.UnitBase; + +import homework_5.custom_regex_matcher.CustomRegexMatcher; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CustomRegexMatcherTest extends UnitBase { + String greet = "Enter password-ish string, should have 1 lowercase letter, 1 uppercase letter, 1 number, and be at least 8 characters long"; + + CustomRegexMatcher crm = new CustomRegexMatcher(); + @Test + public void givenEmptyInput_whenRun_thenNPEThrown() { + setInput(""); + assertThrows(NullPointerException.class, () -> + crm.run()); + } + + @Test + public void givenSignsNotInRegex_whenRun_thenFalse() { + setInput("!!123tr>>?"); + crm.run(); + removeFromOutput(greet); + assertEquals("false", getOutput()); + } + + @Test + public void givenShortString_whenRun_thenFalse() { + setInput("string"); + crm.run(); + removeFromOutput(greet); + assertEquals("false", getOutput()); + } + + @Test + public void given8PlusLengthLowercase_whenRun_thenFalse() { + setInput("abcdefabcdef"); + crm.run(); + removeFromOutput(greet); + assertEquals("false", getOutput()); + } + + @Test + public void given8PlusLengthUppercase_whenRun_thenFalse() { + setInput("ABCDABCDE"); + crm.run(); + removeFromOutput(greet); + assertEquals("false", getOutput()); + } + + @Test + public void given8PlusDigits_whenRun_thenFalse() { + setInput("123456789"); + crm.run(); + removeFromOutput(greet); + assertEquals("false", getOutput()); + } + + @Test + public void givenCorrectOne_whenRun_thenTrue() { + setInput("A1asdasdasd"); + crm.run(); + removeFromOutput(greet); + assertEquals("true", getOutput()); + } + + @Test + public void givenCorrectTwo_whenRun_thenTrue() { + setInput("passworD123"); + crm.run(); + removeFromOutput(greet); + assertEquals("true", getOutput()); + } + + @Test + public void givenCorrectThree_whenRun_thenTrue() { + setInput("PassWord0123"); + crm.run(); + removeFromOutput(greet); + assertEquals("true", getOutput()); + } + + + + + + +} diff --git a/src/test/java/homework/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..5ec5a1b7 --- /dev/null +++ b/src/test/java/homework/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,96 @@ +package homework.homework_5.power_of_number; + + +import homework.unit_base.UnitBase; +import homework_5.power_of_number.PowerOfNumber; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class PowerOfNumberTest extends UnitBase { + private final String ERR_MSG = "Only 2 non-negative integers are allowed"; + private PowerOfNumber powerOfNumber = new PowerOfNumber(); + // tested cases : string in input + // single integer + // three integers + // empty input + // three args, wrong method string + // empty input + // double numbers + // negative numbers + // 2 3 + // 10 123 21, result bigger then int + + @Test + public void givenString_whenRun_thenErrorOccurs() { + setInput("string"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenOneInteger_whenRun_thenErrorOccurs() { + setInput("12"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenThreeIntegers_whenRun_thenErrorOccurs() { + setInput("12 12 12"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenEmptyInput_whenRun_thenErrorOccurs() { + setInput(""); + + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertThrows(NullPointerException.class, () -> + new PowerOfNumber().run()); + } + + @Test + public void givenTwoDoubles_whenRun_thenErrorOccurs() { + setInput("12.1 12.1"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals(ERR_MSG, getOutput()); + } + + @Test + public void givenNegativeInInput_whenRun_thenErrorOccurs() { + setInput("-2 12"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals(ERR_MSG, getOutput()); + removeFromOutput(ERR_MSG); + setInput("2 -12"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals(ERR_MSG, getOutput()); + + } + + @Test + public void givenTwoAndThree_whenRun_thenErrorOccurs() { + setInput("2 3"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals("8", getOutput()); + } + + @Test + public void given123and21_whenRun_thenErrorOccurs() { + setInput("123 21"); + powerOfNumber.run(); + removeFromOutput("Enter the number and degree, please, only 2 non-negative integers are allowed:"); + assertEquals("77269364466549865653073473388030061522211723", getOutput()); + } + + +} diff --git a/src/test/java/base/UnitBase.java b/src/test/java/homework/unit_base/UnitBase.java similarity index 98% rename from src/test/java/base/UnitBase.java rename to src/test/java/homework/unit_base/UnitBase.java index 97e2685b..1daac521 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/homework/unit_base/UnitBase.java @@ -1,4 +1,4 @@ -package base; +package homework.unit_base; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream;