diff --git a/README.md b/README.md index 5d686e9f..3b6085f1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,19 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Krylosov Arkadiy* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | - -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2.1 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/traffic_light) | The app that reads input arguments and output, what traffic light color it would be in inputted time. User has an opportunity to enter time in 2 formats | +| HW2.2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/pyramid_printer) | The app that reads input arguments and prints a pyramid of "x" according to the entered positive integer| +| HW2.3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_2/random_chars_table) | The app that reads input arguments and prints an array and a String of even of odd letters, result depends on chosen strategy| +| HW3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_3) | Example of immutable class| +| HW4.1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_file_reader) |The app that reads file 3 different ways and print the result into console | +| HW4.2 | [My annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/custom_annotation) | My custom annotation that allows to put annotated fields into JSON file| +| HW4.3 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_4/singleton) |Example of singleton design pattern | +| HW5.1 | [Power of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_5/power_of_number) |The app that raises to the power of input using recursion | +| HW5.2 | [Custom regex matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_5/custom_regex_matcher) |The app that simulate password regex matcher | +| HW6 | [Map problems generator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KrylosovArkady/src/main/java/homework_6/map_problems_generator) |Example of problems that may occur if contract of equals & hashCode are not followed and if mutable class if used as a key | +[Link to codingBat](https://codingbat.com/done?user=krylosov.arkady@yandex.ru&tag=8157289593) +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..71a2a19d --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +import course_project.service.Runner; + +public class Main { + public static void main(String[] args) { + Runner runner = new Runner(); + runner.run(); + } + +} diff --git a/src/main/java/course_project/custom_exceptions/CoordinatesNumber.java b/src/main/java/course_project/custom_exceptions/CoordinatesNumber.java new file mode 100644 index 00000000..a539ca28 --- /dev/null +++ b/src/main/java/course_project/custom_exceptions/CoordinatesNumber.java @@ -0,0 +1,8 @@ +package course_project.custom_exceptions; + +public class CoordinatesNumber extends Exception{ + + public CoordinatesNumber() { + super("Number of coordinates don't fit ship length"); + } +} diff --git a/src/main/java/course_project/custom_exceptions/InvalidShip.java b/src/main/java/course_project/custom_exceptions/InvalidShip.java new file mode 100644 index 00000000..639b30cd --- /dev/null +++ b/src/main/java/course_project/custom_exceptions/InvalidShip.java @@ -0,0 +1,8 @@ +package course_project.custom_exceptions; + +public class InvalidShip extends Exception { + + public InvalidShip() { + super("Invalid place for ship! It should be horizontal, vertical and solid structure"); + } +} diff --git a/src/main/java/course_project/custom_exceptions/PlaceNotFree.java b/src/main/java/course_project/custom_exceptions/PlaceNotFree.java new file mode 100644 index 00000000..c5f8c4d2 --- /dev/null +++ b/src/main/java/course_project/custom_exceptions/PlaceNotFree.java @@ -0,0 +1,8 @@ +package course_project.custom_exceptions; + +public class PlaceNotFree extends Exception { + + public PlaceNotFree() { + super("Invalid place for ship: this place is already occupied by another ship or another ship is too close"); + } +} diff --git a/src/main/java/course_project/model/Battlefield.java b/src/main/java/course_project/model/Battlefield.java new file mode 100644 index 00000000..b7071cd9 --- /dev/null +++ b/src/main/java/course_project/model/Battlefield.java @@ -0,0 +1,19 @@ +package course_project.model; + +import java.util.Arrays; + +public class Battlefield { + private Designation[][] grid; + + public Battlefield() { + grid = new Designation[11][11]; + for (Designation[] cell : grid) { + Arrays.fill(cell, Designation.EMPTY); + } + } + + public Designation[][] getGrid() { + return grid; + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/model/Designation.java b/src/main/java/course_project/model/Designation.java new file mode 100644 index 00000000..316fa89f --- /dev/null +++ b/src/main/java/course_project/model/Designation.java @@ -0,0 +1,30 @@ +package course_project.model; + +public enum Designation { + SHIP("◾", 0), + FOUR_DECKER("", 4), + THREE_DECKER("", 3), + TWO_DECKER("", 2), + ONE_DECKER("", 1), + HIT("x", 0), + EMPTY("~", 0), + MISS("*", 0), + GAP("o", 0); + + private String sign; + private int length; + + Designation(String sign, int length) { + this.sign = sign; + this.length = length; + } + + @Override + public String toString() { + return sign; + } + + public int getLength() { + return length; + } +} diff --git a/src/main/java/course_project/model/Player.java b/src/main/java/course_project/model/Player.java new file mode 100644 index 00000000..732ca311 --- /dev/null +++ b/src/main/java/course_project/model/Player.java @@ -0,0 +1,56 @@ +package course_project.model; + +import java.io.IOException; +import java.util.Scanner; + +public class Player { + + private Battlefield myField; + private Battlefield enemyField; + private String name; + private int shipsAmount; + + public Player() { + myField = new Battlefield(); + enemyField = new Battlefield(); + shipsAmount = 10; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + + + public Designation[][] getGrid() { + return myField.getGrid(); + } + + public Battlefield getField() { + return this.myField; + } + + public Battlefield getEnemyField() { + return this.enemyField; + } + + public void setMyField(Battlefield myField) { + this.myField = myField; + } + + public void setEnemyField(Battlefield enemyField) { + this.enemyField = enemyField; + } + + public int getShipsAmount() { + return shipsAmount; + } + + public void setShipsAmount(int shipsAmount) { + this.shipsAmount = shipsAmount; + } +} diff --git a/src/main/java/course_project/service/BattleFieldService.java b/src/main/java/course_project/service/BattleFieldService.java new file mode 100644 index 00000000..d1fdb45e --- /dev/null +++ b/src/main/java/course_project/service/BattleFieldService.java @@ -0,0 +1,367 @@ +package course_project.service; + +import course_project.custom_exceptions.CoordinatesNumber; +import course_project.custom_exceptions.InvalidShip; +import course_project.custom_exceptions.PlaceNotFree; +import course_project.model.Battlefield; +import course_project.model.Designation; +import course_project.model.Player; + +import java.io.IOException; +import java.util.*; + +public class BattleFieldService { + + private final Battlefield battlefield; + + public BattleFieldService(Battlefield battlefield) { + this.battlefield = battlefield; + } + + public void print(Battlefield battlefield) { + Designation[][] grid = battlefield.getGrid(); + for (int i = 1; i < grid.length; i++) { + if (i == 1) { + System.out.print(" \t"); + for (int j = 1; j < 11; j++) { + System.out.print((char) ('A' + (j - 1)) + "\t"); + } + System.out.println(); + } + System.out.print(i + "\t"); + for (int j = 1; j < grid[i].length; j++) { + System.out.print((j == grid[i].length - 1) ? (grid[i][j] + "\n") : grid[i][j] + "\t"); + } + } + } + + public void autoShipPlacement(Player player) { + String fourDecker = "A1;A2;A3;A4"; + String threeDeckerFirst = "C1;C2;C3"; + String threeDeckerSecond = "C5;C6;C7"; + String twoDeckerFirst = "E1;E2"; + String twoDeckerSecond = "E4;E5"; + String twoDeckerThird = "E7;E8"; + String oneDeckerFirst = "G1"; + String oneDeckerSecond = "G3"; + String oneDeckerThird = "G5"; + String oneDeckerFourth = "G7"; + + try { + putShip(player, fourDecker, Designation.FOUR_DECKER); + putShip(player, threeDeckerFirst, Designation.THREE_DECKER); + putShip(player, threeDeckerSecond, Designation.THREE_DECKER); + putShip(player, twoDeckerFirst, Designation.TWO_DECKER); + putShip(player, twoDeckerSecond, Designation.TWO_DECKER); + putShip(player, twoDeckerThird, Designation.TWO_DECKER); + putShip(player, oneDeckerFirst, Designation.ONE_DECKER); + putShip(player, oneDeckerSecond, Designation.ONE_DECKER); + putShip(player, oneDeckerThird, Designation.ONE_DECKER); + putShip(player, oneDeckerFourth, Designation.ONE_DECKER); + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + System.out.println("Fields with all ships: "); + print(player.getField()); + System.out.println("\n\n"); + } + + public void arrangement(Player player, Scanner readIt) { + + System.out.println(player.getName() + ", your field is below\n"); + print(player.getField()); + + while (true) { + try { + System.out.println(player.getName() + ", enter coordinates of four-decker (format: A1;A2;A3;A4)"); + putShip(player, readIt.nextLine(), Designation.FOUR_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip exc) { + System.out.println(exc.getMessage()); + } + } + + for (int i = 0; i < 2; i++) { + while (true) { + try { + System.out.println("Enter coordinates of three-decker (format: A1;A2;A3)"); + putShip(player, readIt.nextLine(), Designation.THREE_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + } + } + + for (int i = 0; i < 3; i++) { + while (true) { + try { + System.out.println("Enter coordinates of two-decker (format: A1;A2)"); + putShip(player, readIt.nextLine(), Designation.TWO_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + } + } + + for (int i = 0; i < 4; i++) { + while (true) { + try { + System.out.println("Enter coordinates of one-decker (format: A1)"); + putShip(player, readIt.nextLine(), Designation.ONE_DECKER); + print(player.getField()); + break; + } catch (IOException | CoordinatesNumber | PlaceNotFree | InvalidShip e) { + System.out.println(e.getMessage()); + } + } + } + System.out.println("Fields with all ships: "); + print(player.getField()); + System.out.println("Enter any to skip your field"); + readIt.nextLine(); + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n"); + } + + public boolean isDead(Battlefield battlefield, int x, int y) { + for (int i = 1; i <= 3; i++) { + if (x - i >= 0 && battlefield.getGrid()[x - i][y] == Designation.SHIP) { + return false; + } else if (x - i >= 0 && battlefield.getGrid()[x - i][y] != Designation.HIT) { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (x + i <= 9 && battlefield.getGrid()[x + i][y] == Designation.SHIP) { + return false; + } else if (x + i <= 9 && battlefield.getGrid()[x + i][y] != Designation.HIT) { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y - i >= 0 && battlefield.getGrid()[x][y - i] == Designation.SHIP) { + return false; + } else if (y - i >= 0 && battlefield.getGrid()[x][y - i] != Designation.HIT) { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y + i <= 9 && battlefield.getGrid()[x][y + i] == Designation.SHIP) { + return false; + } else if (y + i <= 9 && battlefield.getGrid()[x][y + i] != Designation.HIT) { + break; + } + } + return true; + } + + public void surroundDeadShip(Battlefield battlefield, int x, int y) { + List deadShipCoords = new ArrayList<>(); + deadShipCoords.add(new int[]{x, y}); + + for (int i = 1; i <= 3; i++) { + if (x - i >= 0 && battlefield.getGrid()[x - i][y] == Designation.HIT) { + deadShipCoords.add(new int[]{x - i, y}); + } else { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (x + i <= 9 && battlefield.getGrid()[x + i][y] == Designation.HIT) { + deadShipCoords.add(new int[]{x + i, y}); + } else { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y - i >= 0 && battlefield.getGrid()[x][y - i] == Designation.HIT) { + deadShipCoords.add(new int[]{x, y - i}); + } else { + break; + } + } + + for (int i = 1; i <= 3; i++) { + if (y + i <= 9 && battlefield.getGrid()[x][y + i] == Designation.HIT) { + deadShipCoords.add(new int[]{x, y + i}); + } else { + break; + } + } + + for (int[] coord : deadShipCoords) { + int a = coord[0]; + int b = coord[1]; + + if (a - 1 >= 0 && battlefield.getGrid()[a - 1][b] != Designation.HIT) { + battlefield.getGrid()[a - 1][b] = Designation.MISS; + } + if (a - 1 >= 0 && b + 1 <= 9 && battlefield.getGrid()[a - 1][b + 1] != Designation.SHIP) { + battlefield.getGrid()[a - 1][b + 1] = Designation.MISS; + } + if (b + 1 <= 9 && battlefield.getGrid()[a][b + 1] != Designation.HIT) { + battlefield.getGrid()[a][b + 1] = Designation.MISS; + } + if (a + 1 <= 9 && b + 1 <= 9 && battlefield.getGrid()[a + 1][b + 1] != Designation.HIT) { + battlefield.getGrid()[a + 1][b + 1] = Designation.MISS; + } + if (a + 1 <= 9 && battlefield.getGrid()[a + 1][b] != Designation.HIT) { + battlefield.getGrid()[a + 1][b] = Designation.MISS; + } + if (a + 1 <= 9 && b - 1 >= 0 && battlefield.getGrid()[a + 1][b - 1] != Designation.HIT) { + battlefield.getGrid()[a + 1][b - 1] = Designation.MISS; + } + if (b - 1 >= 0 && battlefield.getGrid()[a][b - 1] != Designation.HIT) { + battlefield.getGrid()[a][b - 1] = Designation.MISS; + } + if (a - 1 >= 0 && b - 1 >= 0 && battlefield.getGrid()[a - 1][b - 1] != Designation.HIT) { + battlefield.getGrid()[a - 1][b - 1] = Designation.MISS; + } + } + } + + private void putShip(Player player, String strCoords, Designation ship) throws CoordinatesNumber, IOException, InvalidShip, PlaceNotFree { + + String[] shipCoordsArray = strCoords.split(";"); + + if (shipCoordsArray.length != ship.getLength()) { + throw new CoordinatesNumber(); + } + + int[][] digitalCoords = new int[shipCoordsArray.length][2]; + + for (int i = 0; i < shipCoordsArray.length; i++) { + if (Character.isDigit(shipCoordsArray[i].charAt(0)) || !Character.isDigit(shipCoordsArray[i].charAt(1))) { + System.out.println("Invalid input format! X should be letter A-J and Y - numbers 0 - 9"); + throw new IOException(); + } + + digitalCoords[i][0] = Character.getNumericValue(shipCoordsArray[i].charAt(1)); + digitalCoords[i][1] = shipCoordsArray[i].toLowerCase().charAt(0) - 96; + } + + if (!isValid(digitalCoords)) { + throw new InvalidShip(); + } + if (!isFree(digitalCoords, player.getField().getGrid())) { + throw new PlaceNotFree(); + } + + for (int[] digitalCoord : digitalCoords) { + + player.getField().getGrid()[digitalCoord[0]][digitalCoord[1]] = Designation.SHIP; + } + + for (int[] digitalCoord : digitalCoords) { + int x = digitalCoord[0]; + int y = digitalCoord[1]; + + if (x - 1 >= 0 && player.getField().getGrid()[x - 1][y] != Designation.SHIP) { + player.getField().getGrid()[x - 1][y] = Designation.GAP; + } + if (x - 1 >= 0 && y + 1 <= 9 && player.getField().getGrid()[x - 1][y + 1] != Designation.SHIP) { + player.getField().getGrid()[x - 1][y + 1] = Designation.GAP; + } + if (y + 1 <= 9 && player.getField().getGrid()[x][y + 1] != Designation.SHIP) { + player.getField().getGrid()[x][y + 1] = Designation.GAP; + } + if (x + 1 <= 9 && y + 1 <= 9 && player.getField().getGrid()[x + 1][y + 1] != Designation.SHIP) { + player.getField().getGrid()[x + 1][y + 1] = Designation.GAP; + } + if (x + 1 <= 9 && player.getField().getGrid()[x + 1][y] != Designation.SHIP) { + player.getField().getGrid()[x + 1][y] = Designation.GAP; + } + if (x + 1 <= 9 && y - 1 >= 0 && player.getField().getGrid()[x + 1][y - 1] != Designation.SHIP) { + player.getField().getGrid()[x + 1][y - 1] = Designation.GAP; + } + if (y - 1 >= 0 && player.getField().getGrid()[x][y - 1] != Designation.SHIP) { + player.getField().getGrid()[x][y - 1] = Designation.GAP; + } + if (x - 1 >= 0 && y - 1 >= 0 && player.getField().getGrid()[x - 1][y - 1] != Designation.SHIP) { + player.getField().getGrid()[x - 1][y - 1] = Designation.GAP; + } + } + } + + private boolean isValid(int[][] coords) { + if (coords.length == 1) { + return true; + } + + int x = coords[0][0]; + int y = coords[0][1]; + boolean isCorrect = true; + + for (int i = 1; i < coords.length; i++) { + if (coords[i][0] == x) { + + for (int j = 0; j < coords.length; j++) { + if (i == j) { + continue; + } + + if (coords[i][1] == coords[j][1] || coords[i][1] == y) { + isCorrect = false; + break; + } + } + + int[] isAdjacent = new int[coords.length]; + + for (int j = 0; j < coords.length; j++) { + isAdjacent[j] = coords[j][1]; + } + Arrays.sort(isAdjacent); + + for (int t = 0; t < isAdjacent.length - 1; t++) { + isCorrect = isAdjacent[t + 1] == (isAdjacent[t] + 1) && isCorrect; + } + + } else if (coords[i][1] == y) { + for (int j = 0; j < coords.length; j++) { + if (i == j) { + continue; + } + + if (coords[i][0] == coords[j][0] || coords[i][0] == x) { + isCorrect = false; + break; + } + } + + int[] isAdjacent = new int[coords.length]; + for (int j = 0; j < coords.length; j++) { + isAdjacent[j] = coords[j][0]; + } + Arrays.sort(isAdjacent); + + for (int t = 0; t < isAdjacent.length - 1; t++) { + isCorrect = isAdjacent[t + 1] == (isAdjacent[t] + 1) && isCorrect; + } + + } else { + isCorrect = false; + } + } + return isCorrect; + } + + private boolean isFree(int[][] coords, Designation[][] field) { + for (int[] coord : coords) { + if (!(field[coord[0]][coord[1]] == Designation.EMPTY)) { + return false; + } + } + return true; + } + +} diff --git a/src/main/java/course_project/service/PlayerService.java b/src/main/java/course_project/service/PlayerService.java new file mode 100644 index 00000000..f203b0e3 --- /dev/null +++ b/src/main/java/course_project/service/PlayerService.java @@ -0,0 +1,89 @@ +package course_project.service; + +import course_project.model.Battlefield; +import course_project.model.Designation; +import course_project.model.Player; + +import java.io.IOException; +import java.util.Scanner; + +public class PlayerService { + + private final BattleFieldService battleFieldService; + private final Player player; + + public PlayerService(Player player, BattleFieldService battleFieldService) { + this.player = player; + this.battleFieldService = battleFieldService; + } + + public boolean makeShot(Player currentPlayer, Player enemy, Scanner readIt) throws IOException { + int shipAmount = enemy.getShipsAmount(); + + System.out.println("Your battlefield:"); + battleFieldService.print(currentPlayer.getField()); + System.out.println("Enemy battlefield:"); + battleFieldService.print(currentPlayer.getEnemyField()); + + System.out.println("Player " + currentPlayer.getName() + "is playing. Enter coordinates int format \"A1\""); + + while (true) { + String strCoord = readIt.nextLine(); + + if (strCoord.length() != 2 || + Character.isDigit(strCoord.charAt(0)) || !Character.isDigit(strCoord.charAt(1))) { + System.out.println("Invalid format of input! Enter coordinates in format \"A1\""); + throw new IOException(); + } + + int x = Character.getNumericValue(strCoord.charAt(1)); + int y = strCoord.toLowerCase().charAt(0) - 96; + + if (enemy.getGrid()[x][y] == Designation.SHIP) { + + enemy.getGrid()[x][y] = Designation.HIT; + enemy.getField().getGrid()[x][y] = Designation.HIT; + + if (battleFieldService.isDead(enemy.getField(), x, y)) { + battleFieldService.surroundDeadShip(currentPlayer.getEnemyField(), x, y); + battleFieldService.surroundDeadShip(enemy.getField(), x, y); + } + + System.out.println("Your field:"); + battleFieldService.print(currentPlayer.getField()); + System.out.println("Enemy field:"); + battleFieldService.print(currentPlayer.getEnemyField()); + System.out.println("HIT!"); + + if (battleFieldService.isDead(enemy.getField(), x, y)) { + System.out.println("Ship totally destroyed!"); + enemy.setShipsAmount(--shipAmount); + } + + if (enemy.getShipsAmount() < 0) { + System.out.println("Congratulations to player " + currentPlayer + "!"); + return false; + } else { + System.out.println("Shoot one more time!"); + } + + } else if (enemy.getGrid()[x][y] == Designation.HIT) { + System.out.println("You already shoot here! Shoot one more time!"); + } else { + enemy.getGrid()[x][y] = Designation.MISS; + currentPlayer.getEnemyField().getGrid()[x][y] = Designation.MISS; + System.out.println("Your field:"); + battleFieldService.print(currentPlayer.getField()); + System.out.println("Enemy field:"); + battleFieldService.print(currentPlayer.getEnemyField()); + System.out.println("MISS!"); + break; + } + } + System.out.println(currentPlayer.getName() + ", your turn is over. Press Enter to pass the turn to another player"); + readIt.nextLine(); + System.out.println("\n\n"); + return true; + } + +} diff --git a/src/main/java/course_project/service/Runner.java b/src/main/java/course_project/service/Runner.java new file mode 100644 index 00000000..f349f40e --- /dev/null +++ b/src/main/java/course_project/service/Runner.java @@ -0,0 +1,83 @@ +package course_project.service; + +import course_project.model.Battlefield; +import course_project.model.Player; + +import java.io.IOException; +import java.util.Scanner; + +public class Runner { + public void run() { + Player a, b, c; + boolean win; + boolean enteredFirst = false; + boolean enteredSecond = false; + Scanner readIt = new Scanner(System.in); + + Player player1 = new Player(); + Player player2 = new Player(); + Battlefield battlefieldOne = new Battlefield(); + Battlefield battlefieldTwo = new Battlefield(); + BattleFieldService playerOneBattlefieldService = new BattleFieldService(battlefieldOne); + BattleFieldService playerTwoBattlefieldService = new BattleFieldService(battlefieldTwo); + PlayerService playerServiceOne = new PlayerService(player1, playerOneBattlefieldService); + PlayerService playerServiceTwo = new PlayerService(player2, playerTwoBattlefieldService); + System.out.println("Enter name of the first player"); + player1.setName(readIt.nextLine()); + while (!enteredFirst) { + System.out.println("Choose ship placement mode: auto or manual"); + String modeFirst = readIt.nextLine(); + if (modeFirst.equalsIgnoreCase("auto")) { + playerOneBattlefieldService.autoShipPlacement(player1); + enteredFirst = true; + } else if (modeFirst.equalsIgnoreCase("manual")) { + playerOneBattlefieldService.arrangement(player1, readIt); + enteredFirst = true; + } + } + + System.out.println("Enter name of the second player"); + player2.setName(readIt.nextLine()); + while (!enteredSecond) { + System.out.println("Choose ship placement mode: auto or manual"); + String modeSecond = readIt.nextLine(); + if (modeSecond.equalsIgnoreCase("auto")) { + playerTwoBattlefieldService.autoShipPlacement(player2); + enteredSecond = true; + } else if (modeSecond.equalsIgnoreCase("manual")) { + playerTwoBattlefieldService.arrangement(player2, readIt); + enteredSecond = true; + } + } + + int first = (int) (Math.random() * 2); + if (first == 0) { + a = player1; + b = player2; + } else { + a = player2; + b = player1; + } + System.out.println("Players have put their ships. Let the battle begin!\n Player " + a.getName() + " starts"); + + do { + while (true) { + try { + win = playerServiceOne.makeShot(a, b, readIt); + break; + } catch (IOException e) { + System.out.println(a.getName() + ", enter coordinates in format \"A1\""); + } + } + c = a; + a = b; + b = c; + } while (!win); + + System.out.println("Game is over!"); + + readIt.close(); + } + +} + diff --git a/src/main/java/homework_1/CommandLineArgs.java b/src/main/java/homework_1/CommandLineArgs.java new file mode 100644 index 00000000..95b74935 --- /dev/null +++ b/src/main/java/homework_1/CommandLineArgs.java @@ -0,0 +1,20 @@ +package homework_1; + +public class CommandLineArgs { + + private static final String ANSI_RED = "\u001B[31m"; + + private static final String ANSI_RESET = "\u001B[0m"; + + public static void main(String[] args) { + for (String s : args) { + if (s.equals("error")) { + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); + break; + } else { + System.out.println(s + ": " + s.length() + " letters"); + } + } + } +} + 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..e00ce234 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,8 @@ +package homework_2.pyramid_printer; + +public class Main { + public static void main(String[] args) { + PyramidPrinter pyramidPrinter = new PyramidPrinter(); + 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..f03e5959 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,36 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + private final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run() { + System.out.println("Please, input a number:"); + int input = consoleReader(); + if (input<0) { + System.out.println(ERROR); + } else { + printResult(input); + } + } + + private int consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return Integer.parseInt(bF.readLine()); + } catch (NumberFormatException | IOException exception) { + return -1; + } + } + + private void printResult(int input) { + String output = ""; + for (int i = 0; i < input; i++) { + output += "x"; + System.out.println(output); + } + } +} 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..901735a8 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,8 @@ +package homework_2.random_chars_table; + +public class Main { + public static void main(String[] args) { + RandomCharsTable randomCharsTable = new RandomCharsTable(); + randomCharsTable.run(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..f159cce4 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,106 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + private final String ERROR = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + private char[][] array; + private String strategy; + private String inputData; + private String result; + private int rows; + private int columns; + + public void run() { + System.out.println("Enter data in format: width, length of matrix and strategy (even/odd)"); + inputData = readingConsole(); + parseData(inputData); + if (dataValidation(rows, columns, strategy)) { + System.out.println(ERROR); + } else { + arrayInitialization(); + if (strategy.equals("odd")) { + oddStrategy(); + } else { + evenStrategy(); + } + printingResult(); + } + } + + private void parseData(String s){ + String[] resultArray = s.split(" "); + if(resultArray.length != 3){ + return; + } + rows = Integer.parseInt(resultArray[0]); + columns = Integer.parseInt(resultArray[1]); + strategy = resultArray[2]; + } + + private void arrayInitialization() { + array = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + System.out.print("|"); + for (int j = 0; j < columns; j++) { + char letters = (char) (Math.random() * 10 + 65); + array[i][j] = letters; + System.out.print(array[i][j] + "|"); + } + System.out.println(); + } + } + + private void oddStrategy() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 1) { + result += array[i][j]; + } + } + } + } + + private void evenStrategy() { + result = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + if ((array[i][j] % 2) == 0) { + result += array[i][j]; + } + } + } + } + + private void printingResult() { + if (strategy.equals("even")) { + System.out.print("Even letters - "); + } else { + System.out.print("Odd letters - "); + } + for(int i = 0; i< result.length();i++){ + if (i == result.length() - 1) { + System.out.print(result.charAt(i)); + break; + } + System.out.print(result.charAt(i) + ", "); + } + } + + private String readingConsole() { + inputData = ""; + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + inputData = bF.readLine(); + } catch (IOException exc) { + System.out.println("Error occurred during input"); + } + return inputData; + } + + private boolean dataValidation(int x, int y, String str) { + return x < 1 || y < 1 || (!str.equals("odd") && !str.equals("even")); + } +} diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..a9d70a3f --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,13 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args) { + TrafficLight trafficLight = new TrafficLight(); + TrafficLightExtraMod trafficLightExtraMod = new TrafficLightExtraMod(); + if(args[0].equals("seconds")){ + trafficLight.run(); + } else { + trafficLightExtraMod.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..aaaefb6d --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,70 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + public final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + protected final String ERROR = "Only 1 non-negative integer is allowed as passed parameter"; + + protected int seconds; + + public void run() { + System.out.println("Enter necessary amount of seconds."); + String input = consoleReader(); + if(!isDigit(input)) { + System.out.println(ERROR); + return; + } + seconds = Integer.parseInt(input); + if (seconds < 0) { + System.out.println(ERROR); + return; + } + if (seconds > 86399) { + System.out.println("Day is over"); + return; + } + trafficLightColorDetection(seconds); + } + + + + protected String consoleReader() { + try (BufferedReader bF = new BufferedReader(new InputStreamReader(System.in))) { + return bF.readLine(); + } catch (NumberFormatException | IOException e) { + + } + return ""; + } + + protected void trafficLightColorDetection(int sec) { + if (sec % 60 < 35) { + System.out.print(ANSI_GREEN + "Green light" + ANSI_RESET); + } else if (sec % 60 < 40 || sec % 60 >= 55) { + System.out.print(ANSI_YELLOW + "Yellow Light" + ANSI_RESET); + } else { + System.out.print(ANSI_RED + "Red light" + ANSI_RESET); + } + } + + private boolean isDigit(String input) { + try{ + Integer.parseInt(input); + return true; + } catch (NumberFormatException e) { + return false; + } + } +} + diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java new file mode 100644 index 00000000..3f6f7419 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMod.java @@ -0,0 +1,15 @@ +package homework_2.traffic_light; + +public class TrafficLightExtraMod extends TrafficLight{ + + public void run() { + System.out.println("Enter necessary time in HH:MM:SS format."); + String parsedTime = consoleReader(); + seconds = Integer.parseInt(parsedTime.substring(parsedTime.length() - 2)); + if (seconds < 0) { + System.out.println(ERROR); + return; + } + trafficLightColorDetection(seconds); + } +} diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..fd9a7ffa --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,74 @@ +package homework_3; + +import java.util.ArrayList; +import java.util.List; + +/* +The class must be declared as final. +Data members in the class must be declared as private & final. +A parameterized constructor should initialize all the fields. +Deep Copy of objects should be performed in the getter methods. +No setters. + */ + +final class ImmutableClass { + + private final int firstInt; + + private final String firstString; + + private final int[] firstIntArray; + + private final String[] firstStringArray; + + private final List firstCollection; + + + ImmutableClass(int firstInt, String firstString, int[] firstIntArray, String[] firstStringArray, List firstCollection) { + this.firstInt = firstInt; + this.firstString = firstString; + this.firstIntArray = firstIntArray; + this.firstStringArray = firstStringArray; + this.firstCollection = firstCollection; + } + + public ImmutableClass() { + this.firstInt = 1; + this.firstString = "Default"; + this.firstIntArray = new int[1]; + this.firstStringArray = new String[1]; + this.firstCollection = new ArrayList<>(); + } + + public ImmutableClass(int firstInt, String firstString) { + this.firstInt = firstInt; + this.firstString = firstString; + this.firstIntArray = new int[1]; + this.firstStringArray = new String[1]; + this.firstCollection = new ArrayList<>(); + } + + public int getFirstInt() { + return firstInt; + } + + public String getFirstString() { + return firstString; + } + + public int[] getFirstIntArray() { + return firstIntArray; + } + + public String[] getFirstStringArray() { + return firstStringArray; + } + + public List getFirstCollection() { + return firstCollection; + } + + public ImmutableClass getNewImmutableClass(int x, String y, int[] xy, String[] yx, List list) { + return new ImmutableClass(x,y,xy,yx,list); + } +} diff --git a/src/main/java/homework_4/custom_annotation/MyAnnotation.java b/src/main/java/homework_4/custom_annotation/MyAnnotation.java new file mode 100644 index 00000000..b3d1405f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/MyAnnotation.java @@ -0,0 +1,17 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +//Аннотация необходимая, которая позволяет включать отмеченные поля в сгенерированный JSON + +public class MyAnnotation { + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface JsonElement { + public String key() default ""; + } +} diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..c6c9dbf2 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,62 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class CustomFileReader { + + private static final String PATH_TO_FILE = "\\src\\main\\resources\\custom_file_reader\\"; + + public void run1(String filename) { + isCorrectFilename(filename); + List data = new ArrayList<>(); + try (BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(getPath(filename))))){ + String line; + while ((line = bf.readLine()) != null) { + data.add(line); + } + } catch (IOException exception){ + System.out.println("Error occurred"); + } + System.out.println(String.join("", data).replaceAll("[,.]", "")); + } + + public void run2(String filename) { + isCorrectFilename(filename); + try{ + Files.lines(Paths.get(getPath(filename))).map(x->x.replaceAll("[,.]","")).forEach(System.out::println); + } catch (IOException exception){ + System.out.println("Error occurred"); + } + } + + public void run3(String filename){ + isCorrectFilename(filename); + try { + Scanner scanner = new Scanner(new FileReader(getPath(filename))); + List data = new ArrayList<>(); + while(scanner.hasNextLine()){ + data.add(scanner.nextLine()); + } + System.out.println(String.join("", data).replaceAll("[,.]", "")); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + private String getPath(String fileName){ + return Paths.get("").toAbsolutePath() + PATH_TO_FILE + fileName; + } + + private boolean isCorrectFilename(String filename) { + if (!(filename.endsWith(".txt"))) { + throw new IllegalArgumentException(); + } else { + return filename.endsWith(".txt"); + } + } +} diff --git a/src/main/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..dbabf5e4 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,11 @@ +package homework_4.custom_file_reader; + +public class Main { + + public static void main(String[] args) { + CustomFileReader customFileReader = new CustomFileReader(); + customFileReader.run1(args[0]); + customFileReader.run2(args[0]); + customFileReader.run3(args[0]); + } +} diff --git a/src/main/java/homework_4/singleton/Main.java b/src/main/java/homework_4/singleton/Main.java new file mode 100644 index 00000000..f4908e77 --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,10 @@ +package homework_4.singleton; + +public class Main { + public static void main(String[] args) { + Singleton firstInstance = Singleton.getInstance(); + System.out.println(firstInstance.getClass().getSimpleName()); + Singleton secondInstance = Singleton.getInstance(); + System.out.println(firstInstance == secondInstance); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..43b87374 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,16 @@ +package homework_4.singleton; + +public class Singleton { + private static Singleton INSTANCE; + + public static Singleton getInstance() { + if (INSTANCE == null) { + INSTANCE = new Singleton(); + } + return INSTANCE; + } + + private Singleton() { + System.out.println("Singleton created"); + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..7eb837b0 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,18 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + private final Scanner sc = new Scanner(System.in); + + public void run() { + String input = sc.nextLine(); + System.out.println(matcher(input)); + } + + private boolean matcher(String s) { + String passwordRegex = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; + return Pattern.matches(passwordRegex, s); + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..0f412d29 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,8 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); + customRegexMatcher.run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..18d1c211 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,8 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + PowerOfNumber powerOfNumber = new PowerOfNumber(); + powerOfNumber.run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..8b601b70 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,43 @@ +package homework_5.power_of_number; + +import java.util.Arrays; +import java.util.Scanner; + +public class PowerOfNumber { + private final Scanner sc = new Scanner(System.in); + private final String ERROR = "Only 2 non-negative integers are allowed"; + + public void run() { + String input = sc.nextLine(); + Integer[] inputData = parseData(input); + int value = inputData[0]; + int powValue = inputData[2]; + int result = pow(value, powValue); + if(result == -1){ + System.out.println(ERROR); + } else { + System.out.println(result); + } + } + + private int pow(int value, int powValue) { + if (powValue == 0) { + return 1; + } else if (powValue == 1) { + return value; + } else if (value < 0 || powValue < 0) { + return -1; + } else { + return value * pow(value, powValue - 1); + } + } + + private Integer[] parseData(String s) { + Character[] array = s.chars().mapToObj(c -> (char) c).toArray(Character[]::new); + if (array.length != 3 || (!Character.isDigit(array[0])) || (!Character.isDigit(array[2]))) { + return new Integer[]{-1, 0, -1}; + } else { + return Arrays.stream(array).map(Character::getNumericValue).toArray(Integer[]::new); + } + } +} diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java new file mode 100644 index 00000000..4d3d0ab8 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,32 @@ +package homework_6.map_problems_generator; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + public static void main(String[] args) { + Map collisionGenerator = new HashMap<>(); + MapProblemsCollisionGenerator firstCollisionKey = new MapProblemsCollisionGenerator(1, "firstValue"); + MapProblemsCollisionGenerator secondCollisionKey = new MapProblemsCollisionGenerator(1, "secondValue"); + MapProblemsCollisionGenerator thirdCollisionKey = new MapProblemsCollisionGenerator(2, "thirdValue"); + + collisionGenerator.put(firstCollisionKey, "firstV"); + collisionGenerator.put(secondCollisionKey, "secondV"); + collisionGenerator.put(thirdCollisionKey, "thirdV"); + + System.out.println(collisionGenerator.get(firstCollisionKey) + " is not firstV"); + System.out.println(collisionGenerator.get(secondCollisionKey) + " is not secondV"); + System.out.println(collisionGenerator.get(thirdCollisionKey) + " is not thirdV"); + + Map mutableGenerator = new HashMap<>(); + MapProblemsMutableGenerator firstMutableKey = new MapProblemsMutableGenerator(1, "firstValue"); + MapProblemsMutableGenerator secondMutableKey = new MapProblemsMutableGenerator(2, "thirdValue"); + + mutableGenerator.put(firstMutableKey, "firstV"); + mutableGenerator.put(secondMutableKey, "thirdV"); + + System.out.println("Before changing " + mutableGenerator.get(firstMutableKey)); + firstMutableKey.setKey(2); + System.out.println("After changing " + mutableGenerator.get(firstMutableKey)); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..dee8c8db --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java @@ -0,0 +1,37 @@ +package homework_6.map_problems_generator; + +public class MapProblemsCollisionGenerator { + private int key; + private String value; + + public MapProblemsCollisionGenerator(int key, String value) { + this.key = key; + this.value = value; + } + + public int getKey() { + return key; + } + + public void setKey(int key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + return true; + } + + @Override + public int hashCode() { + return key; + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..48b1ba77 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -0,0 +1,42 @@ +package homework_6.map_problems_generator; + +import java.util.Objects; + +public class MapProblemsMutableGenerator { + private int key; + private String value; + + public MapProblemsMutableGenerator(int key, String value) { + this.key = key; + this.value = value; + } + + public int getKey() { + return key; + } + + public void setKey(int key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + if(this == o) return true; + if(o == null ||getClass() != o.getClass()) return false; + MapProblemsMutableGenerator another = (MapProblemsMutableGenerator) o; + return key == another.key && Objects.equals(value, another.value); + } + + @Override + public int hashCode() { + return Objects.hash(key, key); + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/Cat.java b/src/main/java/homework_7/kitten_to_cat_function/Cat.java new file mode 100644 index 00000000..592ecc3f --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Cat.java @@ -0,0 +1,35 @@ +package homework_7.kitten_to_cat_function; + +public class Cat { + private String name; + private int age; + + public Cat(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/Kitten.java b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java new file mode 100644 index 00000000..3fe6e890 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java @@ -0,0 +1,25 @@ +package homework_7.kitten_to_cat_function; + +public class Kitten extends Cat { + private String parentName; + + public Kitten(String name, int age, String parentName) { + super(name, age); + this.parentName = parentName; + } + + public String getParentName() { + return parentName; + } + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + @Override + public String toString() { + return "Kitten{" + + "parentName='" + parentName + '\'' + + '}' + super.toString(); + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java new file mode 100644 index 00000000..5c7b09d5 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7.kitten_to_cat_function; + +@FunctionalInterface +public interface KittenToCatFunction { + Cat grow(Kitten kitten); +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/Main.java b/src/main/java/homework_7/kitten_to_cat_function/Main.java new file mode 100644 index 00000000..b601b818 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Main.java @@ -0,0 +1,15 @@ +package homework_7.kitten_to_cat_function; + +public class Main { + public static void main(String[] args) { + Cat cat = new Cat("Anfisa", 10); + Kitten kitten = new Kitten("Sam", 3, "test"); + + KittenToCatFunction kittenToCatFunction = newKitten -> new Cat(newKitten.getName() + "Cat", newKitten.getAge() + 10); + Cat oldKitten = kittenToCatFunction.grow(kitten); + + System.out.println(cat); + System.out.println(kitten); + System.out.println(oldKitten); + } +} diff --git a/src/main/resources/custom_file_reader/CustomFileReader.txt b/src/main/resources/custom_file_reader/CustomFileReader.txt new file mode 100644 index 00000000..b96edced --- /dev/null +++ b/src/main/resources/custom_file_reader/CustomFileReader.txt @@ -0,0 +1,4 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna + aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. + Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. + Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \ No newline at end of file diff --git a/src/main/resources/custom_file_reader/testCustom.txt b/src/main/resources/custom_file_reader/testCustom.txt new file mode 100644 index 00000000..69b5c67d --- /dev/null +++ b/src/main/resources/custom_file_reader/testCustom.txt @@ -0,0 +1 @@ +Linkin park, Halestorm... The ,,,...Pretty Reckless,,... Disturbed \ No newline at end of file diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java new file mode 100644 index 00000000..97e2685b --- /dev/null +++ b/src/test/java/base/UnitBase.java @@ -0,0 +1,73 @@ +package base; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +public abstract class UnitBase { + + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } + + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } + + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } + + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } + + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } + +// @Test +// void example() { +// setInput("2"); +// +// new PyramidPrinter().run(); +// printOut(); +// removeFromOutput("Please input number"): +// +// assertEquals("x", getOutputLines()[0]); +// assertEquals("xx", getOutputLines()[1]); +// } + +} diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java new file mode 100644 index 00000000..803dfc82 --- /dev/null +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -0,0 +1,57 @@ +package homework_2; + +import base.UnitBase; +import homework_2.pyramid_printer.PyramidPrinter; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class PyramidPrinterTest extends UnitBase { + + @Test + void given5_whenRun_thenFiveLinesPrinted() { + setInput("5"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("x", getOutputLines()[0]); + Assertions.assertEquals("xx", getOutputLines()[1]); + Assertions.assertEquals("xxx", getOutputLines()[2]); + Assertions.assertEquals("xxxx", getOutputLines()[3]); + Assertions.assertEquals("xxxxx", getOutputLines()[4]); + } + + @Test + void givenZero_whenRun_thenEmpty() { + setInput("0"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("", getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_thenError() { + setInput("-1"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } + + @Test + void givenNaN_whenRun_thenError() { + setInput("text"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please, input a number:"); + + Assertions.assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } +} diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java new file mode 100644 index 00000000..cf7d0a1a --- /dev/null +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -0,0 +1,59 @@ +package homework_2; + +import base.UnitBase; +import homework_2.random_chars_table.RandomCharsTable; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class RandomCharsTableTest extends UnitBase { + + @Test + void givenTwoTwoEven_whenRun_thenMatrixAndLettersPrinted(){ + setInput("2 2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertTrue(getOutput().contains("|")); + Assertions.assertFalse(getOutput().contains(" |")); + Assertions.assertTrue(getOutput().contains("Even letters - ")); + } + + @Test + void givenTwoThreeOdd_whenRun_thenMatrixAndLettersPrinted(){ + setInput("2 3 odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertTrue(getOutput().contains("|")); + Assertions.assertFalse(getOutput().contains(" |")); + Assertions.assertTrue(getOutput().contains("Odd letters - ")); + } + + @Test + void givenNotFullParameters_whenRun_thenError(){ + setInput("2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertEquals("Passed parameters should match the format [positive integer] " + + "[positive integer] [even|odd]",getOutputLines()[0]); + } + + @Test + void givenZeroAndNegativeParameters_whenRun_thenError(){ + setInput("0 -2 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput("Enter data in format: width, length of matrix and strategy (even/odd)"); + + Assertions.assertEquals("Passed parameters should match the format [positive integer] " + + "[positive integer] [even|odd]",getOutput()); + } +} diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java new file mode 100644 index 00000000..c754063c --- /dev/null +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -0,0 +1,117 @@ +package homework_2; + +import base.UnitBase; +import homework_2.traffic_light.TrafficLight; +import homework_2.traffic_light.TrafficLightExtraMod; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class TrafficLightTest extends UnitBase { + + private final String ANSI_RESET = "\u001b[0m"; + + private final String ANSI_RED = "\u001B[31m"; + + private final String ANSI_GREEN = "\u001B[32m"; + + private final String ANSI_YELLOW = "\u001B[33m"; + + @Test + void given0_whenRun_thenGreenLightPrinted(){ + setInput("0"); + + new TrafficLight().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[32m")); + } + + @Test + void given35_whenRun_thenYellowLightPrinted(){ + setInput("35"); + + new TrafficLight().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[33m")); + } + + @Test + void given54_whenRun_thenRedLightPrinted(){ + setInput("54"); + + new TrafficLight().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[31m")); + } + + @Test + void given863400_whenRun_thenDayIsOverPrinted(){ + setInput("863400"); + + new TrafficLight().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Day is over")); + } + + @Test + void givenFiveSecTimeFormat_whenRun_thenGreenLightPrinted(){ + setInput("23:25:05"); + + new TrafficLightExtraMod().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[32m")); + } + + @Test + void givenThirtyFiveSecTimeFormat_whenRun_thenYellowLightPrinted(){ + setInput("14:54:35"); + + new TrafficLightExtraMod().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[33m")); + } + + @Test + void givenFiftyFourSecTimeFormat_whenRun_thenRedLightPrinted(){ + setInput("07:56:54"); + + new TrafficLightExtraMod().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("\u001B[31m")); + } + + @Test + void givenNegativeNumber_whenRun_thenError(){ + setInput("-56"); + + new TrafficLight().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + @Test + void givenNaN_whenRun_thenError(){ + setInput("text"); + + new TrafficLight().run(); + printOut(); + removeFromOutput("Enter necessary amount of seconds"); + + Assertions.assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } +} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..7f654fce --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,70 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBase { + + private final String FILENAME = "testCustom.txt"; + + @Test + void givenFileName_whenRun_thenFileContentPrintOutFirstMode() { + new CustomFileReader().run1(FILENAME); + printOut(); + + assertEquals("Linkin park Halestorm The Pretty Reckless Disturbed", getOutputLines()[0]); + assertNotEquals("TestTestTest", getOutputLines()[0]); + } + + @Test + void givenIncorrectFileName_whenRun_thenExceptionThrownFirstMode(){ + String filenameIncorrect = "testCustom"; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run1(filenameIncorrect)); + } + + @Test + void givenFileName_whenRun_thenFileContentPrintOutSecondMode() { + new CustomFileReader().run2(FILENAME); + printOut(); + + assertEquals("Linkin park Halestorm The Pretty Reckless Disturbed", getOutputLines()[0]); + assertNotEquals("TestTestTest", getOutputLines()[0]); + } + + @Test + void givenIncorrectFileName_whenRun_thenExceptionThrownSecondMode(){ + String filenameIncorrect = "testCustom"; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run2(filenameIncorrect)); + } + + @Test + void givenFileName_whenRun_thenFileContentPrintOutThirdMode() { + new CustomFileReader().run3(FILENAME); + printOut(); + + assertEquals("Linkin park Halestorm The Pretty Reckless Disturbed", getOutputLines()[0]); + assertNotEquals("TestTestTest", getOutputLines()[0]); + } + + @Test + void givenIncorrectFileName_whenRun_thenExceptionThrownThirdMode(){ + String filenameIncorrect = "testCustom"; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run3(filenameIncorrect)); + } + + @Test + void givenEmptyFileName_whenRun_thenExceptionThrown(){ + String emptyName = " "; + + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run3(emptyName)); + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run2(emptyName)); + assertThrows(IllegalArgumentException.class,()-> new CustomFileReader().run1(emptyName)); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..197e49ca --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,18 @@ +package homework_4.singleton; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class SingletonTest extends UnitBase { + + @Test + void givenSingleton_whenRun_thenSimpleClassNameReturned() { + Singleton singleton = Singleton.getInstance(); + System.out.println(singleton.getClass().getSimpleName()); + + assertEquals("Singleton created", getOutputLines()[0]); + assertEquals("Singleton", getOutputLines()[1]); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..ca8b2775 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,40 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomRegexMatcherTest extends UnitBase { + + @Test + void givenMatchingString_whenRun_thenTrueReturned() { + setInput("KissKiss#1"); + + new CustomRegexMatcher().run(); + printOut(); + + Assertions.assertEquals("true", getOutput()); + } + + @Test + void givenTooShortString_whenRun_thenFalseReturned() { + setInput("test"); + + new CustomRegexMatcher().run(); + printOut(); + + Assertions.assertEquals("false",getOutput()); + } + + @Test + void givenNotMatchingString_whenRun_thenFalseReturned() { + setInput("test1test1"); + + new CustomRegexMatcher().run(); + printOut(); + + Assertions.assertEquals("false", getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..1bbbbec4 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,60 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + + @Test + void givenValidInput_whenRun_thenResultPrinted() { + setInput("2 2"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("4", getOutput()); + } + + @Test + void givenNegativeNumbers_whenRun_thenError() { + setInput("-1 -1"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } + + @Test + void givenNotFullInput_whenRun_thenError(){ + setInput("1 "); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } + + @Test + void givenString_whenRun_thenError(){ + setInput("t t"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } + + @Test + void givenMoreParameters_whenRun_thenError(){ + setInput("1 2 3"); + + new PowerOfNumber().run(); + printOut(); + + Assertions.assertEquals("Only 2 non-negative integers are allowed", getOutput()); + } +} \ No newline at end of file