diff --git a/README.md b/README.md index 5d686e9f..e078da7e 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,22 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Dima Troshkin* + +[CodingBat Profile](https://codingbat.com/done?user=allzza4279@gmail.com&tag=1424372731) | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/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/DimaTroshkin/src/main/java/homework_1/) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/traffic_light/) | The app that reads time from keyboard and says which color the traffic light is| +| | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/homework_2.pyramid_printer/) | The app that makes pyramid of "x" using int input| +| | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_2/random_chars_table/) | The app which prints table of random letters using int numbers of rows and columns and string strategy - "even" or "odd". Also prints out all even or odd letters according to strategy chosen| +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_3/)| An example of Immutable Class realization | +| HW4 | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/custom_annotation/)| An example of custom annotation realization | +| | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/custom_file_reader/)| An app which reads String data from file.txt and removes commas and fullstops | +| | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_4/singleton/)| An example of singleton class | +| HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/custom_regex_matcher/)| An app which takes String from terminal and checks whether given String matches hardcoded regex| +| | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_5/power_of_number/)| An app which calculates a^b for two non-negative integers a and b | +| HW6 | [MapPloblemGenerators](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_6/)| The realisation of two classes which generate problems using hashmap| +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/homework_7/)| The realisation of @FunctionalInterface KittenToCatFunction with abstract method grow(). From now on we know how does kitten become a cat!| +| HW7 | [SeaBattle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/DimaTroshkin/src/main/java/course_project/)| The Sea Battle game 1 by 1 (No AI) | +[Link to markdown guide](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/src/main/java/course_project/Battle.java b/src/main/java/course_project/Battle.java new file mode 100644 index 00000000..c2c60f1a --- /dev/null +++ b/src/main/java/course_project/Battle.java @@ -0,0 +1,58 @@ +package course_project; + +import course_project.models.Player; +import course_project.models.Ship; +import course_project.engine.ShipPlacer; +import course_project.engine.Shooter; + +import java.io.IOException; +import java.util.ArrayList; + +public class Battle { + + public static void run() throws IOException { + Player player1 = new Player(); + Player player2 = new Player(); + + ArrayList players = new ArrayList<>(); + players.add(player1); + players.add(player2); + + Player currentPlayer; + for (Player player : players) { // preparing both players battlefields + currentPlayer = player; + + System.out.println("\n \n" + currentPlayer.name() + ", welcome to the Sea Battle. \n \n" + + "It`s time to place your ships. Remember the main rule: ships must not touch each other.\n" + "To place a ship you basically need to type coordinate and then choose mode. \n" + + "There are two ways to place your ships from starting coordinate: from left to right (key \"h\") & from up to down (key \"v\")\n" + + "If there is only one possible way, it will be chosen automatically, if it`s impossible to place ship from this coordinate, you will have to choose another one.\n"); + + System.out.println("Let`s begin with Carrier - huge battleship with size 4. \n"); + ShipPlacer.placement(new Ship("Carrier", 4), currentPlayer); + + System.out.println("Now place 2 Cruisers of size 3"); + for (int i = 0; i < 2; i++) { + ShipPlacer.placement(new Ship("Cruiser", 3), currentPlayer); + } + System.out.println("Now place 3 Destroyers of size 2"); + for (int i = 0; i < 3; i++) { + ShipPlacer.placement(new Ship("Destroyer", 2), currentPlayer); + } + System.out.println("And finally place 4 Scout ships of size 1"); + for (int i = 0; i < 4; i++) { + ShipPlacer.placement(new Ship("Scout", 1), currentPlayer); + } + + } + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n"); + + while (player1.hp() > 0 && player2.hp() > 0) { + Shooter.Shoot(player1, player2); + if (player2.hp() == 0) { + break; + } + Shooter.Shoot(player2, player1); + } + } +} diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..7e09e77f --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +import java.io.IOException; + +public class Main { + + + public static void main(String[] args) throws IOException { + Battle.run(); + } +} diff --git a/src/main/java/course_project/engine/BoardPrinter.java b/src/main/java/course_project/engine/BoardPrinter.java new file mode 100644 index 00000000..6174fee6 --- /dev/null +++ b/src/main/java/course_project/engine/BoardPrinter.java @@ -0,0 +1,58 @@ +package course_project.engine; + +import course_project.models.Player; +import course_project.models.Board; + +import java.util.Locale; + +public class BoardPrinter { + + public static void printMainBoard(Player player) { + Board board = player.mainBoard(); + System.out.println(player.name() + ": MAIN BOARD"); + int rowNum = 1; + String rowOffset; + System.out.println(" " + board.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); + for (int row : board.getRowNames()) { + rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; + System.out.print(rowOffset); + + for (String cell : board.getBoard().get(row)) { + System.out.print(" " + cell + " " + "|"); + } + System.out.print("\n"); + rowNum++; + } + } + + public static void printBothBoards(Player player) { + Board mainBoard = player.mainBoard(); + Board scanBoard = player.scanBoard(); + int rowNum = 1; + String spaceBetween = " "; + String rowOffset; + System.out.println(spaceBetween + player.name() + ": MAIN BOARD" + spaceBetween + spaceBetween + " ENEMY TRACKING"); + // top + System.out.print(" " + mainBoard.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); + System.out.print(spaceBetween); + System.out.println(" " + scanBoard.getColNames().stream().reduce(((s, s2) -> s + " " + s2)).orElse("").toUpperCase(Locale.ROOT)); + + for (int row : mainBoard.getRowNames()) { + rowOffset = (rowNum < 10) ? rowNum + " |" : rowNum + " |"; + System.out.print(rowOffset); + + for (String cell : mainBoard.getBoard().get(row)) { + System.out.print(" " + cell + " " + "|"); + } + System.out.print(spaceBetween); + System.out.print(rowOffset); + for (String cell : scanBoard.getBoard().get(row)) { + System.out.print(" " + cell + " " + "|"); + } + + System.out.print("\n"); + rowNum++; + } + } + +} diff --git a/src/main/java/course_project/engine/Input.java b/src/main/java/course_project/engine/Input.java new file mode 100644 index 00000000..79ebebb5 --- /dev/null +++ b/src/main/java/course_project/engine/Input.java @@ -0,0 +1,66 @@ +package course_project.engine; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Locale; + +public class Input { + + public static String getRightCoordinate() throws IOException { + System.out.println("Enter coordinate if format: \"a1\""); + String s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + s = reader.readLine(); + if (Input.checkCoordinate(s)) { + System.out.println("Coordinate: " + s); + return s; + } else { + System.out.println("Wrong Input! use letters from a to j and numbers from 1 to 10, like \"d4\""); + } + } + } + + public static String getRightMode() throws IOException { + System.out.println("Choose mode: use letter \"v\" to place it vertically or \"h\" to place it horizontally"); + String s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + s = reader.readLine(); + if (Input.checkMode(s)) { + System.out.println("Mode: " + s); + return s; + } else { + System.out.println("Wrong mode! use letter \"v\" to place it vertically or \"h\" to place it horizontally."); + } + } + } + + public static boolean checkCoordinate(String s) { + if (s.length() > 3 || s.length() < 2) { + return false; + } + + if (!s.toLowerCase(Locale.ROOT).substring(0, 1).matches("[a-j]")) { + return false; + } + + if (!s.toLowerCase(Locale.ROOT).substring(1, 2).matches("[1-9]")) { + return false; + } + + if (s.length() == 3 && !s.toLowerCase(Locale.ROOT).substring(2).matches("0")) { + return false; + } + return true; + } + + public static boolean checkMode(String s) { + if (s.toLowerCase(Locale.ROOT).matches("[vh]")) { + return true; + } + return false; + } + +} diff --git a/src/main/java/course_project/engine/PositionChecker.java b/src/main/java/course_project/engine/PositionChecker.java new file mode 100644 index 00000000..0beae767 --- /dev/null +++ b/src/main/java/course_project/engine/PositionChecker.java @@ -0,0 +1,76 @@ +package course_project.engine; + +import course_project.models.Board; +import course_project.models.Coordinate; + +import java.util.List; + +public class PositionChecker { + + public static boolean possibleToPlace(Board b, Coordinate c, int size, String mode) { + // mode h: left -> right , mode v: up - > down from coordinate given + int horizSize; + int vertSize; + + if (mode.equalsIgnoreCase("h")) { // space needed for ship in horizontal mode + horizSize = size; + vertSize = 1; + } else { // space needed for ship in vertical mode + horizSize = 1; + vertSize = size; + } + + List currentRow; + List upperRow; + List lowerRow; + + // Checking upper row + if (b.getBoard().containsKey(c.row() - 1)) { // if it exist + upperRow = b.getBoard().get(c.row() - 1); + for (int col = c.col() - 1; col <= c.col() + horizSize; col++) { // check all cols from current -1 to current + size + if (col >= 0 && col < 10) { // if mainBoard contains such col + if (!upperRow.get(col).equals(" ")) { // cell must be empty + return false; + } + } + } + } + + // Checking hull rows + for (int i = 0; i < vertSize; i++) { + if (!b.getBoard().containsKey(c.row() + i)) { // if doesn`t exist -> not enough vertical space + return false; + } + currentRow = b.getBoard().get(c.row() + i); + for (int col = c.col() - 1; col <= c.col() + horizSize; col++) { // check all cols from current -1 to current + horiz size + if (col >= 0 && col < 10) { // if mainBoard contains such col + if (!currentRow.get(col).equals(" ")) { // cell must be empty + return false; + } + } else { + if ((col - 1 > 9) && mode.equalsIgnoreCase("h")) { // if not enough space horizontally (last hull coord comes out of the map) + return false; + } + } + } + + } + + + // Checking lower row + if (b.getBoard().containsKey(c.row() + vertSize)) { // if it exist + lowerRow = b.getBoard().get(c.row() + vertSize); + for (int col = c.col() - 1; col <= c.col() + horizSize; col++) { // check all cols from current -1 to current + size + if (col >= 0 && col < 10) { // if mainBoard contains such col + if (!lowerRow.get(col).equals(" ")) { // cell must be empty + return false; + } + } + } + } + + return true; + } + + +} diff --git a/src/main/java/course_project/engine/ShipPlacer.java b/src/main/java/course_project/engine/ShipPlacer.java new file mode 100644 index 00000000..b2807e7d --- /dev/null +++ b/src/main/java/course_project/engine/ShipPlacer.java @@ -0,0 +1,65 @@ +package course_project.engine; + +import course_project.models.Player; +import course_project.models.Board; +import course_project.models.Coordinate; +import course_project.models.Ship; + +import java.io.IOException; +import java.util.ArrayList; + +public class ShipPlacer { + + public static void placement(Ship ship, Player p) throws IOException { + + Board b = p.mainBoard(); + while (true) { + BoardPrinter.printMainBoard(p); + System.out.println("It`s time to place a ship."); + Coordinate c = new Coordinate(Input.getRightCoordinate()); + String mode; + int size = ship.getSize(); + + if (PositionChecker.possibleToPlace(b, c, size, "v") && PositionChecker.possibleToPlace(b, c, size, "h")) { + if (size == 1) { //scout does not need direction + placeShip(p, c, ship, "h"); + break; + } + mode = Input.getRightMode(); + placeShip(p, c, ship, mode); + break; + + } else if (PositionChecker.possibleToPlace(b, c, size, "v")) { + placeShip(p, c, ship, "v"); + break; + } else if (PositionChecker.possibleToPlace(b, c, size, "h")) { + placeShip(p, c, ship, "h"); + break; + } else { + System.out.println("Impossible to place it here!"); + } + } + } + + public static void placeShip(Player p, Coordinate c, Ship ship, String mode) { + Board b = p.mainBoard(); + int size = ship.getSize(); + int cCol = c.col(); // current col & row + int cRow = c.row(); + ArrayList shipCoords = new ArrayList<>(); + for (int i = 0; i < size; i++) { + if (mode.equalsIgnoreCase("h")) { + shipCoords.add(new Coordinate(cRow, cCol + i)); + } else if (mode.equalsIgnoreCase("v")) { + shipCoords.add(new Coordinate(cRow + i, cCol)); + } + } + for (Coordinate coordinate : shipCoords) { + b.changeCell(coordinate, "H"); + } + ship.setCoords(shipCoords); + p.ships().add(ship); + BoardPrinter.printMainBoard(p); + } +} + diff --git a/src/main/java/course_project/engine/Shooter.java b/src/main/java/course_project/engine/Shooter.java new file mode 100644 index 00000000..8a703f12 --- /dev/null +++ b/src/main/java/course_project/engine/Shooter.java @@ -0,0 +1,92 @@ +package course_project.engine; + +import course_project.models.Player; +import course_project.models.Ship; +import course_project.models.Coordinate; + + +import java.io.IOException; +import java.util.List; + +public class Shooter { + + public static void Shoot(Player currentPlayer, Player enemyPlayer) throws IOException { + + while (true) { + System.out.println(currentPlayer.name() + " turn! Enter a coordinate to shoot."); + BoardPrinter.printBothBoards(currentPlayer); + Coordinate c = getUniqueShoot(currentPlayer); + if (!makeOneShoot(currentPlayer, enemyPlayer, c)) { //if miss - no other try + break; + } + } + } + + public static boolean makeOneShoot(Player currentPlayer, Player enemyPlayer, Coordinate c) { + + boolean shootMore = true; + for (Ship ship : enemyPlayer.ships()) { + + if (ship.getCoords().contains(c)) { + shootMore = true; + ship.reduceHp(); + enemyPlayer.reduceHp(); + addMark(currentPlayer, enemyPlayer, c, "X"); + + if (shipAlive(ship)) { + System.out.println("Successful hit! Shoot one more time!"); + } else { + if (enemyPlayer.hp() == 0) { + System.out.println("Enemy " + ship + " killed!"); + System.out.println(currentPlayer.name() + " won! Congratulations!!!"); + shootMore = false; + break; + } + System.out.println("Enemy " + ship + " killed! Shoot one more time!"); + //TODO get oriole coordinates and fill + } + break; //another ships cannot contain that coordinate + } else { + shootMore = false; + } + } + if (!shootMore && enemyPlayer.hp() > 0) { + System.out.println("Miss!"); + addMark(currentPlayer, enemyPlayer, c, "*"); + } + return shootMore; + } + + private static Coordinate getUniqueShoot(Player currentPlayer) throws IOException { + while (true) { + Coordinate c = new Coordinate(Input.getRightCoordinate()); + if (currentPlayer.checkedCells().contains(c)) { + System.out.println("That cell is already checked, choose another one"); + } else { + currentPlayer.checkedCells().add(c); + System.out.println("Shooting at cell " + c + "..."); + return c; + } + } + } + + private static boolean shipAlive(Ship ship) { + return ship.getHp() > 0; + } + + private static void addMark(Player currentPlayer, Player enemyPlayer, Coordinate c, String sign) { + enemyPlayer.mainBoard().changeCell(c, sign); + currentPlayer.scanBoard().changeCell(c, sign); + } + + private static void addMark(Player currentPlayer, Player enemyPlayer, List coordinateList, String sign) { + for (Coordinate c : coordinateList) { + enemyPlayer.mainBoard().changeCell(c, sign); + currentPlayer.scanBoard().changeCell(c, sign); + } + } + + //TODO +// private static ArrayList oreole(){} + +} diff --git a/src/main/java/course_project/models/Board.java b/src/main/java/course_project/models/Board.java new file mode 100644 index 00000000..17b787d3 --- /dev/null +++ b/src/main/java/course_project/models/Board.java @@ -0,0 +1,45 @@ +package course_project.models; + +import java.util.*; + +public class Board { + private HashMap> board; + private final List rowNames = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + private final List colNames = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); + private final List emptyRows = Arrays.asList(" ", " ", " ", " ", " ", " ", " ", " ", " ", " "); + + public Board() { + this.board = new HashMap<>(); + for (int r : rowNames) { + board.put(r, getEmptyRows()); + } + } + + public void changeCell(Coordinate coordinate, String sign) { + List currentRow = board.get(coordinate.row()); + currentRow.set(coordinate.col(), sign); + board.put(coordinate.row(), currentRow); + } + + public String getCell(Coordinate c) { + return board.get(c.row()).get(c.col()); + } + + private List getEmptyRows() { + return new ArrayList<>(emptyRows); + } + + public List getRowNames() { + return this.rowNames; + } + + public List getColNames() { + return this.colNames; + } + + public HashMap> getBoard() { + return this.board; + } + + +} diff --git a/src/main/java/course_project/models/Coordinate.java b/src/main/java/course_project/models/Coordinate.java new file mode 100644 index 00000000..469561d3 --- /dev/null +++ b/src/main/java/course_project/models/Coordinate.java @@ -0,0 +1,74 @@ +package course_project.models; + +import java.util.Locale; +import java.util.Objects; + +public class Coordinate { + private int col; + private int row; + + public Coordinate(String s) { + col = s.toLowerCase(Locale.ROOT).charAt(0) - 97; + row = Integer.parseInt(s.substring(1)); + } + + public Coordinate(int r, int c) { + this.row = r; + this.col = c; + } + + public Coordinate(Coordinate c) { + this.row = c.row; + this.col = c.col; + } + + @Override + public String toString() { + return "" + (char) (col + 97) + row; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Coordinate)) return false; + Coordinate that = (Coordinate) o; + return col() == that.col() && row() == that.row(); + } + + @Override + public int hashCode() { + return Objects.hash(col(), row()); + } + + public int col() { + return col; + } + + public int row() { + return row; + } + + public boolean exists() { + return this.row >= 1 && this.row <= 10 && this.col >= 0 && this.col <= 9; + } + + public Coordinate upper() { + return new Coordinate(this.row - 1, this.col); + } + + public Coordinate lower() { + return new Coordinate(this.row + 1, this.col); + } + + public Coordinate lower(int n) { + return new Coordinate(this.row + n, this.col); + } + + public Coordinate toLeft() { + return new Coordinate(this.row, this.col - 1); + } + + public Coordinate toRight() { + return new Coordinate(this.row, this.col + 1); + } +} diff --git a/src/main/java/course_project/models/Player.java b/src/main/java/course_project/models/Player.java new file mode 100644 index 00000000..2dfe32ca --- /dev/null +++ b/src/main/java/course_project/models/Player.java @@ -0,0 +1,65 @@ +package course_project.models; + +import java.util.ArrayList; +import java.util.HashSet; + +public class Player { + private static int count = 1; + private String name; + private ArrayList ships; + private Board mainBoard; + private Board scanBoard; + private HashSet checkedCells; + private int hp = 20; //default hp for whose set of ships + + public Player(String name) { + this.name = name; + ships = new ArrayList<>(10); + mainBoard = new Board(); + scanBoard = new Board(); + checkedCells = new HashSet<>(40); + count++; + } + + public Player() { + this.name = "Player " + count; + ships = new ArrayList<>(10); + mainBoard = new Board(); + scanBoard = new Board(); + checkedCells = new HashSet<>(40); + count++; + } + + public void reduceHp() { + hp--; + } + + public void setHp(int n) { + this.hp = n; + } + + public int hp() { + return hp; + } + + public String name() { + return name; + } + + public ArrayList ships() { + return ships; + } + + public Board mainBoard() { + return mainBoard; + } + + public Board scanBoard() { + return scanBoard; + } + + public HashSet checkedCells() { + return checkedCells; + } + +} diff --git a/src/main/java/course_project/models/Ship.java b/src/main/java/course_project/models/Ship.java new file mode 100644 index 00000000..f17a21c6 --- /dev/null +++ b/src/main/java/course_project/models/Ship.java @@ -0,0 +1,44 @@ +package course_project.models; + +import java.util.ArrayList; + +public class Ship { + private String name; + private int hp; + private int size; + private ArrayList coords; + + public Ship(String name, int size) { + this.name = name; + this.size = size; + this.hp = size; + this.coords = new ArrayList<>(); + } + + @Override + public String toString() { + return name; + } + + public void reduceHp() { + hp--; + } + + public int getHp() { + return hp; + } + + public int getSize() { + return size; + } + + public ArrayList getCoords() { + return coords; + } + + public void setCoords(ArrayList coords) { + this.coords = coords; + } + + +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..5422f9d8 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -3,7 +3,13 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello homework!"); - } + for (String s: args) { + System.out.println(s + ": " + s.length() + " букв"); + if (s.equals("ошибка")) { + System.out.println("Тревога"); + break; + } + } + } } 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..bc983c36 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,38 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { +// считывает число с командной строки, и печатает пирамиду из "x" согласно введенному положительному целому числу. +// После первой печати завершает работу. + + public static void run() { + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + String str; + int num; + + System.out.println("Enter 1 positive integer"); + + try { + str = reader.readLine(); + num = Integer.parseInt(str); + if (num < 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } else { + printPyramid(num); + } + } catch (NumberFormatException | IOException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + } + + private static void printPyramid(int num) { + String output = ""; + for (int i = 0; i < num; i++) { + output += "x"; + System.out.println(output); + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..6787be60 --- /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.run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..321d9158 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,95 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + + public static void run() { + + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter parameters in following format: [positive integer] [positive integer] [even|odd]"); + + try { + String s = reader.readLine(); + String[] params = s.split(" "); + + int rows = Integer.parseInt(params[0]); + int cols = Integer.parseInt(params[1]); + String strategy = params[2]; + + if (NumOfParamsIsOk(params) && StrategyIsOk(strategy) && isPositive(rows) && isPositive(cols)) { + + char[][] letters = getRandomLetters(rows, cols); + printTable(letters); + printStrategy(letters, strategy); + + } else { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + } + } catch (Exception e) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + } + } + + private static boolean isPositive(int num) { + return num > 0; + } + + private static boolean StrategyIsOk(String strategy) { + return strategy.equals("even") || strategy.equals("odd"); + } + + private static boolean NumOfParamsIsOk(String[] params) { + return params.length == 3; + } + + private static char[][] getRandomLetters(int rows, int cols) { + int minIndex = 65; //Char A index + int maxIndex = 90; //Char Z index + char[][] randomLettersTable = new char[rows][cols]; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + randomLettersTable[i][j] = (char) ((int) ((Math.random() * (maxIndex - minIndex)) + minIndex)); + } + } + return randomLettersTable; + } + + private static void printTable(char[][] table) { + for (char[] row : table) { + StringBuilder s = new StringBuilder("|"); + for (char letter : row) { + s.append(" ").append(letter).append(" |"); + } + System.out.println(s); + } + } + + private static void printStrategy(char[][] table, String strategy) { + StringBuilder output = new StringBuilder(); + + if (strategy.equals("even")) { + output.append("Even letters - "); + for (char[] row : table) { + for (char letter : row) { + if ((int) letter % 2 == 0) { + output.append(letter).append(", "); + } + } + } + } else { + output.append("Odd letters - "); + for (char[] row : table) { + for (char letter : row) { + if ((int) letter % 2 != 0) { + output.append(letter).append(", "); + } + } + } + } + System.out.println(output.substring(0, output.length() - 2)); + } +} 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..1764517c --- /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) { + TrafficLight.run(); + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..62b25291 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,51 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { +// считывает количество секунд с начала дня с командной строки во время работы, переводит в инт, +// выводит в командную строку цвет светофора (любым вариантом/сообщением, +// главное чтобы было различие зеленый-желтый-красный). +// Цикл светофора - 60 секунд. +// С 0 <= light < 35 зеленый, 35 <= light < 40 желтый, 40 <= light < 55 красный, 55 <= light < 60 желтый. +// +// Ограничения ввода: минимальное 0, максимальное 24*60*60 - 1 = 86399 + + public static final String RESET = "\u001B[0m"; + public static final String RED = "\u001B[31m"; + public static final String GREEN = "\u001B[32m"; + public static final String YELLOW = "\u001B[33m"; + + public static void run() { + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + String str; + + System.out.println("Enter the number from 0 to 86399"); + + try { + str = reader.readLine(); + int time = Integer.parseInt(str); + if (time < 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } else if (time > 86399) { + System.out.println("The day is over"); + } else { + int light = time % 60; + + if (light < 35) { + System.out.println(GREEN + "GREEN" + RESET); + } else if (light < 40) { + System.out.println(YELLOW + "YELLOW" + RESET); + } else if (light < 55) { + System.out.println(RED + "RED" + RESET); + } else { + System.out.println(YELLOW + "YELLOW" + RESET); + } + } + } catch (NumberFormatException | IOException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + } +} diff --git a/src/main/java/homework_3/ImmutableClassTerminator.java b/src/main/java/homework_3/ImmutableClassTerminator.java new file mode 100644 index 00000000..99c4b4a9 --- /dev/null +++ b/src/main/java/homework_3/ImmutableClassTerminator.java @@ -0,0 +1,64 @@ +package homework_3; + +/* How to make Immutable Objects: + 1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields. + 2. Make all fields final and private. + 3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. + A more sophisticated approach is to make the constructor private and construct instances in factory methods. + 4. If the instance fields include references to mutable objects, don't allow those objects to be changed: + - Don't provide methods that modify the mutable objects. + - Don't share references to the mutable objects. Never store references to external, mutable objects passed to + the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies + of your internal mutable objects when necessary to avoid returning the originals in your methods. +*/ + +import java.util.Date; + +public final class ImmutableClassTerminator { + private final int departureYear; + private final String model; + private final Date timeTravelDate; + + public ImmutableClassTerminator(int departureYear, String model, Date timeTravelDate) { + this.departureYear = departureYear; + this.model = model; + this.timeTravelDate = new Date(timeTravelDate.getTime()); + } + + public ImmutableClassTerminator(int departureYear, Date timeTravelDate) { + this.departureYear = departureYear; + this.model = "T100"; + this.timeTravelDate = new Date(timeTravelDate.getTime()); + } + + public ImmutableClassTerminator(int departureYear, String model) { + this.departureYear = departureYear; + this.model = model; + this.timeTravelDate = new Date(); + } + + public int getDepartureYear() { + return departureYear; + } + + public String getModel() { + return model; + } + + public Date getTimeTravelDate() { + return (Date) timeTravelDate.clone(); + } + + public ImmutableClassTerminator changeTimeTravelDate(Date newTimeTravelDate) { + return new ImmutableClassTerminator(departureYear, model, newTimeTravelDate); + } + + @Override + public String toString() { + return "ImmutableClassTerminator{" + + "departureYear=" + departureYear + + ", model='" + model + '\'' + + ", timeTravelDate=" + timeTravelDate + + '}'; + } +} diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java new file mode 100644 index 00000000..4647a60d --- /dev/null +++ b/src/main/java/homework_3/Main.java @@ -0,0 +1,28 @@ +package homework_3; + +import java.util.Date; + +public class Main { + public static void main(String[] args) { + ImmutableClassTerminator terminator = new ImmutableClassTerminator(2077, "T100"); + Date date = terminator.getTimeTravelDate(); + + System.out.println(date); + date.setTime(0); + System.out.println(date); + System.out.println(terminator.getTimeTravelDate()); //field does not change + + ImmutableClassTerminator newTerminator = terminator.changeTimeTravelDate(new Date(1212121212121L)); + Date newDate = newTerminator.getTimeTravelDate(); + System.out.println(newDate); + + final Date date1 = new Date(); + final ImmutableClassTerminator t100 = new ImmutableClassTerminator(2077, "T100", date1); + System.out.println(t100); + date1.setTime(111111111111L); + System.out.println(t100); + + t100.getTimeTravelDate().setTime(111111111111L); + System.out.println(t100); + } +} diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java new file mode 100644 index 00000000..23e1d35c --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE ) +public @interface CustomAnnotation { + String output() default "Hello, World!"; +} diff --git a/src/main/java/homework_4/custom_annotation/FirstProgram.java b/src/main/java/homework_4/custom_annotation/FirstProgram.java new file mode 100644 index 00000000..b6a4b84d --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/FirstProgram.java @@ -0,0 +1,19 @@ +package homework_4.custom_annotation; + +@CustomAnnotation +public class FirstProgram { + private static String output; + + public FirstProgram(String s) { + output = s; + System.out.println(output); + } + + public FirstProgram() { + final CustomAnnotation annotation = FirstProgram.class.getAnnotation(CustomAnnotation.class); + output = annotation.output(); + System.out.println(output); + } + +} + diff --git a/src/main/java/homework_4/custom_annotation/Main.java b/src/main/java/homework_4/custom_annotation/Main.java new file mode 100644 index 00000000..44b1f0c4 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Main.java @@ -0,0 +1,11 @@ +package homework_4.custom_annotation; + +public class Main { + public static void main(String[] args) { + + new FirstProgram(); // with default value given by annotation + new FirstProgram("Hello, Java!"); + + } + +} diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..ebd5342b --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,52 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +public class CustomFileReader { + private static final String FILE_PATH = "src/main/resources/custom_file_reader/file.txt"; + + public static void run1() throws IOException { + StringBuilder content = new StringBuilder(); + FileInputStream fileInputStream = new FileInputStream(FILE_PATH); + int i; + while ((i = fileInputStream.read()) != -1) { + content.append((char) i); + } ; + printWithoutDotAndComma(content.toString()); + } + + + public static void run2() throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(FILE_PATH), 300); + int i; + while ((i = bufferedInputStream.read()) != -1) { + printWithoutDotAndComma((char) i); + } + bufferedInputStream.close(); + } + + public static void run3() throws IOException { + String content = Files.lines(Paths.get(FILE_PATH), StandardCharsets.UTF_8).reduce((s, s2) -> s + "\n" + s2).orElse(""); + printWithoutDotAndComma(content); + } + + public static void printWithoutDotAndComma(String s) { + char[] chars = s.toCharArray(); + for (char ch : chars) + if (ch != '.' && ch != ',') + System.out.print(ch); + } + + public static void printWithoutDotAndComma(char ch) { + if (ch != '.' && ch != ',') + System.out.print(ch); + } +} diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java new file mode 100644 index 00000000..87d2a24b --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,19 @@ +package homework_4.custom_file_reader; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +public class Main { + public static void main(String[] args) throws IOException { + CustomFileReader.run1(); +// CustomFileReader.run2(); + CustomFileReader.run3(); + + } + + +} diff --git a/src/main/java/homework_4/singleton/Main.java b/src/main/java/homework_4/singleton/Main.java new file mode 100644 index 00000000..91c5144a --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,8 @@ +package homework_4.singleton; + +public class Main { + public static void main(String[] args) { + System.out.println(Singleton.getInstance()); + System.out.println(Singleton.getInstance()); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..2c2e65b1 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +public class Singleton { + + private Singleton() { + } + + private static class SingletonHolder { + public static final Singleton INSTANCE_HOLDER = new Singleton(); + } + + public static Singleton getInstance() { + return SingletonHolder.INSTANCE_HOLDER; + } +} diff --git a/src/main/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..d39433d6 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,37 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + final private static String REGEX = "\\w*@\\w*\\.\\w*"; + // that regex Matches only email-like strings + //for example "Allzza4279@gmail.com" or "regex@lul.notmail1", " dimatroshkin@mail.ru" + + public static void run() { + try { + String s = getString(); + System.out.println(matchRegex(s)); + } catch (Throwable e){ + System.out.println("Wrong input"); + } + + } + + public static String getString() throws Throwable { + System.out.println("Please, enter your string..."); + String s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + s = reader.readLine(); + reader.close(); + return s; + } + + public static boolean matchRegex(String s) { + Pattern pattern = Pattern.compile(REGEX); + Matcher matcher = pattern.matcher(s); + return (matcher.matches()); + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..930fddfb --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) throws Throwable { + CustomRegexMatcher.run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..9a31c2f9 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) throws Throwable { + PowerOfNumber.run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..c996cbf7 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,50 @@ +package homework_5.power_of_number; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; + +public class PowerOfNumber { + final private static String ERROR_MSG = "Only 2 non-negative integers are allowed"; + private static Object Exception; + + public static void run() throws Throwable { + System.out.println("Enter 2 non-negative integers"); + try { + int[] numbers = getNumbers(); + int a = numbers[0]; + int b = numbers[1]; + System.out.println(power(a,b)); + + } catch (Exception e) { + System.out.println(ERROR_MSG); + } + } + + public static int[] getNumbers() throws Throwable { + String[] s; + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + s = reader.readLine().split(" "); + + if (s.length != 2) + throw (Throwable) Exception; + + int[] numbers = new int[2]; + for (int i = 0; i < 2; i++) { + numbers[i] = Integer.parseInt(s[i]); + } + + if (numbers[0] < 0 || numbers[1] < 0) + throw (Throwable) Exception; + return numbers; + } + + public static int power(int a, int b) { + if (b == 0){ + return 1; + } + return a * power(a, b - 1); + } + +} diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..81de344f --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,16 @@ +package homework_6; + +import java.util.HashMap; + +public class Main { + public static void main(String[] args) { + HashMap map = new HashMap(); + MapProblemsMutableGenerator mutableProblemGenerator = new MapProblemsMutableGenerator(0); + + map.put(mutableProblemGenerator, "Some very important information"); + System.out.println(map.get(mutableProblemGenerator)); + mutableProblemGenerator.setSomeNumber(2); + System.out.println(map.get(mutableProblemGenerator)); //got some problem + + } +} diff --git a/src/main/java/homework_6/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..d4608e7e --- /dev/null +++ b/src/main/java/homework_6/MapProblemsCollisionGenerator.java @@ -0,0 +1,12 @@ +package homework_6; + +import java.util.Objects; + +public class MapProblemsCollisionGenerator { + + @Override + public int hashCode() { + return 0; + } +} + diff --git a/src/main/java/homework_6/MapProblemsMutableGenerator.java b/src/main/java/homework_6/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..045c543a --- /dev/null +++ b/src/main/java/homework_6/MapProblemsMutableGenerator.java @@ -0,0 +1,39 @@ +package homework_6; + +import java.util.Objects; + +public class MapProblemsMutableGenerator extends MapProblemsCollisionGenerator{ + private int someNumber; + + public MapProblemsMutableGenerator(int someNumber) { + this.someNumber = someNumber; + } + + public int getSomeNumber() { + return someNumber; + } + + public void setSomeNumber(int someNumber) { + this.someNumber = someNumber; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MapProblemsMutableGenerator)) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return getSomeNumber() == that.getSomeNumber(); + } + + @Override + public int hashCode() { + return Objects.hash(getSomeNumber()); + } + + @Override + public String toString() { + return "MapProblemsMutableGenerator{" + + "someNumber=" + someNumber + + '}'; + } +} diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..dcdaca27 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,47 @@ +package homework_7; + +public class Cat { + private String name; + private int age; + private int weight; + + static { + System.out.println(" My \"MEOW\" grows! I wanna eat! \n"); + } + + public Cat(String name, int age, int weight) { + this.name = name; + this.age = age; + this.weight = weight; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void Meow() { + System.out.println("This is real MEOW! I wanna eat!"); + } + + @Override + public String toString() { + return "Cat " + name + " is " + age + " months old and weights " + weight + " gr. Truly mature cat! \n"; + } + +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..d50fd502 --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,48 @@ +package homework_7; + +public class Kitten { + private String name; + private int age; + private int weight; + + static { + System.out.println(" ... new kitten has just appeared! \n"); + } + + public Kitten(String name, int age, int weight) { + this.name = name; + this.age = age; + this.weight = weight; + } + + public String getName() { + return name; + } + + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void Meow() { + System.out.println("meoww! meoww!"); + } + + @Override + public String toString() { + return "Kitten " + name + " is only " + age + " months old and weights just " + weight + " g. So tiny and cute! \n"; + } + +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..9b34aeb1 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7; + +@FunctionalInterface +public interface KittenToCatFunction { + Cat grow(K k); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..9d4b5cd5 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,26 @@ +package homework_7; + +public class Main { + + public static void main(String[] args) { + KittenToCatFunction timeToGrow = k -> new Cat(k.getName(), 12, k.getWeight()*4); + + Kitten youngKitten = new Kitten("Vaskya", 2, 250); + System.out.println(youngKitten); + +// then.. + Cat matureCat = timeToGrow.grow(youngKitten); + System.out.println(matureCat); + +// Let`s try to make Cat from Cat + Cat oldCat = new Cat("Serj", 24, 2000); +// Cat old = timeToGrow.grow(oldCat); doesn`t work + +// Let`s try to make Cat from SubKitten + SubKitten subKitten = new SubKitten("Antoha", 8, 500); + Cat matureCatFromSubKitten = timeToGrow.grow(subKitten); // it works + System.out.println(matureCatFromSubKitten); + } + + +} diff --git a/src/main/java/homework_7/SubKitten.java b/src/main/java/homework_7/SubKitten.java new file mode 100644 index 00000000..136cdcde --- /dev/null +++ b/src/main/java/homework_7/SubKitten.java @@ -0,0 +1,49 @@ +package homework_7; + +public class SubKitten extends Kitten{ + + private String name; + private int age; + private int weight; + + public SubKitten(String name, int age, int weight) { + super(name,age,weight); + this.name = name; + this.age = age; + this.weight = weight; + } + + static { + System.out.println(" ... new SubKitten has just appeared! \n"); + } + + public String getName() { + return name; + } + + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void Meow() { + System.out.println("SubKitten meoww! SubKitten meoww!"); + } + + @Override + public String toString() { + return "SubKitten " + name + " is only " + age + " months old and weights just " + weight + " g. So subtiny and subcute! \n"; + } +} 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..8af74d73 --- /dev/null +++ b/src/main/resources/custom_file_reader/file.txt @@ -0,0 +1,23 @@ +July 4, 1776 + +The Unanimous Declaration of the thirteen united* States of America. + +When, in the course of human events, it becomes necessary for one people to dissolve the Political Bands which have +connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the +Laws of Nature and of Nature's God entitle them, a decent Respect to the Opinions of Mankind requires that they should +declare the causes which impel them to the Separation. + +We hold these Truths to be self-evident, that all Men are created equal, that they are endowed by their Creator with +certain unalienable Rights, that among these are Life, Liberty and the Pursuit of Happiness -- That to secure these +Rights, Governments are instituted among Men, deriving their just Powers from the Consent of the Governed, that +whenever any Form of Government becomes destructive to these Ends, it is the Right of the People to alter or to abolish +it, and to institute new Government, laying its Foundation on such Principles and organizing its Powers in such Form, +as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments +long established should not be changed for light and transient Causes; and accordingly all Experience hath shown that +Mankind are more disposed to suffer, while Evils are sufferable, than to right themselves by abolishing the Forms to +which they are accustomed. But when a long Train of Abuses and Usurpations, pursuing invariably the same Object, +evinces a Design to reduce them under absolute Despotism, it is their Right, it is their Duty, to throw off such +Government, and to provide new Guards for their future Security. Such has been the patient Sufferance of these Colonies; +and such is now the Necessity which constrains them to alter their former Systems of Government. The History of the +present King of Great- Britain is a History of repeated Injuries and Usurpations, all having in direct Object the +Establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid World. diff --git a/src/main/resources/custom_file_reader/file_for_test.txt b/src/main/resources/custom_file_reader/file_for_test.txt new file mode 100644 index 00000000..172e0750 --- /dev/null +++ b/src/main/resources/custom_file_reader/file_for_test.txt @@ -0,0 +1,23 @@ +July 4 1776 + +The Unanimous Declaration of the thirteen united* States of America + +When in the course of human events it becomes necessary for one people to dissolve the Political Bands which have +connected them with another and to assume among the Powers of the Earth the separate and equal Station to which the +Laws of Nature and of Nature's God entitle them a decent Respect to the Opinions of Mankind requires that they should +declare the causes which impel them to the Separation + +We hold these Truths to be self-evident that all Men are created equal that they are endowed by their Creator with +certain unalienable Rights that among these are Life Liberty and the Pursuit of Happiness -- That to secure these +Rights Governments are instituted among Men deriving their just Powers from the Consent of the Governed that +whenever any Form of Government becomes destructive to these Ends it is the Right of the People to alter or to abolish +it and to institute new Government laying its Foundation on such Principles and organizing its Powers in such Form +as to them shall seem most likely to effect their Safety and Happiness Prudence indeed will dictate that Governments +long established should not be changed for light and transient Causes; and accordingly all Experience hath shown that +Mankind are more disposed to suffer while Evils are sufferable than to right themselves by abolishing the Forms to +which they are accustomed But when a long Train of Abuses and Usurpations pursuing invariably the same Object +evinces a Design to reduce them under absolute Despotism it is their Right it is their Duty to throw off such +Government and to provide new Guards for their future Security Such has been the patient Sufferance of these Colonies; +and such is now the Necessity which constrains them to alter their former Systems of Government The History of the +present King of Great- Britain is a History of repeated Injuries and Usurpations all having in direct Object the +Establishment of an absolute Tyranny over these States To prove this let Facts be submitted to a candid World \ No newline at end of file diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 97e2685b..a8ff7a28 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -5,58 +5,59 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; public abstract class UnitBase { - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } } - } - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); + } // @Test // void example() { diff --git a/src/test/java/course_project/BoardChangeCellTest.java b/src/test/java/course_project/BoardChangeCellTest.java new file mode 100644 index 00000000..ffe74f28 --- /dev/null +++ b/src/test/java/course_project/BoardChangeCellTest.java @@ -0,0 +1,52 @@ +package course_project; + +import course_project.models.Board; +import course_project.models.Coordinate; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class BoardChangeCellTest { + + + Board b = new Board(); + Coordinate c; + String sign; + + @Test + void putA1() { + c = new Coordinate("a1"); + sign = "v"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + + @Test + void putJ10() { + c = new Coordinate("j10"); + sign = "t"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + + @Test + void putA10() { + c = new Coordinate("a10"); + sign = "*"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + + @Test + void putJ1() { + c = new Coordinate("a10"); + sign = "X"; + b.changeCell(c, sign); + + assertEquals(sign, b.getCell(c)); + } + +} diff --git a/src/test/java/course_project/CoordinateCheckTest.java b/src/test/java/course_project/CoordinateCheckTest.java new file mode 100644 index 00000000..132c7021 --- /dev/null +++ b/src/test/java/course_project/CoordinateCheckTest.java @@ -0,0 +1,88 @@ +package course_project; + +import course_project.engine.Input; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CoordinateCheckTest { + + @Test + void testWrongInput_1() { + String input = "a0"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_2() { + String input = "0"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_3() { + String input = "q"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_4() { + String input = "q1"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_5() { + String input = ""; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_6() { + String input = "null"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_7() { + String input = "a12"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_8() { + String input = "k6"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_9() { + String input = "112"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testWrongInput_10() { + String input = "abds"; + assertFalse(Input.checkCoordinate(input)); + } + + @Test + void testRightInput_1() { + String input = "a1"; + assertTrue(Input.checkCoordinate(input)); + } + + @Test + void testRightInput_2() { + String input = "B6"; + assertTrue(Input.checkCoordinate(input)); + } + + @Test + void testRightInput_3() { + String input = "j10"; + assertTrue(Input.checkCoordinate(input)); + } + +} diff --git a/src/test/java/course_project/MakeOneShootTest.java b/src/test/java/course_project/MakeOneShootTest.java new file mode 100644 index 00000000..0313eb9c --- /dev/null +++ b/src/test/java/course_project/MakeOneShootTest.java @@ -0,0 +1,122 @@ +package course_project; + +import course_project.engine.BoardPrinter; +import course_project.engine.ShipPlacer; +import course_project.engine.Shooter; +import course_project.models.Coordinate; +import course_project.models.Player; +import course_project.models.Ship; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class MakeOneShootTest { + + Player currentPlayer = new Player(); + Player enemyPlayer = new Player(); + + @Test + public void oneShipPlacedA1Horizontally_ShootAround_thenMiss() { + Coordinate toPlace = new Coordinate("a1"); + Coordinate toShoot = new Coordinate("a2"); + ShipPlacer.placeShip(enemyPlayer, toPlace, new Ship("Carrier", 4), "h"); + enemyPlayer.setHp(4); + + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("b2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("c2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("d2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("e1"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + toShoot = new Coordinate("e2"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has no additional shoot + assertEquals("*", enemyPlayer.mainBoard().getCell(toShoot)); //marked as miss + + assertEquals(4, enemyPlayer.hp()); + + BoardPrinter.printMainBoard(enemyPlayer); + } + + @Test + public void oneShipPlacedA1Horizontally_ShootAtShip_thenHit() { + Coordinate toPlace = new Coordinate("a1"); + Coordinate toShoot = new Coordinate("a1"); + ShipPlacer.placeShip(enemyPlayer, toPlace, new Ship("Carrier", 4), "h"); + enemyPlayer.setHp(4); + + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("b1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("c1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("d1"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // enemyPlayer has no HP, stop shooting + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + assertEquals(0, enemyPlayer.hp()); + + BoardPrinter.printMainBoard(enemyPlayer); + } + + @Test + public void twoShipsPlacedA1Horizontally_andE2VerticallyShootAtShipsReverseOrder_thenHit() { + Coordinate toPlace1 = new Coordinate("a1"); + Coordinate toPlace2 = new Coordinate("e2"); + + ShipPlacer.placeShip(enemyPlayer, toPlace1, new Ship("Carrier", 4), "h"); + ShipPlacer.placeShip(enemyPlayer, toPlace2, new Ship("Cruiser", 3), "v"); + enemyPlayer.setHp(7); + + Coordinate toShoot = new Coordinate("e4"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("e3"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("e2"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("d1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("c1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("b1"); + assertTrue(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // currentPlayer has additional shoot + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + toShoot = new Coordinate("a1"); + assertFalse(Shooter.makeOneShoot(currentPlayer, enemyPlayer, toShoot)); // enemyPlayer has no HP, stop shooting + assertEquals("X", enemyPlayer.mainBoard().getCell(toShoot)); //marked as hit + + assertEquals(0, enemyPlayer.hp()); + + BoardPrinter.printMainBoard(enemyPlayer); + } + +} diff --git a/src/test/java/course_project/ModeCheckTest.java b/src/test/java/course_project/ModeCheckTest.java new file mode 100644 index 00000000..bcd253dd --- /dev/null +++ b/src/test/java/course_project/ModeCheckTest.java @@ -0,0 +1,64 @@ +package course_project; + +import course_project.engine.Input; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class ModeCheckTest { + + @Test + void testGivenRightMode_v() { + String input = "v"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenRightMode_V() { + String input = "V"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenRightMode_h() { + String input = "h"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenRightMode_H() { + String input = "H"; + assertTrue(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_1() { + String input = "Hv"; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_2() { + String input = "g"; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_3() { + String input = "1"; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_4() { + String input = " "; + assertFalse(Input.checkMode(input)); + } + + @Test + void testGivenWrongString_5() { + String input = ""; + assertFalse(Input.checkMode(input)); + } + +} diff --git a/src/test/java/course_project/ShipPositioningCheckerTest.java b/src/test/java/course_project/ShipPositioningCheckerTest.java new file mode 100644 index 00000000..658d1029 --- /dev/null +++ b/src/test/java/course_project/ShipPositioningCheckerTest.java @@ -0,0 +1,279 @@ +package course_project; + +import course_project.models.Board; +import course_project.models.Coordinate; +import course_project.engine.PositionChecker; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class ShipPositioningCheckerTest { + + Board b = new Board(); + Coordinate c; + int size; + String mode; + + + @Test + void test_EnoughPlace_VerticalA1() { + c = new Coordinate("a1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_EnoughPlace_Horizontal_A1() { + c = new Coordinate("a1"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_EnoughPlace_Vertical_J1() { + c = new Coordinate("j1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_EnoughPlace_Vertical_A6() { + c = new Coordinate("a6"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_EnoughPlace_Horizontal_A6() { + c = new Coordinate("a6"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_EnoughPlace_Horizontal_A10() { + c = new Coordinate("a8"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_NotEnoughPlace_Vertical_A8() { + c = new Coordinate("a8"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_NotEnoughPlace_HorizontalJ1() { + c = new Coordinate("j1"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_NotEnoughPlace_HorizontalJ8() { + c = new Coordinate("j8"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalD1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d1"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalE1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("e1"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalF1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f1"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalD5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d5"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalE5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("e5"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalF5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f5"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalD6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d6"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalE6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("e6"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_VerticalF6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f6"); + size = 4; + mode = "v"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalA4() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("a4"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalA5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("a5"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalA6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("a6"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalF4() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f4"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalF5() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f5"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5NotEnoughPlace_HorizontalF6() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("f6"); + size = 4; + mode = "h"; + assertFalse(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_HorizontalC3() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("c3"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_HorizontalD7() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("d7"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_HorizontalG4() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("g4"); + size = 4; + mode = "h"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_VerticalC1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("c1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_VerticalG1() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("g1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + + @Test + void test_ObstacleE5EnoughPlace_VerticalD7() { + b.changeCell(new Coordinate("e5"), "O"); // add obstacle + c = new Coordinate("g1"); + size = 4; + mode = "v"; + assertTrue(PositionChecker.possibleToPlace(b, c, size, mode)); + } + +} diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..a6031034 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,91 @@ +package homework_2.pyramid_printer; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +import base.UnitBase; + +class PyramidPrinterTest extends UnitBase { + + @Test + void givenPositiveIntFour_whenRun_thenPrintPyramid() { + setInput("4"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + assertEquals("xxxx", getOutputLines()[3]); + } + + @Test + void givenZero_whenRun_thenWriteErrMsgAndStop() { + setInput("0"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void givenNothing_whenRun_thenWriteErrMsgAndStop() { + setInput(""); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenNegativeInt_whenRun_thenWriteErrMsgAndStop() { + setInput("-4"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenDouble_whenRun_thenWriteErrMsgAndStop() { + setInput("2.5"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenString_whenRun_thenWriteErrMsgAndStop() { + setInput("String"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void givenMoreThenOneInput_whenRun_thenWriteErrMsgAndStop() { + setInput("3 0"); + + PyramidPrinter.run(); + printOut(); + removeFromOutput("Enter 1 positive integer"); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + +} diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..bb65cb74 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,157 @@ +package homework_2.random_chars_table; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +import base.UnitBase; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class RandomCharsTableTest extends UnitBase { + + final String WELCOME_MSG = "Enter parameters in following format: [positive integer] [positive integer] [even|odd]"; + final String ERR_MSG = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + @Test + public void givenNull_whenRun_thenPrintErrMsg() { + setInput(""); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenString_whenRun_thenPrintErrMsg() { + setInput("null"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenDoubles_whenRun_thenPrintErrMsg() { + setInput("2.5 3 odd"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenNotEnoughArguments_whenRun_thenPrintErrMsg() { + setInput("25 odd"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenTooManyArguments_whenRun_thenPrintErrMsg() { + setInput("2 5 lol odd"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenWrongStrategy_whenRun_thenPrintErrMsg() { + setInput("2 5 ewen"); + + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenCorrectInputThreeFiveOdd_whenRun_thenPrintErrMsg() { + String input = "3 5 odd"; + String strategy = input.split(" ")[2]; + + setInput(input); + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + final String actualResult = getOutputLines()[3]; + removeFromOutput(actualResult); + final String table = getOutput(); + + StringBuilder letters = getLettersFromTable(table); + StringBuilder expectedResult = getExpectedResult(letters,strategy); + assertEquals(expectedResult.toString(), actualResult); + } + + @Test + public void givenCorrectInputThreeFiveEven_whenRun_thenPrintErrMsg() { + String input = "3 5 even"; + String strategy = input.split(" ")[2]; + + setInput(input); + RandomCharsTable.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + + final String actualResult = getOutputLines()[3]; + removeFromOutput(actualResult); + final String table = getOutput(); + + StringBuilder letters = getLettersFromTable(table); + StringBuilder expectedResult = getExpectedResult(letters,strategy); + assertEquals(expectedResult.toString(), actualResult); + } + + + public StringBuilder getLettersFromTable(String table) { + Pattern pattern = Pattern.compile("[A-Z]"); + Matcher matcher = pattern.matcher(table); + StringBuilder letters = new StringBuilder(); + while (matcher.find()) { + letters.append(matcher.group(0)); + } + return letters; + } + + public StringBuilder getExpectedResult(StringBuilder letters, String strategy) { + StringBuilder expectedResult = new StringBuilder(); + + if (strategy.equals("even")) { + expectedResult.append("Even letters - "); + for (int i = 0; i < letters.length(); i++) { + char ch = letters.charAt(i); + if ((int) ch % 2 == 0) { + expectedResult.append(ch); + expectedResult.append(", "); + } + } + } else { + expectedResult.append("Odd letters - "); + for (int i = 0; i < letters.length(); i++) { + char ch = letters.charAt(i); + if ((int) ch % 2 != 0) { + expectedResult.append(ch); + expectedResult.append(", "); + } + } + } + expectedResult = new StringBuilder(expectedResult.substring(0, expectedResult.length() - 2)); + return expectedResult; + } +} 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..490be0a1 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,122 @@ +package homework_2.traffic_light; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import base.UnitBase; + +public class TrafficLightTest extends UnitBase { + + final String ERR_MSG = "Only 1 non-negative integer is allowed as passed parameter"; + final String WELCOME_MSG = "Enter the number from 0 to 86399"; + final String RED = "[31mRED\u001B[0m"; + final String GREEN = "[32mGREEN\u001B[0m"; + final String YELLOW = "[33mYELLOW\u001B[0m"; + + @Test + public void givenNull_whenRun_thenPrintErrMsg() { + setInput(""); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenString_whenRun_thenPrintErrMsg() { + setInput("someString"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenDouble_whenRun_thenPrintErrMsg() { + setInput("2.55"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void givenMoreArguments_whenRun_thenPrintErrMsg() { + setInput("2 5"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(ERR_MSG, getOutputLines()[0]); + } + + @Test + public void given0_whenRun_thenPrintErrMsg() { + setInput("0"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(GREEN, getOutputLines()[0]); + } + + @Test + public void given65_whenRun_thenPrintErrMsg() { + setInput("65"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(GREEN, getOutputLines()[0]); + } + + @Test + public void given35_whenRun_thenPrintErrMsg() { + setInput("35"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(YELLOW, getOutputLines()[0]); + } + + @Test + public void given55_whenRun_thenPrintErrMsg() { + setInput("55"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(YELLOW, getOutputLines()[0]); + } + + @Test + public void given155_whenRun_thenPrintErrMsg() { + setInput("155"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(YELLOW, getOutputLines()[0]); + } + + @Test + public void given40_whenRun_thenPrintErrMsg() { + setInput("40"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(RED, getOutputLines()[0]); + } + + @Test + public void given114_whenRun_thenPrintErrMsg() { + setInput("114"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals(RED, getOutputLines()[0]); + } + + @Test + public void givenTooBig_whenRun_thenPrintErrMsg() { + setInput("86401"); + TrafficLight.run(); + printOut(); + removeFromOutput(WELCOME_MSG); + assertEquals("The day is over", getOutputLines()[0]); + } +} diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..2dfe0b40 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,25 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class CustomAnnotationTest extends UnitBase { + private final static String DEFAULT_MESSAGE = "Hello, World!"; + + @Test + public void emptyConstructor() { + new FirstProgram(); + printOut(); + assertEquals(DEFAULT_MESSAGE, getOutput()); + } + + @Test + public void nonEmptyConstructor() { + String msg = "Some message"; + new FirstProgram(msg); + printOut(); + assertEquals(msg, getOutput()); + } + +} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..79311b1b --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,45 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +class CustomFileReaderTest extends UnitBase { + private static final String FILE_PATH = "src/main/resources/custom_file_reader/file_for_test.txt"; + + @Test + public void checkRun1() throws IOException { + final String expectedContent = Files.readString(Path.of(FILE_PATH)); + + CustomFileReader.run1(); + printOut(); + final String actualContent = getOutput(); + + assertEquals(expectedContent, actualContent); + } + + @Test + public void checkRun2() throws IOException { + final String expectedContent = Files.readString(Path.of(FILE_PATH)); + + CustomFileReader.run2(); + printOut(); + final String actualContent = getOutput(); + + assertEquals(expectedContent, actualContent); + } + + @Test + public void checkRun3() throws IOException { + final String expectedContent = Files.readString(Path.of(FILE_PATH)); + + CustomFileReader.run3(); + printOut(); + final String actualContent = getOutput(); + + assertEquals(expectedContent, actualContent); + } +} diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..3203593d --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,14 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SingletonTest{ + + @Test + public void checkSingleton() { + Singleton singleton = Singleton.getInstance(); + Singleton anotherSingleton = Singleton.getInstance(); + assertEquals(singleton,anotherSingleton); + } +} 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..dfa459a4 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,48 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomRegexMatcherTest extends UnitBase { + + @Test + public void givenMatching1_whenRun_thenPrintTrue() { + setInput("allzza4279@gmail.com"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("true",getOutput()); + } + + @Test + public void givenMatching2_whenRun_thenPrintTrue() { + setInput("dimatroshkin@mail.ru"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("true",getOutput()); + } + + @Test + public void givenNonMatching1_whenRun_thenPrintFalse() { + setInput("my email is: dimatroshkin@mail.ru"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("false",getOutput()); + } + + @Test + public void givenNonMatching2_whenRun_thenPrintFalse() { + setInput("/.epof@.rert.surr"); + CustomRegexMatcher.run(); + printOut(); + removeFromOutput("Please, enter your string..."); + + assertEquals("false",getOutput()); + } +} diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..011da070 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,91 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PowerOfNumberTest extends UnitBase { + final private static String ERROR_MSG = "Only 2 non-negative integers are allowed"; + + @Test + public void given02_whenRun_thenPrint0() throws Throwable { + setInput("0 2"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(0, Integer.parseInt(getOutput())); + } + + @Test + public void given24_whenRun_thenPrint16() throws Throwable { + setInput("2 4"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(16, Integer.parseInt(getOutput())); + } + + @Test + public void given20_whenRun_thenPrint1() throws Throwable { + setInput("2 0"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(1, Integer.parseInt(getOutput())); + } + + @Test + public void givenOneNumber_whenRun_thenPrintErr() throws Throwable { + setInput("2 "); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenMoreNumbersThenNeeded_whenRun_thenPrintErr() throws Throwable { + setInput("2 3 4"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenString_whenRun_thenPrintErr() throws Throwable { + setInput("asg djj"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenDoubleNumbers_whenRun_thenPrintErr() throws Throwable { + setInput("2.0 3.0"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + + @Test + public void givenNegative_whenRun_thenPrintErr() throws Throwable { + setInput("-2 3"); + PowerOfNumber.run(); + printOut(); + removeFromOutput("Enter 2 non-negative integers"); + + assertEquals(ERROR_MSG, getOutput()); + } + +}