diff --git a/README.md b/README.md index 5d686e9f..df194332 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,23 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Asadulaev Gamzat* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/traffic_light) | The app that reads the time from the console (seconds/hh:mm:ss) and calculates the output color of the traffic light | +| | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/pyramid_printer) | The app that prints a pyramid based on user input | +| | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_2/random_chars_table) | The app that reads length, width, strategy from the console generates the table and prints even/odd letters | +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_3) | Immutable Class "Book" | +| HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/custom_file_reader) |The app that reads the file in different ways and prints the text without(, .) | +| | [CustomSingleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/singleton) | Custom Singleton | +| | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_4/custom_annotation) | Custom Annotation | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/power_of_number) | The app that reads the number from the console and raises it to the power | +| | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_5/custom_regex_matcher) | The app that reads the number from the console and checks it for validity | +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_6/map_problems_generator) | | +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_7) | Custom functional interface that transform Kitten to Cat | +| CP | [Battleship](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/GamzatAsadulaev/src/main/java/homework_7/course_project_battleship) | Course project "Battleship" | -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) + +[CodingBat](https://codingbat.com/done?user=asadulaevgamzat@gmail.com&tag=2887423202) \ No newline at end of file diff --git a/build.gradle b/build.gradle index b91dc843..e63f1244 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,12 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.0' + testImplementation 'org.hamcrest:hamcrest:2.2' + testImplementation 'org.hamcrest:hamcrest-library:2.2' + + compileOnly 'org.projectlombok:lombok:1.18.20' + annotationProcessor 'org.projectlombok:lombok:1.18.20' } test { diff --git a/src/main/java/course_project/battleship/Main.java b/src/main/java/course_project/battleship/Main.java new file mode 100644 index 00000000..86385404 --- /dev/null +++ b/src/main/java/course_project/battleship/Main.java @@ -0,0 +1,11 @@ +package course_project.battleship; + + +import course_project.battleship.game.Game; + +public class Main { + + public static void main(String[] args) { + new Game().run(); + } +} diff --git a/src/main/java/course_project/battleship/controller/AIController.java b/src/main/java/course_project/battleship/controller/AIController.java new file mode 100644 index 00000000..285595a3 --- /dev/null +++ b/src/main/java/course_project/battleship/controller/AIController.java @@ -0,0 +1,17 @@ +package course_project.battleship.controller; + + +import course_project.battleship.player.Player; + +public class AIController implements PlayerController { + + @Override + public void placeShips(Player player) { + throw new UnsupportedOperationException(); + } + + @Override + public void makeTurns(Player player1, Player player2) { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/course_project/battleship/controller/HumanController.java b/src/main/java/course_project/battleship/controller/HumanController.java new file mode 100644 index 00000000..be50a347 --- /dev/null +++ b/src/main/java/course_project/battleship/controller/HumanController.java @@ -0,0 +1,52 @@ +package course_project.battleship.controller; + +import course_project.battleship.game.GameRule; +import course_project.battleship.player.Player; +import course_project.battleship.utils.*; + + +public class HumanController implements PlayerController { + + @Override + public void placeShips(Player player) { + System.out.println(player.getName() + " choose the ship placement mode:\n1.Manually\n2.Randomly"); + int setupMode = Menu.getInt(2); + if (setupMode == 1) { + new ManualShipPlacement().placeShips(player); + } else { + new RandomShipPlacement().placeShips(player); + } + + System.out.println("Ships are placed!\n"); + } + + public void makeTurns(Player player1, Player player2) { + System.out.println("Your field: "); + Display.drawField(player1.getBattlefield()); + + while (true) { + System.out.println(); + System.out.println("" + player1.getName() + ", please, make your turn."); + Display.drawField(player1.getMonitorField()); + + Coordinate coordinate = Menu.createCoordinate(); + + if (coordinate == null || !Validator.isValidCoordinate(coordinate)) { + continue; + } + + if (!player1.makeTurn(player2, + coordinate)) { + System.out.println("\nMiss! Your opponents turn!\n"); + break; + } + + if (GameRule.isWinCondition(player1)) { + break; + } +// display.clearConsole(); + } + } + + +} diff --git a/src/main/java/course_project/battleship/controller/PlayerController.java b/src/main/java/course_project/battleship/controller/PlayerController.java new file mode 100644 index 00000000..26f8257c --- /dev/null +++ b/src/main/java/course_project/battleship/controller/PlayerController.java @@ -0,0 +1,10 @@ +package course_project.battleship.controller; + +import course_project.battleship.player.Player; + +public interface PlayerController { + + void placeShips(Player player); + + void makeTurns(Player player1, Player player2); +} diff --git a/src/main/java/course_project/battleship/game/Game.java b/src/main/java/course_project/battleship/game/Game.java new file mode 100644 index 00000000..fe057ff1 --- /dev/null +++ b/src/main/java/course_project/battleship/game/Game.java @@ -0,0 +1,73 @@ +package course_project.battleship.game; + + +import course_project.battleship.controller.HumanController; +import course_project.battleship.controller.PlayerController; +import course_project.battleship.player.Human; +import course_project.battleship.player.Player; +import course_project.battleship.utils.Menu; + +import java.util.Scanner; + +public class Game { + private final GameMode gameMode = new GameMode(); + private static final Scanner scanner = new Scanner(System.in); + + public void run() { + System.out.println("----------SeaBattle---------"); + System.out.println("Choose Mode\n1. PvP\n2. PvE"); + + int mode = Menu.getInt(2); + if (mode == 1) { + gameMode.setMode(GameMode.Mode.PVP); + } else { + gameMode.setMode(GameMode.Mode.PVE); + } + startGame(); + } + + public void startGame() { + if (gameMode.getMode() == GameMode.Mode.PVP) { + playVsHuman(); + } else { + playVsComputer(); + } + } + + private void playVsHuman() { + System.out.println("Player 1, please, enter your name:"); + String playerName1 = scanner.nextLine(); + Player player1 = new Human(playerName1); + System.out.println("Player 2, please, enter your name:"); + String playerName2 = scanner.nextLine(); + Player player2 = new Human(playerName2); + + System.out.println("-----------------------------"); + + PlayerController playerController = new HumanController(); + playerController.placeShips(player1); + playerController.placeShips(player2); + + String winner; + + while (true) { + playerController.makeTurns(player1, player2); + if (GameRule.isWinCondition(player1)) { + winner = player1.getName(); + break; + } + playerController.makeTurns(player2, player1); + if (GameRule.isWinCondition(player2)) { + winner = player1.getName(); + break; + } + } + System.out.println(winner + " win this game!"); + } + + public void playVsComputer() { + throw new UnsupportedOperationException(); + } +} + + diff --git a/src/main/java/course_project/battleship/game/GameMode.java b/src/main/java/course_project/battleship/game/GameMode.java new file mode 100644 index 00000000..c2da32f7 --- /dev/null +++ b/src/main/java/course_project/battleship/game/GameMode.java @@ -0,0 +1,21 @@ +package course_project.battleship.game; + +public class GameMode { + private Mode mode; + + public GameMode() { + } + + public enum Mode { + PVP, + PVE + } + + public Mode getMode() { + return mode; + } + + public void setMode(Mode mode) { + this.mode = mode; + } +} diff --git a/src/main/java/course_project/battleship/game/GameRule.java b/src/main/java/course_project/battleship/game/GameRule.java new file mode 100644 index 00000000..42855c56 --- /dev/null +++ b/src/main/java/course_project/battleship/game/GameRule.java @@ -0,0 +1,21 @@ +package course_project.battleship.game; + + +import course_project.battleship.player.Player; +import course_project.battleship.utils.Position; + +public class GameRule { + private final static int WIN_STREAK = 20; + + public static boolean isWinCondition(Player player) { + int counter = 0; + for (int i = 0; i < player.getMonitorField().getField().length; i++) { + for (int j = 0; j < player.getMonitorField().getField().length; j++) { + if (player.getMonitorField().getField()[i][j].getState() == Position.State.HIT) { + counter++; + } + } + } + return counter >= WIN_STREAK; + } +} diff --git a/src/main/java/course_project/battleship/model/Field.java b/src/main/java/course_project/battleship/model/Field.java new file mode 100644 index 00000000..5bdc7cd4 --- /dev/null +++ b/src/main/java/course_project/battleship/model/Field.java @@ -0,0 +1,29 @@ +package course_project.battleship.model; + +import course_project.battleship.utils.Position; + +public class Field { + public static final int FILED_SIZE = 10; + private Position[][] field; + + public Field() { + this.field = new Position[FILED_SIZE][FILED_SIZE]; + initTable(); + } + + private void initTable() { + for (int i = 0; i < field.length; i++) { + for (int j = 0; j < field[i].length; j++) { + field[i][j] = new Position(); + } + } + } + + public Position[][] getField() { + return field; + } + + public void setField(Position[][] field) { + this.field = field; + } +} diff --git a/src/main/java/course_project/battleship/model/Ship.java b/src/main/java/course_project/battleship/model/Ship.java new file mode 100644 index 00000000..cae4efd4 --- /dev/null +++ b/src/main/java/course_project/battleship/model/Ship.java @@ -0,0 +1,46 @@ +package course_project.battleship.model; + +public class Ship { + private int deck; + private boolean isAlive; + + private int countHits = 1; + + public Ship(int deck) { + this.isAlive = true; + this.deck = deck; + } + + public boolean getDamage() { + if (countHits != deck) { + countHits++; + return true; + } + isAlive = false; + return false; + } + + public int getDeck() { + return deck; + } + + public void setDeck(int deck) { + this.deck = deck; + } + + public boolean isAlive() { + return isAlive; + } + + public void setAlive(boolean alive) { + isAlive = alive; + } + + public int getCountHits() { + return countHits; + } + + public void setCountHits(int countHits) { + this.countHits = countHits; + } +} diff --git a/src/main/java/course_project/battleship/player/Computer.java b/src/main/java/course_project/battleship/player/Computer.java new file mode 100644 index 00000000..ccfc5874 --- /dev/null +++ b/src/main/java/course_project/battleship/player/Computer.java @@ -0,0 +1,22 @@ +package course_project.battleship.player; + + +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; + +public class Computer extends Player { + + public Computer() { + super("Computer"); + } + + @Override + public boolean makeTurn(Player enemy, Coordinate coordinate) { + throw new UnsupportedOperationException(); + } + + @Override + public void placeShip(Coordinate coordinate, Ship ship, int direction) { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/course_project/battleship/player/Human.java b/src/main/java/course_project/battleship/player/Human.java new file mode 100644 index 00000000..fee5ef25 --- /dev/null +++ b/src/main/java/course_project/battleship/player/Human.java @@ -0,0 +1,69 @@ +package course_project.battleship.player; + +import course_project.battleship.model.Field; +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; +import course_project.battleship.utils.Position; + + +public class Human extends Player { + public Human(String name) { + super(name); + } + + public boolean makeTurn(Player enemy, Coordinate coordinate) { + if (enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()] + .getState() == Position.State.HIT || + this.getMonitorField().getField()[coordinate.getX()][coordinate.getY()] + .getState() == Position.State.MISS) { + System.out.println("\nYou have already hit this place!"); + return true; + } + if (enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()] + .getState() == Position.State.SHIP) { + + System.out.println("Hit!"); + + this.getMonitorField().getField()[coordinate.getX()][coordinate.getY()].setState(Position.State.HIT); + enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()].setState(Position.State.HIT); + + Ship ship = enemy.getBattlefield().getField()[coordinate.getX()][coordinate.getY()].getShip(); + + if (!ship.getDamage()) { + System.out.println("\nThe " + ship.getDeck() + "-deck ship was destroyed!"); + } + + fillAroundHitPlace(coordinate, enemy.getBattlefield(), this.getMonitorField()); + } else { + this.getMonitorField().getField()[coordinate.getX()][coordinate.getY()] + .setState(Position.State.MISS); + return false; + } + return true; + } + + @Override + public void placeShip(Coordinate coordinate, Ship ship, int direction) { + for (int i = 0; i < ship.getDeck(); i++) { + if (direction == 1) { + getBattlefield().getField()[coordinate.getX()] + [coordinate.getY() + i].addShip(ship); + } else { + getBattlefield().getField()[coordinate.getX() + i][coordinate.getY()].addShip(ship); + } + } + } + + public void fillAroundHitPlace(Coordinate coordinate, Field battlefield, Field monitorField) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + int xi = Math.min(Math.max((coordinate.getX() + (j - 1)), 0), monitorField.getField().length - 1); + int yi = Math.min(Math.max((coordinate.getY() + (i - 1)), 0), monitorField.getField()[i].length - 1); + if (monitorField.getField()[xi][yi].getState() == Position.State.EMPTY && + battlefield.getField()[xi][yi].getState() == Position.State.EMPTY) { + monitorField.getField()[xi][yi].setState(Position.State.POINT); + } + } + } + } +} diff --git a/src/main/java/course_project/battleship/player/Player.java b/src/main/java/course_project/battleship/player/Player.java new file mode 100644 index 00000000..eaa5237a --- /dev/null +++ b/src/main/java/course_project/battleship/player/Player.java @@ -0,0 +1,47 @@ +package course_project.battleship.player; + + +import course_project.battleship.model.Field; +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; + +public abstract class Player { + private String name; + private Field battlefield; + private Field monitorField; + + + public Player(String name) { + this.name = name; + battlefield = new Field(); + monitorField = new Field(); + } + + public abstract boolean makeTurn(Player enemy, Coordinate coordinate); + + public abstract void placeShip(Coordinate coordinate, Ship ship, int direction); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Field getBattlefield() { + return battlefield; + } + + public void setBattlefield(Field battlefield) { + this.battlefield = battlefield; + } + + public Field getMonitorField() { + return monitorField; + } + + public void setMonitorField(Field monitorField) { + this.monitorField = monitorField; + } +} diff --git a/src/main/java/course_project/battleship/utils/Coordinate.java b/src/main/java/course_project/battleship/utils/Coordinate.java new file mode 100644 index 00000000..3359c776 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Coordinate.java @@ -0,0 +1,43 @@ +package course_project.battleship.utils; + + +import java.util.Objects; + +public class Coordinate { + private int x; + private int y; + + public Coordinate(int x, int y) { + this.x = x; + this.y = y; + } + + public int getX() { + return x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return y; + } + + public void setY(int y) { + this.y = y; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Coordinate that = (Coordinate) o; + return x == that.x && y == that.y; + } + + @Override + public int hashCode() { + return Objects.hash(x, y); + } +} diff --git a/src/main/java/course_project/battleship/utils/Display.java b/src/main/java/course_project/battleship/utils/Display.java new file mode 100644 index 00000000..6e01daf9 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Display.java @@ -0,0 +1,47 @@ +package course_project.battleship.utils; + + +import course_project.battleship.model.Field; + +import java.io.IOException; + +public final class Display { + + private static final String COLUMNS = " 1 2 3 4 5 6 7 8 9 10"; + + private Display(){} + + public static void drawField(Field field) { + System.out.println(COLUMNS); + for (int i = 0; i < field.getField().length; i++) { + System.out.print((char) (i + 65) + " "); + for (int j = 0; j < field.getField()[1].length; j++) { + if (field.getField()[j][i].getState() == Position.State.SHIP) { + System.out.print("+ "); + } else if (field.getField()[j][i].getState() == Position.State.HIT) { + System.out.print("X "); + } else if (field.getField()[j][i].getState() == Position.State.MISS) { + System.out.print("@ "); + } else if (field.getField()[j][i].getState() == Position.State.POINT) { + System.out.print("* "); + } else { + System.out.print("- "); + } + } + System.out.println(); + } + } + + public static void clearConsole() { + String os = System.getProperty("os.name").toLowerCase(); + try { + if (os.contains("win")) { + new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); + } else if (os.contains("nix") || os.contains("nux")) { + new ProcessBuilder("terminal", "/c", "clear").inheritIO().start().waitFor(); + } + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/course_project/battleship/utils/ManualShipPlacement.java b/src/main/java/course_project/battleship/utils/ManualShipPlacement.java new file mode 100644 index 00000000..e9a8b685 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/ManualShipPlacement.java @@ -0,0 +1,44 @@ +package course_project.battleship.utils; + +import course_project.battleship.model.Ship; +import course_project.battleship.player.Player; + +public class ManualShipPlacement implements ShipPlacement { + + @Override + public void placeShips(Player player) { + int deck = 4; + int counter = 1; + for (int i = 1; i <= 4; i++) { + while (counter <= i) { + System.out.println(player.getName() + ", place your " + deck + "-deck ship on the field:"); + Display.drawField(player.getBattlefield()); + + Coordinate coordinate = Menu.createCoordinate(); + if (coordinate == null || !Validator.isValidCoordinate(coordinate)) { + System.out.println("\nEntered Invalid coordinate!\n"); + continue; + } + + int direction = Menu.createDirection(); + if (!Validator.isValidDirection(direction)) { + System.out.println("\nEntered Invalid value for direction!\n"); + continue; + } + + if (!Validator.isAvailable(coordinate, deck, direction, player.getBattlefield())) { + System.out.println("Wrong coordinates or direction!"); + continue; + } + + Ship ship = new Ship(deck); + + player.placeShip(coordinate, ship, direction); + counter++; + } + deck--; + counter = 1; + } + } + +} diff --git a/src/main/java/course_project/battleship/utils/Menu.java b/src/main/java/course_project/battleship/utils/Menu.java new file mode 100644 index 00000000..1ad2de02 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Menu.java @@ -0,0 +1,67 @@ +package course_project.battleship.utils; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public final class Menu { + private static final Scanner scanner = new Scanner(System.in); + + private Menu() { + } + + public static Coordinate createCoordinate() { + System.out.println("Please, enter the number:"); + int x; + try { + x = scanner.nextInt() - 1; + } catch (InputMismatchException e) { + return null; + } finally { + scanner.nextLine(); + } + + System.out.println("Please, enter the char:"); + String str = scanner.nextLine().toUpperCase(); + if (str.length() != 1) { + return null; + } + + int y = (str.charAt(0)) - 65; + + return new Coordinate(x, y); + } + + + public static int createDirection() { + System.out.println("Choose direction: \n1. Vertical\n2. Horizontal"); + + int direction; + try { + direction = scanner.nextInt(); + } catch (InputMismatchException e) { + return -1; + } finally { + scanner.nextLine(); + } + + return direction; + } + + public static int getInt(int range) { + int number; + while (true) { + try { + number = scanner.nextInt(); + if (number > range || number < 1) { + throw new InputMismatchException(); + } + break; + } catch (InputMismatchException ignored) { + System.out.println("Entered invalid value!"); + } finally { + scanner.nextLine(); + } + } + return number; + } +} diff --git a/src/main/java/course_project/battleship/utils/Position.java b/src/main/java/course_project/battleship/utils/Position.java new file mode 100644 index 00000000..c4ccb8fa --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Position.java @@ -0,0 +1,43 @@ +package course_project.battleship.utils; + + +import course_project.battleship.model.Ship; + +public class Position { + private Ship ship; + private State state; + + public enum State { + EMPTY, + SHIP, + HIT, + MISS, + POINT + } + + public Position() { + state = State.EMPTY; + } + + public Position(Ship ship) { + this.ship = ship; + this.state = State.SHIP; + } + + public void addShip(Ship ship) { + this.ship = ship; + state = State.SHIP; + } + + public Ship getShip() { + return ship; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } +} diff --git a/src/main/java/course_project/battleship/utils/RandomShipPlacement.java b/src/main/java/course_project/battleship/utils/RandomShipPlacement.java new file mode 100644 index 00000000..2a1884c2 --- /dev/null +++ b/src/main/java/course_project/battleship/utils/RandomShipPlacement.java @@ -0,0 +1,36 @@ +package course_project.battleship.utils; + +import course_project.battleship.model.Ship; +import course_project.battleship.player.Player; + +import java.util.Random; + +public class RandomShipPlacement implements ShipPlacement { + private final Random random = new Random(); + + @Override + public void placeShips(Player player) { + int deck = 4; + int counter = 1; + for (int i = 1; i <= 4; i++) { + while (counter <= i) { + int x = random.nextInt(10); + int y = random.nextInt(10); + Coordinate coordinate = new Coordinate(x, y); + + int direction = random.nextInt(2) + 1; + + if (!Validator.isAvailable(coordinate, deck, direction, player.getBattlefield())) { + continue; + } + + Ship ship = new Ship(deck); + player.placeShip(coordinate, ship, direction); + + counter++; + } + deck--; + counter = 1; + } + } +} diff --git a/src/main/java/course_project/battleship/utils/ShipPlacement.java b/src/main/java/course_project/battleship/utils/ShipPlacement.java new file mode 100644 index 00000000..ef2455ff --- /dev/null +++ b/src/main/java/course_project/battleship/utils/ShipPlacement.java @@ -0,0 +1,9 @@ +package course_project.battleship.utils; + +import course_project.battleship.player.Player; + +import java.util.Random; + +public interface ShipPlacement { + void placeShips(Player player); +} diff --git a/src/main/java/course_project/battleship/utils/Validator.java b/src/main/java/course_project/battleship/utils/Validator.java new file mode 100644 index 00000000..9fe2bfab --- /dev/null +++ b/src/main/java/course_project/battleship/utils/Validator.java @@ -0,0 +1,81 @@ +package course_project.battleship.utils; + + +import course_project.battleship.model.Field; + +public final class Validator { + + private Validator(){} + + public static boolean isAvailable(Coordinate coordinate, int deck, int direction, Field battlefield) { + if (!isOutOfBound(coordinate, deck, direction, battlefield)) { + return false; + } + + if (battlefield.getField()[coordinate.getX()][coordinate.getY()].getState() == Position.State.SHIP) { + return false; + } + + if (!checkAroundTheShip(coordinate, direction, deck, battlefield)) { + return false; + } + + return true; + } + + public static boolean isValidDirection(int direction) { + return 2 >= direction && direction >= 1; + } + + public static boolean isOutOfBound(Coordinate coordinate, int deck, int direction, Field battlefield) { + if (direction == 1) { + if (coordinate.getY() + deck > battlefield.getField().length) { + return false; + } + } + if (direction == 2) { + if (coordinate.getX() + deck > battlefield.getField()[0].length) { + return false; + } + } + return true; + } + + public static boolean checkAroundTheShip(Coordinate coordinate, int direction, int deck, Field battlefield) { + for (int i = 0; i < deck; i++) { + if (direction == 1) { + if (!checkAroundTheCoordinate(coordinate.getX(), (coordinate.getY() + i), battlefield)) { + return false; + } + } else { + if (!checkAroundTheCoordinate((coordinate.getX() + i), coordinate.getY(), battlefield)) { + return false; + } + } + } + return true; + } + + + + public static boolean isValidCoordinate(Coordinate coordinate) { + if (coordinate.getX() < 0 || coordinate.getX() >= 10 || + coordinate.getY() < 0 || coordinate.getY() >= 10) { + return false; + } + return true; + } + + public static boolean checkAroundTheCoordinate(int x, int y, Field battlefield) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + int xi = Math.min(Math.max((x + (j - 1)), 0), battlefield.getField().length - 1); + int yi = Math.min(Math.max((y + (i - 1)), 0), battlefield.getField()[i].length - 1); + if (battlefield.getField()[xi][yi].getState() != Position.State.EMPTY) { + return false; + } + } + } + return true; + } +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..56de3156 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,9 +1,13 @@ package homework_1; public class Main { - - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - + public static void main(String[] args) { + for (String s : args) { + if(s.equals("ошибка")){ + System.err.println("Тревога!"); + break; + } + System.out.println(s + ": " + s.length()); + } + } } diff --git a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java new file mode 100644 index 00000000..c355c318 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java @@ -0,0 +1,47 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ExtraPyramidPrinter { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run(String... args) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("Please input number"); + int rows = Integer.parseInt(reader.readLine()); + printPyramid(rows, args); + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter!" + ANSI_RESET); + + } + } + + void printPyramid(int rows, String[] args) { + if (rows < 0 || args.length == 0) { + System.out.println("arr + length " + args.length); + throw new IllegalArgumentException(); + } + + if (args[0].equalsIgnoreCase("invert")) { + for (int i = rows; i >= 1; --i) { + for (int j = 1; j <= i; ++j) { + System.out.print("x"); + } + System.out.println(); + } + } else { + for (int i = 1; i <= rows; i++) { + for (int j = 0; j < i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } + } +} diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..e50e37eb --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer; + +public class Main { + public static void main(String[] args) { + new PyramidPrinter().run(); + } +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java new file mode 100644 index 00000000..949bd1db --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,35 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("Please input number"); + int rows = Integer.parseInt(reader.readLine()); + printPyramid(rows); + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter!" + ANSI_RESET); + } + } + + void printPyramid(int rows) { + if(rows < 0){ + throw new IllegalArgumentException(); + } + for (int i = 1; i <= rows; i++) { + for (int j = 0; j < i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } +} + diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..682fe366 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,7 @@ +package homework_2.random_chars_table; + +public class Main { + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/PrintChars.java b/src/main/java/homework_2/random_chars_table/PrintChars.java new file mode 100644 index 00000000..c634fa36 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/PrintChars.java @@ -0,0 +1,54 @@ +package homework_2.random_chars_table; + +import java.util.ArrayList; +import java.util.List; + +public class PrintChars { + + void print(char[][] table, String strategy) { + if (strategy.equalsIgnoreCase("even")) { + printEvenChars(table); + } else if (strategy.equalsIgnoreCase("odd")) { + printOddChars(table); + } else { + throw new IllegalArgumentException(); + } + } + + void print(char[][] chars) { + for (char[] row : chars) { + System.out.print("| "); + for (char column : row) { + System.out.print(column + " | "); + } + System.out.println(); + } + } + + void printEvenChars(char[][] table) { + List evenChars = new ArrayList<>(); + for (char[] row : table) { + for (char column : row) { + if (column % 2 == 0) { + evenChars.add(column); + } + } + System.out.println("Even letters - " + + evenChars.toString().replaceAll("[\\[\\]]", "")); + } + } + + void printOddChars(char[][] table) { + List evenChars = new ArrayList<>(); + for (char[] row : table) { + for (char column : row) { + if (column % 2 != 0) { + evenChars.add(column); + } + } + System.out.println("Even letters - " + + evenChars.toString().replaceAll("[\\[\\]]", "")); + } + } + +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..d5bf2466 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,36 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.print("Enter the length, width and strategy(\"even\" or \"odd\")\n-> "); + String[] arr = reader.readLine().split(" "); + + int length = Integer.parseInt(arr[0]); + int width = Integer.parseInt(arr[1]); + String strategy = arr[2]; + + char[][] table = new RandomCharsTableCreator().create(length, width); + + PrintChars printChars = new PrintChars(); + + printChars.print(table); + printChars.print(table, strategy); + + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]" + ANSI_RESET); + } + } + +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java new file mode 100644 index 00000000..3d42b8f9 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -0,0 +1,24 @@ +package homework_2.random_chars_table; + +import java.util.Random; + +public class RandomCharsTableCreator { + private final Random random = new Random(); + + char[][] create(int length, int width) { + if (length < 1 || width < 1) { + throw new IllegalArgumentException(); + } + char[][] randomChars = new char[length][width]; + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + randomChars[i][j] = getRandomChar(); + } + } + return randomChars; + } + + private char getRandomChar() { + return (char) (random.nextInt(90 - 65 + 1) + 65); + } +} diff --git a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java new file mode 100644 index 00000000..aa3cefe1 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -0,0 +1,53 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ExtraTrafficLight { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run(int mode) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.print("Choose the mode:\n1 - seconds\n2 - hh:mm:ss\n-> "); +// int mode = Integer.parseInt(reader.readLine()); + int seconds = getSeconds(reader, mode); + + new PrintColor().print(seconds); + } catch (IOException e) { + e.printStackTrace(); + } catch (NumberFormatException e) { + System.out.println(ANSI_RED + "Only non-negative integers is allowed as passed parameter" + ANSI_RESET); + } catch (IllegalArgumentException e){ + System.out.println(ANSI_RED + e.getMessage() + ANSI_RESET); + + } + } + + private int getSeconds(BufferedReader reader, int mode) throws IOException { + int seconds; + if (mode == 1) { + System.out.print("Enter time in seconds: "); + seconds = Integer.parseInt(reader.readLine()); + + } else if (mode == 2) { + System.out.print("Enter time in the format(hh:mm:ss): "); + String[] arguments = reader.readLine().split(":"); + + int hh = Integer.parseInt(arguments[0]); + int mm = Integer.parseInt(arguments[1]); + int ss = Integer.parseInt(arguments[2]); + + if (hh < 0 || hh >= 24 || mm < 0 || mm >= 60 || ss < 0 || ss >= 60) { + throw new IllegalArgumentException("Entered time doesn't match the format!"); + } + + seconds = hh * 3600 + mm * 60 + ss; + } else { + throw new IllegalArgumentException("Invalid mode type!"); + } + return seconds; + } +} diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..fa033081 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,7 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args) { + new TrafficLight().run(); + } +} diff --git a/src/main/java/homework_2/traffic_light/PrintColor.java b/src/main/java/homework_2/traffic_light/PrintColor.java new file mode 100644 index 00000000..3636df12 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/PrintColor.java @@ -0,0 +1,31 @@ +package homework_2.traffic_light; + +public class PrintColor { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; + + void print(int seconds){ + + if (seconds < 0) { + throw new NumberFormatException(); + } + + if (seconds >= 86400) { + System.out.println(ANSI_RED + "The day is over!" + ANSI_RESET); + return; + } + + seconds %= 60; + + if (seconds < 35) { + System.out.println(ANSI_GREEN + "GREEN" + ANSI_RESET); + } else if (seconds < 40 || seconds >= 55) { + System.out.println(ANSI_YELLOW + "YELLOW" + ANSI_RESET); + } else { + System.out.println(ANSI_RED + "RED" + ANSI_RESET); + } + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..d3dfed48 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,26 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.print("Enter time in seconds: "); + int seconds = Integer.parseInt(reader.readLine()); + System.out.println(); + + new PrintColor().print(seconds); + + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(ANSI_RED + "Only 1 non-negative integer is allowed as passed parameter" + ANSI_RESET); + } + } +} diff --git a/src/main/java/homework_3/Book.java b/src/main/java/homework_3/Book.java new file mode 100644 index 00000000..e904e021 --- /dev/null +++ b/src/main/java/homework_3/Book.java @@ -0,0 +1,50 @@ +package homework_3; + +import java.util.Arrays; + +public final class Book { + + private final String title; + private final int year; + private final String[] authors; + + public Book(String name, int age, String... authors) { + this.title = name; + this.year = age; + this.authors = Arrays.copyOf(authors, authors.length); + } + + public Book(String name, String... authors) { + this.title = name; + this.year = 0; + this.authors = Arrays.copyOf(authors, authors.length); + } + + public Book(String name, int age) { + this.title = name; + this.year = age; + this.authors = new String[0]; + } + + public Book() { + this.title = ""; + this.year = 0; + this.authors = new String[0]; + } + + public String getTitle() { + return this.title; + } + + public int getYear() { + return this.year; + } + + public String[] getAuthors() { + return Arrays.copyOf(authors, authors.length); + } + + public Book changeTitle(String title) { + return new Book(title, year, Arrays.copyOf(authors, authors.length)); + } +} \ No newline at end of file diff --git a/src/main/java/homework_4/custom_annotation/FilePath.java b/src/main/java/homework_4/custom_annotation/FilePath.java new file mode 100644 index 00000000..c0d70ab1 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/FilePath.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface FilePath { + String path() default "src/main/resources/custom_file_reader/file.txt"; +} diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..2f4b5618 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,65 @@ +package homework_4.custom_file_reader; + +import homework_4.custom_annotation.FilePath; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Scanner; + +@FilePath +public class CustomFileReader { + private static final String FILE_PATH = CustomFileReader.class.getAnnotation(FilePath.class).path(); + + + public void run1() { + InputStream inputStream = CustomFileReader.class.getResourceAsStream("/custom_file_reader/file.txt"); + if (inputStream != null) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + String result = reader.readLine(); + printResult(result); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void run2() { + try (BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) { + String result = reader.readLine(); + printResult(result); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + public void run3() { + try (Scanner scanner = new Scanner(new File(FILE_PATH))) { + scanner.useDelimiter("[.,]"); + StringBuilder stringBuilder = new StringBuilder(); + while (scanner.hasNext()) { + stringBuilder.append(scanner.next()); + } + System.out.println(stringBuilder); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + //NIO + public void run4() { + Path path = Paths.get(FILE_PATH); + try (BufferedReader reader = Files.newBufferedReader(path)) { + String result = reader.readLine(); + printResult(result); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void printResult(String result) { + System.out.println(result.replaceAll("[.,]", "")); + } +} diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java new file mode 100644 index 00000000..17e8c99b --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,11 @@ +package homework_4.custom_file_reader; + +public class Main { + public static void main(String[] args) { + CustomFileReader customFileReader = new CustomFileReader(); + customFileReader.run1(); + customFileReader.run2(); + customFileReader.run3(); + customFileReader.run4(); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..d95daa39 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +public class Singleton { + private static Singleton instance; + + private Singleton(){} + + + public static Singleton getInstance(){ + if(instance == null){ + instance = new Singleton(); + } + return instance; + } +} diff --git a/src/main/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..a413e5a0 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,16 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; + +public class CustomRegexMatcher { + + public boolean isValidPhoneNumber(String number){ + return number.matches("\\+?[7|8]\\s?[(-.\\s]?\\d{3}[)-.\\s]?\\s?\\d{3}[-.\\s]?\\d{2}[-.\\s]?\\d{2}"); + } + + public void run() { + System.out.print("Enter a phone number: "); + Scanner scanner = new Scanner(System.in); + System.out.println("Entered the phone number is valid: " + (isValidPhoneNumber(scanner.nextLine()))); + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..f8b52c06 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..930f2040 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..6e3c32d6 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,34 @@ +package homework_5.power_of_number; + +import java.util.Scanner; + +public class PowerOfNumber { + + public int pow(int number, int pow) { + if(number < 0 || pow < 0){ + throw new IllegalArgumentException(); + } + if(pow == 0){ + return 1; + } + if(pow == 1) { + return number; + } + return number * pow(number, --pow); + } + + public void run() { + System.out.print("Enter two numbers(number, pow): "); + Scanner scanner = new Scanner(System.in); + try { + String str = scanner.nextLine(); + String[] split = str.split(",? "); + if (split.length != 2) { + throw new IllegalArgumentException(); + } + System.out.println("Result: " + pow(Integer.parseInt(split[0]), Integer.parseInt(split[1]))); + } catch (Exception e){ + System.out.println("Only 2 non-negative integers are allowed"); + } + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java new file mode 100644 index 00000000..5cf43f74 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,39 @@ +package homework_6.map_problems_generator; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +import java.util.Objects; + +public class MapProblemsGenerator { + + @AllArgsConstructor + @Getter + @Setter + public static class MapProblemsCollisionGenerator { + private int id; + private String name; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsCollisionGenerator that = (MapProblemsCollisionGenerator) o; + return id == that.id && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return 1; + } + } + + @Data + @AllArgsConstructor + public static class MapProblemsMutableGenerator { + private int id; + private String name; + } +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..8b455d92 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,10 @@ +package homework_7; + +import homework_7.animals.Cat; +import homework_7.animals.Kitten; + +@FunctionalInterface +public interface KittenToCatFunction { + + R grow(T t); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..6067b6f2 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,17 @@ +package homework_7; + +import homework_7.animals.Cat; +import homework_7.animals.Kitten; + +public class Main { + public static void main(String[] args) { + Kitten kitten = new Kitten("Simon", 1, 0.5); + System.out.println(kitten); + + KittenToCatFunction function = (k -> new Cat(k.getName(), + k.getAge() + 1, k.getWeight() * 3)); + + Cat cat = function.grow(kitten); + System.out.println(cat); + } +} diff --git a/src/main/java/homework_7/animals/Cat.java b/src/main/java/homework_7/animals/Cat.java new file mode 100644 index 00000000..0d97b9a9 --- /dev/null +++ b/src/main/java/homework_7/animals/Cat.java @@ -0,0 +1,12 @@ +package homework_7.animals; + + +import lombok.*; + +@Data +@AllArgsConstructor +public class Cat { + private String name; + private int age; + private double weight; +} diff --git a/src/main/java/homework_7/animals/Kitten.java b/src/main/java/homework_7/animals/Kitten.java new file mode 100644 index 00000000..dd56152d --- /dev/null +++ b/src/main/java/homework_7/animals/Kitten.java @@ -0,0 +1,14 @@ +package homework_7.animals; + + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class Kitten { + private String name; + private int age; + private double weight; + +} diff --git a/src/main/resources/custom_file_reader/file.txt b/src/main/resources/custom_file_reader/file.txt new file mode 100644 index 00000000..d2ff0b7d --- /dev/null +++ b/src/main/resources/custom_file_reader/file.txt @@ -0,0 +1 @@ +Hello,,,,, World......!, \ No newline at end of file diff --git a/src/test/java/course_project/battleship/player/HumanTest.java b/src/test/java/course_project/battleship/player/HumanTest.java new file mode 100644 index 00000000..c04d9749 --- /dev/null +++ b/src/test/java/course_project/battleship/player/HumanTest.java @@ -0,0 +1,37 @@ +package course_project.battleship.player; + +import course_project.battleship.model.Ship; +import course_project.battleship.utils.Coordinate; +import course_project.battleship.utils.Position; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class HumanTest { + + @Test + void testPlaceShipMethod() { + Human human = new Human("Test"); + Coordinate coordinate = new Coordinate(5, 5); + int direction = 2; + Ship ship = new Ship(4); + human.placeShip(coordinate, ship, direction); + assertNotNull(human.getBattlefield().getField()[coordinate.getX()][coordinate.getY()].getShip()); + } + + @Test + void testMakeTurnMethod() { + Human human = new Human("Test"); + Coordinate coordinate = new Coordinate(5, 5); + Human enemy = new Human("enemy"); + int direction = 2; + Ship ship = new Ship(4); + enemy.placeShip(coordinate, ship, direction); + human.makeTurn(enemy, coordinate); + assertEquals(Position.State.HIT, human.getMonitorField() + .getField()[coordinate.getX()][coordinate.getY()].getState()); + assertEquals(Position.State.HIT, enemy.getBattlefield() + .getField()[coordinate.getX()][coordinate.getY()].getState()); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship/utils/ValidatorTest.java b/src/test/java/course_project/battleship/utils/ValidatorTest.java new file mode 100644 index 00000000..156ae3b5 --- /dev/null +++ b/src/test/java/course_project/battleship/utils/ValidatorTest.java @@ -0,0 +1,44 @@ +package course_project.battleship.utils; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +class ValidatorTest extends UnitBase { + + @ParameterizedTest + @MethodSource("invalidCoordinates") + void givenInvalidCoordinate_whenRun_thenCheckReturn(Coordinate coordinate) { + assertFalse(Validator.isValidCoordinate(coordinate)); + } + + @ParameterizedTest + @MethodSource("invalidDirections") + void givenInvalidCoordinate_whenRun_then_checkReturn(int direction) { + assertFalse(Validator.isValidDirection(direction)); + } + + private static Stream invalidCoordinates() { + return Stream.of( + arguments(new Coordinate(12, 5)), + arguments(new Coordinate(-5, 5)), + arguments(new Coordinate(5, 12)), + arguments(new Coordinate(5, -5)) + ); + } + + private static Stream invalidDirections() { + return Stream.of( + arguments(3), + arguments(-1) + ); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java new file mode 100644 index 00000000..ed322c9c --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java @@ -0,0 +1,114 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ExtraPyramidPrinterTest extends UnitBase { + + @Test + void given_1_whenRun_then_printPyramid() { + setInput("1"); + + new ExtraPyramidPrinter().run(""); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given_1_whenRun_then_printInvertPyramid() { + setInput("1"); + + new ExtraPyramidPrinter().run("invert"); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given_3_whenRun_then_printPyramid() { + setInput("3"); + + new ExtraPyramidPrinter().run(""); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + } + + @Test + void given_3_whenRun_then_printInvertPyramid() { + setInput("3"); + + new ExtraPyramidPrinter().run("invert"); + + removeFromOutput("Please input number"); + + assertEquals("xxx", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("x", getOutputLines()[2]); + } + + @Test + void given_0_whenRun_then_printNothing() { + setInput("0"); + + new ExtraPyramidPrinter().run(""); + + removeFromOutput("Please input number"); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void given_emptyArgument_whenRun_then_printErrorMessage() { + setInput(""); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_smth_whenRun_then_printErrorMessage() { + setInput("abc"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_floatingPointArgument_whenRun_then_printErrorMessage() { + setInput("0.5"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_tooBigNumber_whenRun_then_printErrorMessage() { + setInput("9999999999"); + + new ExtraPyramidPrinter().run(""); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..1ded1901 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,90 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterTest extends UnitBase { + + @Test + void given_1_whenRun_then_printPyramid() { + setInput("1"); + + new PyramidPrinter().run(); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given_3_whenRun_then_printPyramid() { + setInput("3"); + + new PyramidPrinter().run(); + + removeFromOutput("Please input number"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + } + + @Test + void given_0_whenRun_then_printNothing() { + setInput("0"); + + new PyramidPrinter().run(); + + removeFromOutput("Please input number"); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void given_emptyArgument_whenRun_then_printErrorMessage() { + setInput(""); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_smth_whenRun_then_printErrorMessage() { + setInput("abc"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_floatingPointArgument_whenRun_then_printErrorMessage() { + setInput("0.5"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + + @Test + void given_tooBigNumber_whenRun_then_printErrorMessage() { + setInput("9999999999"); + + new PyramidPrinter().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter!")); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..0c5ba87b --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,155 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RandomCharsTableTest extends UnitBase { + + + + // Hamcrest + @Test + void given_lengthWidth_whenRun_then_printChars() { + setInput("4 4 even"); + + new RandomCharsTable().run(); + removeFromOutput("Enter the length, width and strategy(\"even\" or \"odd\")\n-> "); + removeFromOutput("Even letters - "); + removeFromOutput(","); + removeFromOutput(" "); + removeFromOutput("|"); + + List strings = new ArrayList<>(Arrays.asList(getOutputLines())); + + assertThat(strings, everyItem(matchesPattern("[A-Z]+"))); + } + + + @Test + void given_negativeIntegerFirstArgument_whenRun_then_printErrorMessage() { + setInput("-2 2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_negativeIntegerSecondArgument_whenRun_then_printErrorMessage() { + setInput("2 -2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_smthStrategy_whenRun_then_printErrorMessage() { + setInput("2 2 abc"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_smthFirstArgument_whenRun_then_printErrorMessage() { + setInput("b 2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_smthSecondArgument_whenRun_then_printErrorMessage() { + setInput("2 b even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_floatingPointFirstArgument_whenRun_then_printErrorMessage() { + setInput("0.2 2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_floatingPointSecondArgument_whenRun_then_printErrorMessage() { + setInput("2 0.2 even"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + + @Test + void given_moreThanThreeArguments_whenRun_then_printErrorMessage() { + setInput("4 4 4 odd"); + + new RandomCharsTable().run(); + + assertTrue(getOutput().contains("Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]")); + } + + @Test + void given_lengthWidthStrategy_whenRun_then_printEvenChars() { + setInput("4 4 even"); + + new RandomCharsTable().run(); + removeFromOutput("Even letters - "); + removeFromOutput(","); + removeFromOutput(" "); + + String str = getOutputLines()[getOutputLines().length - 1]; + + for (int i = 0; i < str.length(); i++) { + assertEquals(0, str.charAt(i) % 2); + } + } + + + @Test + void given_lengthWidthStrategy_whenRun_then_printOddChars() { + setInput("4 4 odd"); + + new RandomCharsTable().run(); + removeFromOutput("Even letters - "); + removeFromOutput(","); + removeFromOutput(" "); + + String str = getOutputLines()[getOutputLines().length - 1]; + + for (int i = 0; i < str.length(); i++) { + assertEquals(1, str.charAt(i) % 2); + } + } + + + + +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java new file mode 100644 index 00000000..d6f25558 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java @@ -0,0 +1,126 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ExtraTrafficLightTest extends UnitBase { + + @Test + void given_minSeconds_whenRun_then_printColor() { + setInput("0"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_maxSeconds_whenRun_then_printColor() { + setInput("86399"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_5_whenRun_then_printColor() { + setInput("5"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_35_whenRun_then_printColor() { + setInput("35"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_54_whenRun_then_printColor() { + setInput("54"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("RED")); + } + + + @Test + void given_86401_whenRun_then_printErrorMessage() { + setInput("86401"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("The day is over!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("Only non-negative integers is allowed as passed parameter")); + } + + @Test + void given_string_whenRun_then_printErrorMessage() { + setInput("abc"); + + new ExtraTrafficLight().run(1); + + assertTrue(getOutput().contains("Only non-negative integers is allowed as passed parameter")); + } + + @Test + void given_minTime_whenRun_then_printColor() { + setInput("00:00:00"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_maxTime_whenRun_then_printColor() { + setInput("23:59:59"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_timeOutOfRange_whenRun_then_printErrorMessage() { + setInput("24:00:00"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("Entered time doesn't match the format!")); + } + + @Test + void given_negativeTime_whenRun_then_printErrorMessage() { + setInput("-23:00:00"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("Entered time doesn't match the format!")); + } + @Test + void given_timeWithStringArgument_whenRun_then_printErrorMessage() { + setInput("23:00:b"); + + new ExtraTrafficLight().run(2); + + assertTrue(getOutput().contains("Only non-negative integers is allowed as passed parameter")); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java new file mode 100644 index 00000000..8d720097 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,96 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + + + +class TrafficLightTest extends UnitBase { + + @Test + void given_minSeconds_whenRun_then_printColor() { + setInput("0"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_maxSeconds_whenRun_then_printColor() { + setInput("86399"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_5_whenRun_then_printColor() { + setInput("5"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void given_35_whenRun_then_printColor() { + setInput("35"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void given_54_whenRun_then_printColor() { + setInput("54"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("RED")); + } + + + @Test + void given_86401_whenRun_then_printErrorMessage() { + setInput("86401"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("The day is over!")); + } + + @Test + void given_negativeInteger_whenRun_then_printErrorMessage() { + setInput("-1"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + + + @Test + void given_string_whenRun_then_printErrorMessage() { + setInput("abc"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + @Test + void given_severalArguments_whenRun_then_printErrorMessage() { + setInput("2 2"); + + new TrafficLight().run(); + + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_3/BookTest.java b/src/test/java/homework_3/BookTest.java new file mode 100644 index 00000000..2c4bb771 --- /dev/null +++ b/src/test/java/homework_3/BookTest.java @@ -0,0 +1,21 @@ +package homework_3; + +import base.UnitBase; +import homework_2.traffic_light.TrafficLight; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class BookTest extends UnitBase { + @Test + void testImmutableClass() { + Book book1 = new Book("Test-Driven Java Development", 2015, " Viktor Farcic", + "Alex Garcia"); + Book book2 = book1.changeTitle("Test-Driven Java Development"); + assertNotEquals(book1, book2); + assertEquals("Test-Driven Java Development", book1.getTitle()); + assertEquals(book2.getTitle(), book1.getTitle()); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..5a98ce0c --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,14 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomAnnotationTest extends UnitBase { + @Test + void testAnnotation() { + assertEquals( "src/main/resources/custom_file_reader/file.txt", CustomFileReader.class.getAnnotation(FilePath.class).path()); + } +} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..7289106f --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,37 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBase { + CustomFileReader reader = new CustomFileReader(); + String expectedString = "Hello World!"; + + @Test + void testInputStreamReader() { + reader.run1(); + assertTrue(getOutput().contains(expectedString)); + } + + @Test + void testFileReader() { + reader.run2(); + assertTrue(getOutput().contains(expectedString)); + } + + @Test + void testScanner() { + reader.run3(); + assertTrue(getOutput().contains(expectedString)); + } + + @Test + void testNIO() { + reader.run4(); + assertTrue(getOutput().contains(expectedString)); + } + + +} \ No newline at end of file diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..8f0b39d9 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SingletonTest extends UnitBase { + + @Test + void testSingleton() { + Singleton instance = Singleton.getInstance(); + assertEquals(instance, Singleton.getInstance()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..8d29e214 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,54 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CustomRegexMatcherTest extends UnitBase { + + @ParameterizedTest + @MethodSource("validPhoneNumbers") + void testPhoneNumbers(String number) { + setInput(number); + new CustomRegexMatcher().run(); + assertTrue(getOutput().contains("true")); + } + + @ParameterizedTest + @MethodSource("invalidPhoneNumbers") + void testInvalidPhoneNumbers(String number) { + setInput(number); + new CustomRegexMatcher().run(); + assertTrue(getOutput().contains("false")); + } + + private static Stream validPhoneNumbers() { + return Stream.of( + Arguments.of("79001234567"), + Arguments.of("89001234567"), + Arguments.of("8(900)1234567"), + Arguments.of("+7 (900) 123-45-67"), + Arguments.of("8 900 123 45 67"), + Arguments.of("8-900-123-45-67"), + Arguments.of("8.900.123.45.67") + ); + } + + private static Stream invalidPhoneNumbers() { + return Stream.of( + Arguments.of("7 9 0 0 1 2 3 4 5 6 7"), + Arguments.of("9001234567777"), + Arguments.of("7__9001234567"), + Arguments.of("6(900)1234567"), + Arguments.of("+7 (900) 123-45-67"), + Arguments.of("8 9005 123 45 67"), + Arguments.of("8-900-123-45-6"), + Arguments.of("900.123.45.67.31") + ); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..69fd7637 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,59 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + + @Test + void given2_2_whenRun_then_print2ToThePowerOf2() { + setInput("2 2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("4")); + } + + + @Test + void given2_1_whenRun_then_print2ToThePowerOf1() { + setInput("2 1"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("2")); + } + + @Test + void given2_0_whenRun_then_print2ToThePowerOf0() { + setInput("2 0"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("1")); + } + + @Test + void given0_2_whenRun_then_print0ToThePowerOf2() { + setInput("0 2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("0")); + } + + @Test + void givenNegativeNumber_whenRun_then_printError() { + setInput("-2 2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } + + @Test + void givenNegativePow_whenRun_then_printError() { + setInput("2 -2"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } + + @Test + void givenString_whenRun_then_printError() { + setInput("abc def"); + new PowerOfNumber().run(); + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } +} diff --git a/src/test/java/homework_6/map_problems_generator/MapProblemsGeneratorTest.java b/src/test/java/homework_6/map_problems_generator/MapProblemsGeneratorTest.java new file mode 100644 index 00000000..efb15c93 --- /dev/null +++ b/src/test/java/homework_6/map_problems_generator/MapProblemsGeneratorTest.java @@ -0,0 +1,27 @@ +package homework_6.map_problems_generator; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; + +import static homework_6.map_problems_generator.MapProblemsGenerator.MapProblemsMutableGenerator; +import static org.junit.jupiter.api.Assertions.*; + +class MapProblemsGeneratorTest { + + @Test + void testMapProblemsMutableGenerator() { + MapProblemsMutableGenerator element = + new MapProblemsMutableGenerator(27, "Element 1"); + MapProblemsMutableGenerator sameElement = + new MapProblemsMutableGenerator(27, "Element 1"); + assertEquals(element, sameElement); + + HashMap map = new HashMap<>(); + map.put(element, element.getName()); + assertNotNull(map.get(element)); + + element.setId(30); + assertNull(map.get(element)); + } +} \ No newline at end of file