diff --git a/README.md b/README.md index 5d686e9f..f4593e69 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,24 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Rog Elena* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW1. ConsolePrinter | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2.1. TrafficLight | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_2/traffic_light) | traffic_light | +| HW2.2. PyramidPrinter | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_2/pyramid_printer) | pyramid_printer | +| HW2.3. RandomCharsTable | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_2/random_chars_table) | random_chars_table | +| HW3. ImmutableClass | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_3) | immutable_class | +| HW4.1. CustomFileReader | [Custom file reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_4/custom_file_reader) | custom_file_reader | +| HW4.2. Singleton | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_4/singleton) | singleton | +| HW4.3. CustomAnnotation | [Custom annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_4/custom_annotation) | custom_annotation | +| HW5.1. PowerOfNumber | [Power of number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_5/power_of_number) | power_of_number +| HW5.2. CustomRegexMatcher | [Custom regex matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_5/custom_regex_matcher) | custom_regex_matcher +| HW6. MapProblemsGenerator | [Map problems generator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_6/map_problems_generator) | map_problems_generator +| HW7. KittenToCatFunction | [Kitten to cat function](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/homework_7/kitten_to_cat_function) | kitten_to_cat_function +| CourseProject | [Course project](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/main/java/course_project) | course_project +| tests | [Test classes](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/RogElena/src/test/java) | Test classes | [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) + +[Link to codingbat profile](https://codingbat.com/done?user=rog.elena.yu@gmail.com&tag=9660623200) \ No newline at end of file diff --git a/build.gradle b/build.gradle index b91dc843..0fd42aba 100644 --- a/build.gradle +++ b/build.gradle @@ -12,8 +12,13 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + + compileOnly 'org.projectlombok:lombok:1.18.20' + annotationProcessor 'org.projectlombok:lombok:1.18.20' + testCompileOnly 'org.projectlombok:lombok:1.18.20' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.20' } test { useJUnitPlatform() -} \ No newline at end of file +} diff --git a/src/main/java/course_project/Field.java b/src/main/java/course_project/Field.java new file mode 100644 index 00000000..97b7491d --- /dev/null +++ b/src/main/java/course_project/Field.java @@ -0,0 +1,299 @@ +package course_project; + +import lombok.Data; +import lombok.Value; + +import java.util.*; + +@Data +public class Field { + enum cellStatus { + CLEAN, + TOUCHING, + SHIP, + WOUNDED, + SUNK, + MISS + } + private final static int fieldLength = 10; + private static final HashMap cellStatusSign = new HashMap(){{ + put(cellStatus.CLEAN, '~'); + put(cellStatus.TOUCHING, '~'); + put(cellStatus.SHIP, 'U'); + put(cellStatus.WOUNDED, 'x'); + put(cellStatus.SUNK, 'x'); + put(cellStatus.MISS, 'o'); + }}; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_RESET = "\u001B[0m"; + private cellStatus[][] cells = new cellStatus[fieldLength][fieldLength]; + private List listOfShips = new ArrayList<>(); + + public static int[] stringToCell(String str) { + char columnNumberChar = str.substring(0, 1).charAt(0); + int columnNumber; + + if ((int) columnNumberChar > 74) { + return null; + } else { + columnNumber = (int) columnNumberChar - 64; + } + String lineNumberStr = str.substring(1); + + try { + int lineNumber = Integer.parseInt(lineNumberStr); + if (lineNumber < 1 || lineNumber > 10) { + return null; + } + return new int[]{lineNumber - 1, columnNumber - 1}; + } catch (NumberFormatException e) { + return null; + } + } + + public Field() { + for (int i = 0; i < fieldLength; i++) { + for (int j = 0; j < fieldLength; j++) { + cells[j][i] = cellStatus.CLEAN; + } + } + } + + public boolean createShip(int shipLength, String[] shipCoordinates) { + int[] beginningCell; + int[] endCell; + + if (shipLength == 1 && (shipCoordinates.length != 1 || shipCoordinates[0] == null)) { + System.out.println("Error! Wrong length of the ship! Try again.\n"); + return false; + } else if (shipLength > 1 && (shipCoordinates.length != 2 + || shipCoordinates[0] == null + || shipCoordinates[1] == null)) { + System.out.println("Error! Wrong length of the ship! Try again.\n"); + return false; + } + + beginningCell = stringToCell(shipCoordinates[0]); + endCell = shipLength == 1 ? beginningCell : stringToCell(shipCoordinates[1]); + + if (beginningCell == null || endCell == null) { + System.out.println("Error! Wrong enter! Try again.\n"); + return false; + } + + if (checkShip(shipLength, beginningCell, endCell)) { + drawShip(shipLength, beginningCell, endCell); + return true; + } + return false; + } + + private boolean checkShip(int shipLength, int[] beginningCell, int[] endCell) { + if (!cellWithinFieldBoundaries(beginningCell) || !cellWithinFieldBoundaries(endCell)) { + System.out.println("Error! Out of field bounds! Try again.\n"); + return false; + } else if (!Ship.shipIsInAStraightLine(shipLength, beginningCell, endCell)) { + System.out.println("Error! The ship is not in a straight line! Try again.\n"); + return false; + } else if (!Ship.rightShipLength(shipLength, beginningCell, endCell)) { + System.out.println("Error! Wrong length of the ship! Try again.\n"); + return false; + } else if (!cellsAbleToFill(beginningCell, endCell)) { + System.out.println("Error! This cell is not able to be filled with a ship. Try again.\n"); + return false; + } + return true; + } + + private boolean cellWithinFieldBoundaries(int[] cell) { + return cell[0] <= 9 && cell[1] <= 9 && cell[0] >= 0 && cell[1] >= 0; + } + + private boolean cellsAbleToFill(int[] beginningCell, int[] endCell) { + int[][] shipCells = getShipCells(beginningCell, endCell); + if (shipCells != null) { + for (int[] cell : shipCells) { + if (!cellCleanAndNotTouching(cell)) { + return false; + } + } + } + return true; + } + + private int[][] getShipCells(int[] beginningCell, int[] endCell) { + int[][] shipCells; + + if (beginningCell[1] == endCell[1]) { //horizontal + shipCells = new int[Math.abs(beginningCell[0] - endCell[0]) + 1][3]; + int lineMin = Math.min(beginningCell[0], endCell[0]); + int lineMax = Math.max(beginningCell[0], endCell[0]); + for (int i = 0; i <= lineMax - lineMin; i++) { + shipCells[i][0] = lineMin + i; + shipCells[i][1] = beginningCell[1]; + shipCells[i][2] = 0; //status + } + return shipCells; + } else if (beginningCell[0] == endCell[0]) { //vertical + shipCells = new int[Math.abs(beginningCell[1] - endCell[1]) + 1][3]; + int columnMin = Math.min(beginningCell[1], endCell[1]); + int columnMax = Math.max(beginningCell[1], endCell[1]); + for (int i = 0; i <= columnMax - columnMin; i++) { + shipCells[i][0] = beginningCell[0]; + shipCells[i][1] = columnMin + i; + shipCells[i][2] = 0; //status + } + return shipCells; + } + return null; + } + + private boolean cellCleanAndNotTouching(int[] cell) { + int line = cell[0]; + int column = cell[1]; + + if (cells[line][column] != cellStatus.CLEAN) { + return false; + } + + ArrayList adjacentCells = getAdjacentCells(cell); + for (int[] adjacentCell : adjacentCells) { + int adjacentLine = adjacentCell[0]; + int adjacentColumn = adjacentCell[1]; + + if (cells[adjacentLine][adjacentColumn] == cellStatus.SHIP) { + return false; + } + } + return true; + } + + private ArrayList getAdjacentCells(int[] cell) { + int column = cell[0]; + int line = cell[1]; + + ArrayList adjacentCells = new ArrayList<>(); + for (int i = line - 1; i <= line + 1; i++) { + for (int j = column - 1; j <= column + 1; j++) { + int[] checkingCell = new int[]{j, i}; + if (cellWithinFieldBoundaries(checkingCell) && !Arrays.equals(cell, checkingCell)) { + adjacentCells.add(checkingCell); + } + } + } + return adjacentCells; + } + + public void drawTestShips(int[][][] data) { + for (int[][] arr : data) { + drawShip(arr[0][0], arr[1], arr[2]); + } + } + + private void drawShip(int shipLength, int[] beginningCell, int[] endCell) { + int[][] shipCells = getShipCells(beginningCell, endCell); + listOfShips.add(new Ship(shipLength, shipCells)); + + if (shipCells != null) { + for (int[] cell : shipCells) { + int line = cell[0]; + int column = cell[1]; + cells[line][column] = cellStatus.SHIP; + + ArrayList adjacentCells = getAdjacentCells(cell); + for (int[] adjacentCell : adjacentCells) { + int adjacentColumn = adjacentCell[1]; + int adjacentLine = adjacentCell[0]; + + if (cells[adjacentLine][adjacentColumn] != cellStatus.SHIP) { + cells[adjacentLine][adjacentColumn] = cellStatus.TOUCHING; + } + } + } + } + } + + boolean allShipsSunk() { + for (Ship ship : listOfShips) { + if (ship.getShipStatus() != Ship.status.SUNK) { + return false; + } + } + return true; + } + + String shotResult(int[] shotCell) { + int line = shotCell[0]; + int column = shotCell[1]; + cellStatus status = getCellStatus(line, column); + + if (status == cellStatus.SHIP) { + cells[line][column] = cellStatus.WOUNDED; + Ship hitShip = getHitShip(shotCell); + if (hitShip != null && hitShip.getShipStatus() == Ship.status.SUNK) { + setSunkStatusToCells(hitShip); + return "sunk"; + } + return "hit"; + } else if (status == cellStatus.MISS || status == cellStatus.WOUNDED || status == cellStatus.SUNK) { + return "repeat"; + } else { + cells[line][column] = cellStatus.MISS; + } + return "miss"; + } + + private cellStatus getCellStatus(int line, int column) { + return cells[line][column]; + } + + private Ship getHitShip(int[] shotCell) { + for (Ship ship : listOfShips) { + if (ship.cellBelongsToShip(shotCell)) { + ship.setShipStatus(Ship.status.HIT); + ship.setCellHit(shotCell); + return ship; + } + } + return null; + } + + private void setSunkStatusToCells(Ship ship) { + int[][] shipCells = ship.getShipCells(); + + for (int[] shipCell : shipCells) { + int line = shipCell[0]; + int column = shipCell[1]; + cells[line][column] = cellStatus.SUNK; + } + } + + void printField(boolean showShips) { + System.out.print(" "); + char c = 0x0041; + + for (int i = 1; i <= fieldLength; i++) { + System.out.print(c + " "); + c += 1; + } + System.out.print("\n"); + + for (int i = 0; i < fieldLength; i++) { + System.out.print(i < 9 ? " " + (i + 1) : " " + (i + 1)); + for (int j = 0; j < fieldLength; j++) { + System.out.print(" "); + if (!showShips && (cells[i][j] == cellStatus.SHIP || cells[i][j] == cellStatus.TOUCHING)) { + System.out.print(cellStatusSign.get(cellStatus.CLEAN)); + } else if (cells[i][j] == cellStatus.SUNK) { + System.out.print(ANSI_RED + cellStatusSign.get(cells[i][j]) + ANSI_RESET); + } else { + System.out.print(cellStatusSign.get(cells[i][j])); + } + } + System.out.println(); + } + System.out.print("\n"); + } + +} + diff --git a/src/main/java/course_project/Player.java b/src/main/java/course_project/Player.java new file mode 100644 index 00000000..7b6adec5 --- /dev/null +++ b/src/main/java/course_project/Player.java @@ -0,0 +1,82 @@ +package course_project; + +import lombok.Data; +import java.util.Scanner; +import java.util.TreeMap; +import java.util.regex.Pattern; + +@Data +public class Player { + public static int numberOfUsers; + private String name; + private Field field; + private Scanner scanner; + + public Player(String name, Scanner scanner) { + this.name = name == null || !(Pattern.matches("[a-zA-Z]+", name)) ? "Unknown" + ++numberOfUsers : name; + this.field = new Field(); + this.scanner = scanner; + } + + void fillField(TreeMap numberOfShips) throws InterruptedException { + field.printField(true); + + for (Integer key : numberOfShips.keySet()) { + int numberOfShipType = numberOfShips.get(key); + + for (int i = 0; i < numberOfShipType; i++) { + boolean shipCreated = false; + + while (!shipCreated) { + System.out.println(this.name + ", enter the coordinates of the ship (" + key + " cell(s))."); + System.out.println("Input format must be \"A1 A2\" or \"A1 B1\" for multitube ship and \"A1\" for one-pipe ship.\n"); + String shot = scanner.nextLine(); + String[] shipCoordinates = shot.trim().split("\\s"); + shipCreated = field.createShip(key, shipCoordinates); + + if (!shipCreated) { + field.printField(true); + } else { + field.printField(true); + } + } + } + } + Thread.sleep(4000); + } + + int[] makeShot() { + String shot = ""; + boolean shotFired = false; + int[] shotCell = new int[]{}; + System.out.println(this.name + ", enter the coordinates of the shot.\n"); + + while (!shotFired) { + shot = scanner.nextLine(); + if (shot == null || "".equals(shot)) { + System.out.println("Error! You entered the wrong coordinates! Try again.\n"); + continue; + } + shotCell = Field.stringToCell(shot); + if (shotCell == null) { + System.out.println("Error! You entered the wrong coordinates! Try again.\n"); + } else { + shotFired = true; + } + } + return shotCell; + } + + String checkShot(int[] shotCell) { + return field.shotResult(shotCell); + } + + boolean allShipsSunk() { + return field.allShipsSunk(); + } + + public void printField(boolean showShips) { + field.printField(showShips); + } + +} diff --git a/src/main/java/course_project/SeaBattle.java b/src/main/java/course_project/SeaBattle.java new file mode 100644 index 00000000..488ba975 --- /dev/null +++ b/src/main/java/course_project/SeaBattle.java @@ -0,0 +1,121 @@ +package course_project; + +import lombok.Data; +import java.util.Collections; +import java.util.Scanner; +import java.util.TreeMap; + +@Data +public class SeaBattle { + static final TreeMap numberOfShips = new TreeMap(Collections.reverseOrder()) {{ + put(4, 1); + put(3, 2); + put(2, 3); + put(1, 4); + }}; + private static Scanner scanner = new Scanner(System.in); + private Player player1; + private Player player2; + private SeaBattleTestService service = null; + + public static void main(String[] args) throws InterruptedException { + System.out.println("Player1, enter your name."); + String playerName1 = scanner.nextLine(); + System.out.println("\nPlayer2, enter your name."); + String playerName2 = scanner.nextLine(); + + System.out.println("Do you want an auto-alignment of ships? (Y/N)\n"); + String replay = scanner.nextLine().toLowerCase(); + if (!"y".equals(replay) && !"n".equals((replay))) { + System.out.println("The game is canselled. Goodbye!\n"); + scanner.close(); + return; + } + + SeaBattle game = new SeaBattle(playerName1, playerName2); + if ("n".equals(replay)) { + System.out.println("Thank you. The game is started.\n"); + game.fillFields(); + + } else if ("y".equals(replay)) { + System.out.println("\nThank you. The game is started only for testing (no random placement).\n"); + Thread.sleep(4000); + game.service = new SeaBattleTestService(game.getPlayer1(), game.getPlayer2()); + + System.out.println(game.getPlayer1().getName() + ", here is your field.\n"); + game.getPlayer1().printField(true); + Thread.sleep(4000); + clearScreen(); + + System.out.println(game.getPlayer2().getName() + ", here is your field.\n"); + game.getPlayer2().printField(true); + Thread.sleep(4000); + clearScreen(); + } + + System.out.println("Ships are drawn. Let's start shooting.\n"); + Player winner = game.makeShots(); + System.out.println("Congratulations! " + winner.getName() + " is the winner!\n"); + Thread.sleep(4000); + + System.out.println("The field of the winner.\n"); + winner.printField(true); + + scanner.close(); + } + + public SeaBattle(String playerName1, String playerName2) { + this.player1 = new Player(playerName1, scanner); + this.player2 = new Player(playerName2, scanner); + } + + private void fillFields() throws InterruptedException { + player1.fillField(numberOfShips); + clearScreen(); + System.out.println("Next player's turn.\n"); + player2.fillField(numberOfShips); + } + + private Player makeShots() throws InterruptedException { + Player nextPlayer = player1; + Player firedPlayer = player2; + boolean gameOver = false; + + clearScreen(); + while (!gameOver) { + firedPlayer.printField(false); + int[] shotCell = nextPlayer.makeShot(); + String shotResult = firedPlayer.checkShot(shotCell); + + if ("miss".equals(shotResult)) { + System.out.println("You missed. Next player's turn.\n"); + firedPlayer.printField(false); + firedPlayer = nextPlayer; + nextPlayer = nextPlayer == player1 ? player2 : player1; + Thread.sleep(4000); + clearScreen(); + } else if ("repeat".equals(shotResult)) { + System.out.println("Error! You have already shot this cell! Try again.\n"); + } else if ("hit".equals(shotResult)) { + System.out.println("Congratulations! You hit the ship! Try again.\n"); + } else if ("sunk".equals(shotResult)) { + gameOver = firedPlayer.allShipsSunk(); + if (gameOver) { + System.out.println("You sunk all ships!\n"); + firedPlayer.printField(false); + } else { + System.out.println("Congratulations! You sunk the ship! Try again.\n"); + } + } + } + return nextPlayer; + } + + public static void clearScreen() { + for (int i = 0; i < 50; ++i) { + System.out.println(); + } + } + +} + diff --git a/src/main/java/course_project/SeaBattleTestService.java b/src/main/java/course_project/SeaBattleTestService.java new file mode 100644 index 00000000..c9e2ae28 --- /dev/null +++ b/src/main/java/course_project/SeaBattleTestService.java @@ -0,0 +1,33 @@ +package course_project; + +import lombok.Data; + +@Data +public class SeaBattleTestService { + public SeaBattleTestService(Player player1, Player player2) { + fillFields(player1, 0); + fillFields(player2, 1); + } + + private void fillFields(Player player, int coordinateShift) { + Field field = player.getField(); + field.drawTestShips(getMatrix(coordinateShift)); + } + + private int[][][] getMatrix(int cs) { + int[][][] matrix = { + {{4, 0}, {2 + cs, 0 + cs}, {2 + cs, 3 + cs}}, + {{3, 0}, {0 + cs, 2 + cs}, {0 + cs, 4 + cs}}, + {{3, 0}, {6 + cs, 8 + cs}, {8 + cs, 8 + cs}}, + {{2, 0}, {5 + cs, 2 + cs}, {5 + cs, 3 + cs}}, + {{2, 0}, {5 + cs, 5 + cs}, {5 + cs, 6 + cs}}, + {{2, 0}, {7 + cs, 1 + cs}, {8 + cs, 1 + cs}}, + {{1, 0}, {0 + cs, 0 + cs}, {0 + cs, 0 + cs}}, + {{1, 0}, {1 + cs, 8 + cs}, {1 + cs, 8 + cs}}, + {{1, 0}, {3 + cs, 6 + cs}, {3 + cs, 6 + cs}}, + {{1, 0}, {7 + cs, 4 + cs}, {7 + cs, 4 + cs}} + }; + return matrix; + } + +} diff --git a/src/main/java/course_project/Ship.java b/src/main/java/course_project/Ship.java new file mode 100644 index 00000000..c5742093 --- /dev/null +++ b/src/main/java/course_project/Ship.java @@ -0,0 +1,65 @@ +package course_project; + +import lombok.Data; + +@Data +public class Ship { + enum status { + INTACT, + HIT, + SUNK + } + private int shipLength; + private int[][] shipCells; + private status shipStatus; + + public Ship(int shipLength, int[][] shipCells) { + this.shipLength = shipLength; + this.shipCells = shipCells; + this.shipStatus = status.INTACT; + } + + public static boolean shipIsInAStraightLine(int shipLength, int[] beginningCell, int[] endCell) { + return beginningCell[0] == endCell[0] || beginningCell[1] == endCell[1]; + } + + public static boolean rightShipLength(int shipLength, int[] beginningCell, int[] endCell) { + if (shipLength == 1) { + return Math.abs(beginningCell[0] - endCell[0]) + 1 == shipLength && + Math.abs(beginningCell[1] - endCell[1]) + 1 == shipLength; + } + return Math.abs(beginningCell[0] - endCell[0]) + 1 == shipLength || + Math.abs(beginningCell[1] - endCell[1]) + 1 == shipLength; + } + + public boolean cellBelongsToShip(int[] shipCell) { + for (int[] cell : shipCells) { + if (cell[0] == shipCell[0] && cell[1] == shipCell[1]) { + return true; + } + } + return false; + } + + public void setCellHit(int[] shipCell) { + for (int[] cell : shipCells) { + if (cell[0] == shipCell[0] && cell[1] == shipCell[1]) { + cell[2] = 1; + } + } + + if (shipSunk()) { + shipStatus = status.SUNK; + } + } + + private boolean shipSunk() { + for (int[] cell : shipCells) { + if (cell[2] != 1) { + return false; + } + } + return true; + } + +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..77868e48 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,9 +1,16 @@ package homework_1; public class Main { + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_RESET = "\u001B[0m"; - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - -} + public static void main(String[] args) { + for (String arg : args) { + if ("error".equalsIgnoreCase(arg)) { + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); + break; + } + System.out.println(arg + ": " + arg.length() + " letter(s)"); + } + } +} \ No newline at end of file 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..57072e16 --- /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(); + } +} \ No newline at end of file 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..fc07f777 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,34 @@ +package homework_2.pyramid_printer; + +import lombok.Data; +import java.util.InputMismatchException; +import java.util.Scanner; + +@Data +public class PyramidPrinter { + + public void run() { + try (Scanner scanner = new Scanner(System.in)) { + String str = scanner.nextLine(); + int number = Integer.parseInt(str); + System.out.println(buildPyramidString(number)); + } catch (NumberFormatException | ArithmeticException | InputMismatchException ex) { + System.out.println("Only non-negative integer is allowed as passed parameter!"); + } + } + + StringBuilder buildPyramidString(int number) { + StringBuilder pyramidString = new StringBuilder(); + if (number < 0) { + throw new ArithmeticException(); + } + + for (int i = 0; i < number; i++) { + for (int j = 0; j <= i; j++) { + pyramidString.append('x'); + } + pyramidString.append('\n'); + } + return pyramidString; + } +} \ 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..bdb56ffe --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,7 @@ +package homework_2.random_chars_table; + +public class Main { + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..cbb712fd --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,113 @@ +package homework_2.random_chars_table; + +import lombok.Data; +import java.util.*; + +@Data +public class RandomCharsTable { + public enum Strategy { + EVEN, + ODD + } + private int length; + private int width; + private Strategy strategy; + private int[][] table; + + public void run() { + Scanner scanner = new Scanner(System.in); + String[] arr = scanner.nextLine().trim().split("\\s"); + scanner.close(); + + try { + setParameters(arr); + } catch (IllegalArgumentException ex) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]!"); + return; + } + initializeTable(); + + System.out.println(getStrForPrinting()); + System.out.println(getStrForPrintingByStrategy(getStrategy())); + } + + public void setParameters(String[] arr) { + if (arr.length != 3) { + throw new IllegalArgumentException(); + } + + length = Integer.parseInt(arr[0]); + width = Integer.parseInt(arr[1]); + if (length < 1 || width < 1) { + throw new IllegalArgumentException(); + } + + String strategyStr = arr[2]; + if (Strategy.EVEN.equals(Strategy.valueOf(strategyStr.toUpperCase())) || Strategy.ODD.equals(Strategy.valueOf(strategyStr.toUpperCase()))) { + strategy = Strategy.valueOf(strategyStr.toUpperCase()); + } else { + throw new IllegalArgumentException(); + } + } + + public void initializeTable() { + table = new int[length][width]; + + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + table[i][j] = getRandomChar(); + } + } + } + + private char getRandomChar() { + Random rnd = new Random(); + return (char) ('A' + rnd.nextInt(26)); + } + + public StringBuilder getStrForPrinting() { + int[][] table = getTable(); + StringBuilder result = new StringBuilder(); + + for (int i = 0; i < table.length; i++) { + for (int j = 0; j < table[i].length; j++) { + result.append("|" + (char) table[i][j]); + } + result.append("|" + "\n"); + } + return result; + } + + public StringBuilder getStrForPrintingByStrategy(Strategy strategy) { + int[][] table = getTable(); + StringBuilder result = new StringBuilder(); + int remainder; + + if (strategy == Strategy.ODD) { + result.append("Odd letters: "); + remainder = 1; + } else { + result.append("Even letters: "); + remainder = 0; + } + + boolean firstPrint = true; + for (int i = 0; i < table.length; i++) { + for (int j = 0; j < table[i].length; j++) { + int currentChar = table[i][j]; + if (currentChar % 2 == remainder) { + String substr = String.valueOf((char) currentChar); + if (result.toString().contains(substr)) { + continue; + } + if (!firstPrint) { + result.append(", "); + } + result.append((char) currentChar); + firstPrint = false; + } + } + } + return result; + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..071437b1 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,7 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args) { + new TrafficLight().run(); + } +} \ No newline at end of file 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..6a0dc118 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,79 @@ +package homework_2.traffic_light; + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +public class TrafficLight { + public enum Colour { + RED, + YELLOW, + GREEN + } + public static Map coloursForPrinting = new HashMap(); + private Colour trafficLightColour; + + static { + coloursForPrinting.put(Colour.RED, "\u001B[31m"); + coloursForPrinting.put(Colour.YELLOW, "\u001B[33m"); + coloursForPrinting.put(Colour.GREEN, "\u001B[32m"); + } + + public void run() { + Scanner scanner = new Scanner(System.in); + String str = scanner.nextLine(); + + scanner.close(); + try { + int seconds = Integer.parseInt(str); + try { + this.setTrafficLightColour(seconds); + printColour(); + } + catch (WrongSecondsException e) { + System.out.println(e.getMessage()); + } + } catch (NumberFormatException ex) { + System.out.println("Error! Only numbers!"); + } + } + + public void setTrafficLightColour(int seconds) throws WrongSecondsException { + if (seconds < 0) + throw new WrongSecondsException("Only non-negative integer is allowed as passed parameter!"); + else if (seconds >= 86400) + throw new WrongSecondsException("Error! Day is over!"); + else { + int secondsRemainder = seconds % 60; + if (secondsRemainder < 35) + this.setTrafficLightColour(Colour.GREEN); + else if (secondsRemainder >= 40 && secondsRemainder < 55) + this.setTrafficLightColour(Colour.RED); + else // (secondsRemainder >= 35 && secondsRemainder < 40) + // || (secondsRemainder >= 55 && secondsRemainder < 60) + this.setTrafficLightColour(Colour.YELLOW); + } + } + + class WrongSecondsException extends Exception { + + WrongSecondsException(String msg) { + super(msg); + } + } + + public void setTrafficLightColour(Colour colour) { + this.trafficLightColour = colour; + } + + public void printColour() { + final String ANSI_RESET = "\u001B[0m"; + Colour currentColour = this.getTrafficLightColour(); + + System.out.println(coloursForPrinting.get(currentColour) + currentColour + ANSI_RESET); + } + + public Colour getTrafficLightColour() { + return this.trafficLightColour; + } +} \ No newline at end of file diff --git a/src/main/java/homework_3/library/Author.java b/src/main/java/homework_3/library/Author.java new file mode 100644 index 00000000..2d9d4890 --- /dev/null +++ b/src/main/java/homework_3/library/Author.java @@ -0,0 +1,36 @@ +package homework_3.library; + +import lombok.Data; + +@Data +public class Author implements Cloneable { + private String name; + private String country; + private String century; + + public Author(String name) { + if (name == null || "".equals(name.trim())) { + throw new IllegalArgumentException(); + } + this.name = name; + } + + public Author(String name, String country, String century) { + if (name == null || "".equals(name.trim())) { + throw new IllegalArgumentException(); + } + this.name = name; + this.country = country; + this.century = century; + } + + @Override + protected Author clone() { + return new Author(this.name, this.country, this.century); + } + + @Override + public String toString() { + return name; + } +} diff --git a/src/main/java/homework_3/library/LibraryCard.java b/src/main/java/homework_3/library/LibraryCard.java new file mode 100644 index 00000000..cb9be924 --- /dev/null +++ b/src/main/java/homework_3/library/LibraryCard.java @@ -0,0 +1,96 @@ +/* + * List of ImmutableClass requirements: + * 1) class must be final; + * 2) all fields must be final; + * 3) methods-mutators must return a new copy of the object; + */ + +package homework_3.library; + +import lombok.Getter; +import java.util.*; + +@Getter +public final class LibraryCard { + private enum Section { + MYSTERY, + HORROR, + HISTORICAL, + ROMANCE, + SIENCE_FICTION, + FANTASY, + REALIST_LITERATURE + } + private final Author author; + private final String title; + private final Section section; + private final Calendar yearOfPublishing; + private final int numberOfPages; + + public static LibraryCard initializeNewLibraryCard (Author author, String title, + GregorianCalendar yearOfPublishing, int numberOfPages, String sectionStr) + throws IllegalArgumentException { + if (author == null + || title == null + || "".equals(title.trim()) + || yearOfPublishing.equals(new GregorianCalendar(0, Calendar.JANUARY, 0)) + || yearOfPublishing.after(new GregorianCalendar()) + || numberOfPages == 0) { + throw new IllegalArgumentException(); + } + Section section; + + if (sectionStr != null) { + section = initializeSection(sectionStr); + } else section = null; + + if (section == null) { + return new LibraryCard(author, title, yearOfPublishing, numberOfPages); + } else { + return new LibraryCard(author, title, yearOfPublishing, numberOfPages, section); + } + } + + static private Section initializeSection(String sectionStr) { + for (Section section : Section.values()) { + if (section.equals(Section.valueOf(sectionStr.toUpperCase()))) { + return section; + } + } + return null; + } + + public LibraryCard(Author author, String title, Calendar yearOfPublishing, int numberOfPages, Section section) { + this.title = title; + this.author = author; + this.yearOfPublishing = yearOfPublishing; + this.numberOfPages = numberOfPages; + this.section = section; + } + + public LibraryCard(Author author, String title, Calendar yearOfPublishing, int numberOfPages) { + this.title = title; + this.author = author; + this.yearOfPublishing = yearOfPublishing; + this.numberOfPages = numberOfPages; + this.section = Section.REALIST_LITERATURE; + } + + @Override + public String toString() { + return getAuthor() + " \"" + + getTitle() + " \", " + + getYearOfPublishing().get(Calendar.YEAR) + ", " + + getNumberOfPages() + " pp. (" + + getSection() + ")"; + } + + public Author getAuthor() { + return author.clone(); + } + + public Calendar getYearOfPublishing() { + return (Calendar) yearOfPublishing.clone(); + } + +} diff --git a/src/main/java/homework_3/library/Main.java b/src/main/java/homework_3/library/Main.java new file mode 100644 index 00000000..1582f17f --- /dev/null +++ b/src/main/java/homework_3/library/Main.java @@ -0,0 +1,22 @@ +package homework_3.library; + +import java.util.Calendar; +import java.util.GregorianCalendar; + +public class Main { + public static void main(String[] args) { + LibraryCard lc; + + try { + lc = LibraryCard.initializeNewLibraryCard(new Author(" ", "France", "19"), + "Les Misérables", + new GregorianCalendar(2020, Calendar.JANUARY, 1), + 1248, + null); + } catch (IllegalArgumentException e) { + System.out.println("Error! No author, title, year of publishing or number of pages!"); + return; + } + System.out.println(lc); + } +} 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..b426e029 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -0,0 +1,15 @@ +package homework_4.custom_annotation; + +import homework_3.library.Author; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface CustomAnnotation { + float v() default 1.1f; + Author DEFAULT_AUTHOR = new Author("Rog Elena", "Russia", null); + String DEFAULT_COUNTRY = DEFAULT_AUTHOR.getCountry(); +} \ No newline at end of file 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..301f275a --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Main.java @@ -0,0 +1,13 @@ +package homework_4.custom_annotation; + +@CustomAnnotation(v = 1.2f) +public class Main { + public static void main(String[] args) { + new Main().run(); + } + + public void run() { + CustomAnnotation annotation = Main.class.getAnnotation(CustomAnnotation.class); + System.out.println("Author: " + annotation.DEFAULT_AUTHOR + " (" + annotation.DEFAULT_COUNTRY + "), version: " + annotation.v()); + } +} \ No newline at end of file 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..bc6c32a2 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,130 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; + +public class CustomFileReader { + + public void run1() { + String str; + + try { + str = readFileFileReader("src/main/resources/custom_file_reader.txt"); + String str2 = replaceDotsCommas(str); + print(str2); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void run2() { + String str; + RandomAccessFile file = null; + + try { + file = getFile("src/main/resources/custom_file_reader.txt"); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + try { + str = readFileInChannel(file); + String str2 = replaceDotsCommas(str); + print(str2); + } catch (NullPointerException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void run3() { + String str; + + try { + str = readFileInputStream("src/main/resources/custom_file_reader.txt"); + String str2 = replaceDotsCommas(str); + print(str2); + } catch (NullPointerException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String readFileFileReader(String path) throws IOException { + StringBuilder strb = new StringBuilder(); + + try (FileReader reader = new FileReader(path)) { + int i; + + while ((i = reader.read()) != -1) { + strb.append((char) i); + } + } catch (IOException e) { + throw new IOException(e.getMessage()); + } + + return strb.toString(); + } + + public RandomAccessFile getFile (String path) throws FileNotFoundException { + RandomAccessFile file; + + try { + file = new RandomAccessFile(path, "r"); + } catch (FileNotFoundException e) { + throw new FileNotFoundException(e.getMessage()); + } + + return file; + } + + public String readFileInChannel(RandomAccessFile file) throws IOException { + FileChannel channel = file.getChannel(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + int bufferSize = 1024; + if (bufferSize > channel.size()) { + bufferSize = (int) channel.size(); + } + ByteBuffer buff = ByteBuffer.allocate(bufferSize); + + while (channel.read(buff) > 0) { + out.write(buff.array(), 0, buff.position()); + buff.clear(); + } + String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8); + file.close(); + out.close(); + channel.close(); + + return fileContent; + } + + public String readFileInputStream(String path) throws IOException { + StringBuilder strb = new StringBuilder(); + FileInputStream fileInputStream = new FileInputStream(path); + BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream, 200); + + int i; + while ((i = bufferedInputStream.read()) != -1) { + strb.append((char) i); + } + fileInputStream.close(); + bufferedInputStream.close(); + + return strb.toString(); + } + + public String replaceDotsCommas(String str) { + String str2 = str.replaceAll("\\.", ""); + return str2.replaceAll(",", ""); + } + + private void print(String str) { + System.out.println(str); + } +} 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..f43bae20 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,11 @@ +package homework_4.custom_file_reader; + + +public class Main { + + public static void main(String[] args) { + new CustomFileReader().run1(); + new CustomFileReader().run2(); + new CustomFileReader().run3(); + } +} \ No newline at end of file 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..174893f9 --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,9 @@ +package homework_4.singleton; + + +public class Main { + + public static void main(String[] args) { + Singleton.getInstance("Dobrynya").run(); + } +} \ No newline at end of file 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..af73d7bc --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,41 @@ +package homework_4.singleton; + +import lombok.Data; +import java.util.Random; + + +@Data +public class Singleton { + private static volatile Singleton instance; + private int age; + private String name; + + public void run() { + Singleton singleGameHero2 = Singleton.getInstance("Ilya"); + + System.out.println(this.hashCode() + ", age: " + this.getAge() + ", name: " + this.getName()); + System.out.println(singleGameHero2.hashCode() + ", age: " + singleGameHero2.getAge() + ", name: " + singleGameHero2.getName()); + } + + private Singleton() {} + + private Singleton(String name) { + this.name = name; + this.age = new Random().nextInt(17) + 34; + } + + public static Singleton getInstance(String name) { + Singleton localGameHero = instance; + + if (localGameHero == null) { + synchronized (Singleton.class) { + localGameHero = instance; + if (localGameHero == null) { + instance = localGameHero = new Singleton(name); + } + } + } + return localGameHero; + } +} + 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..440b660b --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,26 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class CustomRegexMatcher { + public void run() { + try (Scanner scanner = new Scanner(System.in)) { + String str = scanner.nextLine(); + //String str = "Java_Core_June_2021.package homework_5.custom_regex_matcher"; + String regex = ".[package\\s][homework_][1-9]+[.]."; + boolean result = validateString(str, regex); + + System.out.println(result); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public boolean validateString(String str, String regex) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(str); + return matcher.find(); + } +} \ No newline at end of file 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..0a1aad95 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} \ No newline at end of file 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..f8ac9c46 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,9 @@ +package homework_5.power_of_number; + + +public class Main { + + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} \ No newline at end of file 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..f32093c1 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,47 @@ +package homework_5.power_of_number; + + +import java.util.InputMismatchException; +import java.util.Scanner; + + +class PowerOfNumber { + + public void run() { + + try (Scanner scanner = new Scanner(System.in)) { + String[] arr = scanner.nextLine().trim().split("\\s"); + int[] numbers = validateNumbers(arr); + int result = calculateNumberInPower(numbers[0], numbers[1]); + + System.out.println(result); + } catch (NumberFormatException | InputMismatchException ex) { + System.out.println("Only two non-negative integer is allowed!"); + } + } + + public int[] validateNumbers(String[] arr) { + int[] numbers = new int[2]; + + if (arr.length != 2) { + throw new InputMismatchException(); + } + numbers[0] = Integer.parseInt(arr[0]); + numbers[1] = Integer.parseInt(arr[1]); + + for (int i : numbers) { + if (i < 0) { + throw new InputMismatchException(); + } + } + + return numbers; + } + + public int calculateNumberInPower(int number, int power) { + if (power == 0) { + return 1; + } + return number * calculateNumberInPower(number, power - 1); + } +} \ No newline at end of file diff --git a/src/main/java/homework_6/map_problems_generator/CollisionClass.java b/src/main/java/homework_6/map_problems_generator/CollisionClass.java new file mode 100644 index 00000000..dfcd7aec --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/CollisionClass.java @@ -0,0 +1,29 @@ +package homework_6.map_problems_generator; + +import lombok.Data; +import java.util.Calendar; + +@Data +public class CollisionClass { + private Calendar dateOfBirth; + + CollisionClass(Calendar dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + @Override + public int hashCode() { + return 1; + } + + @Override + public boolean equals(Object obj) { + return dateOfBirth.equals(((CollisionClass) obj).getDateOfBirth()); + } + + @Override + public String toString() { + return dateOfBirth.getTime().toString(); + } +} + diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java new file mode 100644 index 00000000..39d54ab1 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,7 @@ +package homework_6.map_problems_generator; + +public class Main { + public static void main(String[] args) { + new MapProblemsGenerator().run(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java new file mode 100644 index 00000000..a45d6c08 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,38 @@ +package homework_6.map_problems_generator; + +import java.util.*; + +public class MapProblemsGenerator { + public void run() { + + HashMap collisionMap = new HashMap<>(); + + collisionMap.put(new CollisionClass(new GregorianCalendar(1905, 1,2)), "Ayn Rand"); + collisionMap.put(new CollisionClass(new GregorianCalendar(1905, 8,18)), "Greta Garbo"); + collisionMap.put(new CollisionClass(new GregorianCalendar(1905, 11,30)), "Daniil Harms"); + + System.out.println("The same year of birth -> the same hashcode -> the same bucket:"); + collisionMap.forEach((key, value) -> System.out.println("hashcode " + key.hashCode() + ": " + key + ", " + value)); + System.out.println(); + + HashMap mutableMap = new HashMap<>(); + + MutableClass aynRandDateOfBirth = new MutableClass(new GregorianCalendar(1905, 1,2)); + MutableClass gretaGarboDateOfBirth = new MutableClass(new GregorianCalendar(1905, 8,18)); + MutableClass daniilHarmsDateOfBirth = new MutableClass(new GregorianCalendar(1905, 11,30)); + + mutableMap.put(aynRandDateOfBirth, "Ayn Rand"); + mutableMap.put(gretaGarboDateOfBirth, "Greta Garbo"); + mutableMap.put(daniilHarmsDateOfBirth, "Daniil Harms"); + mutableMap.forEach((key, value) -> System.out.println("hashcode " + key.hashCode() + ": " + key.toString() + ", " + value)); + + aynRandDateOfBirth.setDateOfBirth(new GregorianCalendar(1905, 1,3)); + gretaGarboDateOfBirth.setDateOfBirth(new GregorianCalendar(1905, 8,19)); + daniilHarmsDateOfBirth.setDateOfBirth(new GregorianCalendar(1905, 11,29)); + System.out.println("Each time new hashcode of the same element -> each time new bucket for element searching:"); + System.out.println("Ayn Rand searching: " + mutableMap.get(aynRandDateOfBirth)); + System.out.println("Greta Garbo searching: " + mutableMap.get(gretaGarboDateOfBirth)); + System.out.println("Daniil Harms searching: " + mutableMap.get(daniilHarmsDateOfBirth)); + } +} + diff --git a/src/main/java/homework_6/map_problems_generator/MutableClass.java b/src/main/java/homework_6/map_problems_generator/MutableClass.java new file mode 100644 index 00000000..cda068dc --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MutableClass.java @@ -0,0 +1,31 @@ +package homework_6.map_problems_generator; + +import lombok.Data; + +import java.util.Calendar; +import java.util.Random; + +@Data +public class MutableClass { + private Calendar dateOfBirth; + + MutableClass(Calendar dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + @Override + public int hashCode() { + return dateOfBirth == null ? 0 : dateOfBirth.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return dateOfBirth.equals(((MutableClass) obj).getDateOfBirth()); + } + + @Override + public String toString() { + return dateOfBirth.getTime().toString(); + } +} + diff --git a/src/main/java/homework_7/kitten_to_cat_function/Cat.java b/src/main/java/homework_7/kitten_to_cat_function/Cat.java new file mode 100644 index 00000000..d5eae1f7 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Cat.java @@ -0,0 +1,22 @@ +package homework_7.kitten_to_cat_function; + +import lombok.Data; + +@Data +public class Cat { + public enum Sex { + MALE, + FEMALE + } + private String name; + private Sex sex; + private int ageInYears; + private String colour; + + public Cat(String name, Sex sex, int ageInYears, String colour) { + this.name = name; + this.sex = sex; + this.ageInYears = ageInYears; + this.colour = colour; + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/Kitten.java b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java new file mode 100644 index 00000000..69c37eb0 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java @@ -0,0 +1,24 @@ +package homework_7.kitten_to_cat_function; + +import lombok.Data; + +@Data +public class Kitten { + private String name; + private Cat.Sex sex; + private String colour; + private int ageInMonths; + private String motherName; + private String fatherName; + private int kittenInLitter; + + public Kitten(String name, Cat.Sex sex, String colour, int ageInMonths, String motherName, String fatherName, int kittenInLitter) { + this.name = name; + this.sex = sex; + this.colour = colour; + this.ageInMonths = ageInMonths; + this.motherName = motherName; + this.fatherName = fatherName; + this.kittenInLitter = kittenInLitter; + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java new file mode 100644 index 00000000..4baf2ed1 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7.kitten_to_cat_function; + +@FunctionalInterface +interface KittenToCatFunction { + Cat grow(Kitten kitten); +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/Main.java b/src/main/java/homework_7/kitten_to_cat_function/Main.java new file mode 100644 index 00000000..4f50a288 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Main.java @@ -0,0 +1,25 @@ +package homework_7.kitten_to_cat_function; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Main { + public static void main(String[] args) { + Kitten martha = new Kitten("Martha", Cat.Sex.FEMALE, "red", + 12, "Daina", "Boris", 3); + Kitten martin = new Kitten("Martin", Cat.Sex.MALE, "red and white", + 12, "Daina", "Boris", 3); + Kitten martisha = new Kitten("Martisha", Cat.Sex.MALE, "black and white", + 12, "Martha", "Martin", 3); + + List kittens = new ArrayList<>(); + kittens.add(martha); + kittens.add(martin); + kittens.add(martisha); + + KittenToCatFunction function = k -> new Cat(k.getName(), k.getSex(), k.getAgeInMonths() / 12, k.getColour()); + Cat[] cats = kittens.stream().map(k -> function.grow(k)).toArray(Cat[]::new); + Arrays.stream(cats).forEach(System.out::println); + } +} \ No newline at end of file diff --git a/src/main/resources/custom_file_reader.txt b/src/main/resources/custom_file_reader.txt new file mode 100644 index 00000000..445972b6 --- /dev/null +++ b/src/main/resources/custom_file_reader.txt @@ -0,0 +1,28 @@ +You think I'm delirious with malaria? + +This happened. +In Odessa, this happened. + +"I'll come at four," promised Maria. + +Eight... +Nine... +Ten. + +Soon after, +The evening, +Frowning, +And Decemberish, + +Left the windows +And vanished in dire darkness. + +Behind me, I hear the neighing and laughter +Of candelabras. + +You wouldn't recognize me if you knew me prior: +A bulk of sinews +Moaning, +Fidgeting. +What can such a clod desire? +But a clod desires many things. \ No newline at end of file diff --git a/src/test/java/course_project/SeaBattleTest.java b/src/test/java/course_project/SeaBattleTest.java new file mode 100644 index 00000000..a6802172 --- /dev/null +++ b/src/test/java/course_project/SeaBattleTest.java @@ -0,0 +1,169 @@ +package course_project; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.TreeMap; + +import static org.junit.jupiter.api.Assertions.*; + +class SeaBattleTest { + + @Test + void setPlayerNamesTest() { + Player.numberOfUsers = 0; + SeaBattle game = new SeaBattle("\n", " "); + Assertions.assertEquals("Unknown1", game.getPlayer1().getName()); + Assertions.assertEquals("Unknown2", game.getPlayer2().getName()); + } + + @Test + void stringToCellTest() { + Assertions.assertArrayEquals(new int[]{3, 0}, Field.stringToCell("A4")); + Assertions.assertArrayEquals(new int[]{0, 9}, Field.stringToCell("J1")); + } + + @Test + void wrongCaseStringToCellTest() { + Assertions.assertNull(Field.stringToCell("A14")); + Assertions.assertNull(Field.stringToCell("A-4")); + Assertions.assertNull(Field.stringToCell("M4")); + Assertions.assertNull(Field.stringToCell("a4")); + Assertions.assertNull(Field.stringToCell("4")); + } + + @Test + void shipRightCreationTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Assertions.assertTrue(game.getPlayer1().getField().createShip(4, new String[]{"A1", "A4"})); + Assertions.assertTrue(game.getPlayer1().getField().createShip(3, new String[]{"I7", "I5"})); + Assertions.assertTrue(game.getPlayer1().getField().createShip(1, new String[]{"J10"})); + } + + @Test + void shipWrongCreationTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "A1"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "A-2"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "A1"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "B4"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "A3"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "A4", "A1"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "AA4"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", null})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{null, "A4"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(1, new String[]{null})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A10", "A13"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"K1", "K4"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(1, new String[]{"J10 J"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(1, new String[]{"J11"})); + } + + @Test + void shipTouchingCreationTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Assertions.assertTrue(game.getPlayer1().getField().createShip(4, new String[]{"A1", "A4"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(4, new String[]{"A1", "D1"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(1, new String[]{"A2"})); + Assertions.assertFalse(game.getPlayer1().getField().createShip(1, new String[]{"B2"})); + } + + @Test + void shipIsInAStraightLineTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Assertions.assertTrue(Ship.shipIsInAStraightLine(4, new int[]{2, 3}, new int[]{5, 3})); + Assertions.assertFalse(Ship.shipIsInAStraightLine(4, new int[]{2, 3}, new int[]{5, 2})); + } + + @Test + void rightShipLengthTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Assertions.assertTrue(Ship.rightShipLength(4, new int[]{2, 3}, new int[]{5, 3})); + Assertions.assertFalse(Ship.rightShipLength(4, new int[]{2, 3}, new int[]{4, 3})); + Assertions.assertTrue(Ship.rightShipLength(1, new int[]{2, 3}, new int[]{2, 3})); + Assertions.assertFalse(Ship.rightShipLength(1, new int[]{2, 3}, new int[]{1, 3})); + } + + @Test + void cellBelongsToShipTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Ship ship = new Ship(4, new int[][] {{1, 2}, {1, 3}, {1, 4}, {1, 5}}); + Assertions.assertTrue(ship.cellBelongsToShip(new int[]{1, 3})); + Assertions.assertFalse(ship.cellBelongsToShip(new int[]{2, 3})); + } + + @Test + void allShipsSunkTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Field field = game.getPlayer1().getField(); + field.createShip(4, new String[]{"A1", "A4"}); + field.createShip(1, new String[]{"J8"}); + + Assertions.assertFalse(game.getPlayer1().allShipsSunk()); + for (Ship ship : game.getPlayer1().getField().getListOfShips()) { + ship.setShipStatus(Ship.status.SUNK); + } + Assertions.assertTrue(game.getPlayer1().allShipsSunk()); + } + + @Test + void shotResultTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Field field = game.getPlayer1().getField(); + field.createShip(3, new String[]{"A1", "A3"}); + + Assertions.assertEquals("miss", field.shotResult(new int[]{9, 7})); + Assertions.assertEquals("repeat", field.shotResult(new int[]{9, 7})); + Assertions.assertEquals("hit", field.shotResult(new int[]{0, 0})); + Assertions.assertEquals("hit", field.shotResult(new int[]{1, 0})); + Assertions.assertEquals("sunk", field.shotResult(new int[]{2, 0})); + Assertions.assertEquals("repeat", field.shotResult(new int[]{2, 0})); + } + + @Test + void shotResultTest2() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Field field = game.getPlayer1().getField(); + field.createShip(1, new String[]{"J8"}); + + Assertions.assertEquals("sunk", field.shotResult(new int[]{7, 9})); + } + + @Test + void shipStatusTest() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Field field = game.getPlayer1().getField(); + field.createShip(3, new String[]{"A1", "A3"}); + + Assertions.assertSame(field.getListOfShips().get(0).getShipStatus(), Ship.status.INTACT); + field.shotResult(new int[]{0, 0}); + Assertions.assertSame(field.getListOfShips().get(0).getShipStatus(), Ship.status.HIT); + field.shotResult(new int[]{1, 0}); + Assertions.assertSame(field.getListOfShips().get(0).getShipStatus(), Ship.status.HIT); + field.shotResult(new int[]{2, 0}); + Assertions.assertSame(field.getListOfShips().get(0).getShipStatus(), Ship.status.SUNK); + } + + @Test + void shipStatusTest2() { + SeaBattle game = new SeaBattle("Player1", "Player2"); + Field field = game.getPlayer1().getField(); + field.createShip(1, new String[]{"J8"}); + + Assertions.assertSame(field.getListOfShips().get(0).getShipStatus(), Ship.status.INTACT); + field.shotResult(new int[]{7, 9}); + Assertions.assertSame(field.getListOfShips().get(0).getShipStatus(), Ship.status.SUNK); + } + + @Test + void setShipHitAndSunkTest() { + Ship ship = new Ship(2, new int[][] {{1, 2, 0}, {1, 3, 0}}); + assertSame(ship.getShipStatus(), Ship.status.INTACT); + ship.setCellHit(new int[]{1, 2}); + ship.setCellHit(new int[]{1, 3}); + assertSame(ship.getShipStatus(), Ship.status.SUNK); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..797a5831 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,24 @@ +package homework_2.pyramid_printer; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class PyramidPrinterTest { + + @Test + void testRightCasePyramidPrinter() { + PyramidPrinter ppr = new PyramidPrinter(); + + final StringBuilder actual = ppr.buildPyramidString(3); + final String expected = "x" + '\n' + "xx" + '\n' + "xxx" + '\n'; + + assertEquals(actual.toString(), expected); + } + + @Test + void testNegativeNumberInParameterCasePyramidPrinter() { + PyramidPrinter ppr = new PyramidPrinter(); + Assertions.assertThrows(ArithmeticException.class, () -> ppr.buildPyramidString(-3)); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..8323d3b6 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,70 @@ +package homework_2.random_chars_table; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class RandomCharsTableTest { + + @Test + void testOddCaseRandomCharsTable() { + RandomCharsTable rct = new RandomCharsTable(); + + rct.setLength(3); + rct.setWidth(2); + rct.setStrategy(RandomCharsTable.Strategy.ODD); + int [][] twoDimArray = {{65, 77}, {87, 90}, {78, 81}}; + rct.setTable(twoDimArray); + + final StringBuilder actualPrinting = rct.getStrForPrinting(); + final StringBuilder actualPrintingByStrategy = rct.getStrForPrintingByStrategy(rct.getStrategy()); + final String expectedPrinting = "|A|M|" + "\n" + "|W|Z|" + "\n" + "|N|Q|" + "\n"; + final String expectedPrintingByStrategy = "Odd letters: A, M, W, Q"; + + assertEquals(actualPrinting.toString(), expectedPrinting); + assertEquals(actualPrintingByStrategy.toString(), expectedPrintingByStrategy); + } + + @Test + void testEvenCaseRandomCharsTable() { + RandomCharsTable rct = new RandomCharsTable(); + + rct.setLength(3); + rct.setWidth(2); + rct.setStrategy(RandomCharsTable.Strategy.EVEN); + int [][] twoDimArray = {{65,77}, {87,90}, {78,81}}; + rct.setTable(twoDimArray); + + final StringBuilder actualPrinting = rct.getStrForPrinting(); + final StringBuilder actualPrintingByStrategy = rct.getStrForPrintingByStrategy(rct.getStrategy()); + final String expectedPrinting = "|A|M|" + "\n" + "|W|Z|" + "\n" + "|N|Q|" + "\n"; + final String expectedPrintingByStrategy = "Even letters: Z, N"; + + assertEquals(actualPrinting.toString(), expectedPrinting); + assertEquals(actualPrintingByStrategy.toString(), expectedPrintingByStrategy); + } + + @Test + void testWrongNumberOfParametersCaseRandomCharsTable() { + RandomCharsTable rct = new RandomCharsTable(); + Assertions.assertThrows(IllegalArgumentException.class, () -> rct.setParameters(new String[] {"3", "4", "odd", "ODD"})); + } + + @Test + void testNotANumberInParameterCaseRandomCharsTable() { + RandomCharsTable rct = new RandomCharsTable(); + Assertions.assertThrows(NumberFormatException.class, () -> rct.setParameters(new String[] {"3", "j", "ODD"})); + } + + @Test + void testNegativeNumberInParameterCaseRandomCharsTable() { + RandomCharsTable rct = new RandomCharsTable(); + Assertions.assertThrows(IllegalArgumentException.class, () -> rct.setParameters(new String[] {"3", "-2", "EVEN"})); + } + + @Test + void testWrongStrategyInParameterCaseRandomCharsTable() { + RandomCharsTable rct = new RandomCharsTable(); + Assertions.assertThrows(IllegalArgumentException.class, () -> rct.setParameters(new String[] {"3", "2", "eeven"})); + } +} 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..2ef4e447 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,53 @@ +package homework_2.traffic_light; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class TrafficLightTest { + + @Test + void testGreenCaseTrafficLight() throws TrafficLight.WrongSecondsException { + TrafficLight trl = new TrafficLight(); + trl.setTrafficLightColour(11); + + final String actual = trl.getTrafficLightColour().toString(); + final String expected = "GREEN"; + + assertEquals(actual, expected); + } + + @Test + void testYellowCaseTrafficLight() throws TrafficLight.WrongSecondsException { + TrafficLight trl = new TrafficLight(); + trl.setTrafficLightColour(37); + + final String actual = trl.getTrafficLightColour().toString(); + final String expected = "YELLOW"; + + assertEquals(actual, expected); + } + + @Test + void testRedCaseTrafficLight() throws TrafficLight.WrongSecondsException { + TrafficLight trl = new TrafficLight(); + trl.setTrafficLightColour(53); + + final String actual = trl.getTrafficLightColour().toString(); + final String expected = "RED"; + + assertEquals(actual, expected); + } + + @Test + void testNegativeSecondsTrafficLight() { + TrafficLight trl = new TrafficLight(); + Assertions.assertThrows(TrafficLight.WrongSecondsException.class, () -> trl.setTrafficLightColour(-37)); + } + + @Test + void testTooBigValueSecondsCaseTrafficLight() { + TrafficLight trl = new TrafficLight(); + Assertions.assertThrows(TrafficLight.WrongSecondsException.class, () -> trl.setTrafficLightColour(86401)); + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..628f39e1 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,17 @@ +package homework_4.custom_annotation; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class CustomAnnotationTest { + Main main = new Main(); + + @Test + void testCustomAnnotation() { + CustomAnnotation annotation = Main.class.getAnnotation(CustomAnnotation.class); + + Assertions.assertEquals(annotation.DEFAULT_AUTHOR.getName(), "Rog Elena"); + Assertions.assertEquals(annotation.DEFAULT_COUNTRY, "Russia"); + Assertions.assertEquals(annotation.v(), 1.2f); + } +} \ No newline at end of file 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..0f1e8084 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,130 @@ +package homework_4.custom_file_reader; + +import org.junit.jupiter.api.Test; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import static org.junit.jupiter.api.Assertions.*; + +public class CustomFileReaderTest { + + @Test + void testRightCaseFileReaderCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + String str = null; + + try { + str = cfr.readFileFileReader("src/main/resources/custom_file_reader.txt"); + } catch (IOException e) { + e.printStackTrace(); + } + final String actual = cfr.replaceDotsCommas(str); + + assertEquals(getExpectedText(), actual); + } + + @Test + void testWrongCase1FileReaderCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + assertThrows(IOException.class, () -> cfr.readFileFileReader("src/main/resources/custom_file_reader1.txt")); + } + + @Test + void testWrongCase2FileReaderCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + assertThrows(NullPointerException.class, () -> cfr.getFile(null)); + } + + @Test + void testRightCaseInChannelCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + String str = null; + RandomAccessFile file = null; + try { + file = cfr.getFile("src/main/resources/custom_file_reader.txt"); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + try { + str = cfr.readFileInChannel(file); + file.close(); + } catch (IOException e) { + e.printStackTrace(); + } + String str2 = cfr.replaceDotsCommas(str); + final String actual = cfr.replaceDotsCommas(str); + + assertEquals(getExpectedText(), actual); + } + + @Test + void testWrongCase1InChannelCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + assertThrows(FileNotFoundException.class, () -> cfr.getFile("src/main/resources/custom_file_reader1.txt")); + } + + @Test + void testWrongCase2InChannelCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + assertThrows(NullPointerException.class, () -> cfr.readFileInChannel(null)); + } + + @Test + void testRightCaseInputStreamCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + String str = null; + + try { + str = cfr.readFileInputStream("src/main/resources/custom_file_reader.txt"); + } catch (IOException e) { + e.printStackTrace(); + } + final String actual = cfr.replaceDotsCommas(str); + + assertEquals(getExpectedText(), actual); + } + + @Test + void testWrongCase1InputStreamCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + assertThrows(IOException.class, () -> cfr.readFileInputStream("src/main/resources/custom_file_reader1.txt")); + } + + @Test + void testWrongCase2InputStreamCustomFileReader() { + CustomFileReader cfr = new CustomFileReader(); + assertThrows(NullPointerException.class, () -> cfr.readFileInputStream(null)); + } + + private String getExpectedText() { + return "You think I'm delirious with malaria?" + '\r' + '\n' + + '\r' + '\n' + + "This happened" + '\r' + '\n' + + "In Odessa this happened" + '\r' + '\n' + + '\r' + '\n' + + "\"I'll come at four\" promised Maria" + '\r' + '\n' + + '\r' + '\n' + + "Eight" + '\r' + '\n' + + "Nine" + '\r' + '\n' + + "Ten" + '\r' + '\n' + + '\r' + '\n' + + "Soon after" + '\r' + '\n' + + "The evening" + '\r' + '\n' + + "Frowning" + '\r' + '\n' + + "And Decemberish" + '\r' + '\n' + + '\r' + '\n' + + "Left the windows" + '\r' + '\n' + + "And vanished in dire darkness" + '\r' + '\n' + + '\r' + '\n' + + "Behind me I hear the neighing and laughter" + '\r' + '\n' + + "Of candelabras" + '\r' + '\n' + + '\r' + '\n' + + "You wouldn't recognize me if you knew me prior:" + '\r' + '\n' + + "A bulk of sinews" + '\r' + '\n' + + "Moaning" + '\r' + '\n' + + "Fidgeting" + '\r' + '\n' + + "What can such a clod desire?" + '\r' + '\n' + + "But a clod desires many things"; + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..06f2bb20 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,32 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class SingletonTest { + + @Test + void testSingleton() { + Singleton singleGameHero = Singleton.getInstance("Dobrynya"); + Singleton singleGameHero2 = Singleton.getInstance("Ilya"); + + Assertions.assertEquals(singleGameHero.getName(), singleGameHero2.getName()); + Assertions.assertEquals(singleGameHero.getAge(), singleGameHero2.getAge()); + Assertions.assertSame(singleGameHero, singleGameHero2); + } + + @Test + void testWithChangingSingleton() { + Singleton singleGameHero = Singleton.getInstance("Dobrynya"); + Singleton singleGameHero2 = Singleton.getInstance("Ilya"); + + singleGameHero.setAge(20); + singleGameHero2.setAge(30); + singleGameHero.setName("Alosha"); + singleGameHero.setName("Svyatogog"); + + Assertions.assertEquals(singleGameHero.getName(), singleGameHero2.getName()); + Assertions.assertEquals(singleGameHero.getAge(), singleGameHero2.getAge()); + Assertions.assertSame(singleGameHero, singleGameHero2); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..657dae75 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,35 @@ +package homework_5.custom_regex_matcher; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class CustomRegexMatcherTest { + + @Test + void testRightCaseCustomRegexMatcher() { + CustomRegexMatcher crm = new CustomRegexMatcher(); + + String str = "Java_Core_June_2021.package homework_5.custom_regex_matcher"; + String str2 = "Java_Core_June_2019...package homework_5.custom_regex_matcher"; + String str3 = "Java_Core_June_2019.package homework_444466665.custom_regex_matcher"; + String regex = ".[package\\s][homework_][1-9]+[.]."; + + Assertions.assertTrue(crm.validateString(str, regex)); + Assertions.assertTrue(crm.validateString(str2, regex)); + Assertions.assertTrue(crm.validateString(str3, regex)); + } + + @Test + void testWrongCaseCustomRegexMatcher() { + CustomRegexMatcher crm = new CustomRegexMatcher(); + + String str = "Java_Core_June_2021.package homework5.custom_regex_matcher"; + String str2 = "Java_Core_June_2021.package_homework.custom_regex_matcher"; + String str3 = "Java_Core_June_2021.package_homework"; + String regex = ".[package\\s][homework_][1-9]+[.]."; + + Assertions.assertFalse(crm.validateString(str, regex)); + Assertions.assertFalse(crm.validateString(str2, regex)); + Assertions.assertFalse(crm.validateString(str3, regex)); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..a25a93e1 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,44 @@ +package homework_5.power_of_number; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.InputMismatchException; + +import static org.junit.jupiter.api.Assertions.*; + +public class PowerOfNumberTest { + + @Test + void testRightCasePowerOfNumber() { + PowerOfNumber pon = new PowerOfNumber(); + + assertEquals(pon.calculateNumberInPower(3, 3), 27); + assertEquals(pon.calculateNumberInPower(0, 3), 0); + assertEquals(pon.calculateNumberInPower(2, 0), 1); + } + + @Test + void testNotANumberCasePowerOfNumber() { + PowerOfNumber pon = new PowerOfNumber(); + + Assertions.assertThrows(NumberFormatException.class, () -> pon.validateNumbers(new String[]{"j", "2"})); + Assertions.assertThrows(NumberFormatException.class, () -> pon.validateNumbers(new String[]{"2", "k"})); + Assertions.assertThrows(NumberFormatException.class, () -> pon.validateNumbers(new String[]{"j", "k"})); + } + + @Test + void testWrongAmountOfNumbersCasePowerOfNumber() { + PowerOfNumber pon = new PowerOfNumber(); + + Assertions.assertThrows(InputMismatchException.class, () -> pon.validateNumbers(new String[]{"2", "3", "3"})); + Assertions.assertThrows(InputMismatchException.class, () -> pon.validateNumbers(new String[]{"3"})); + } + @Test + void testNegativeNumberCasePowerOfNumber() { + PowerOfNumber pon = new PowerOfNumber(); + + Assertions.assertThrows(InputMismatchException.class, () -> pon.validateNumbers(new String[]{"-3", "3"})); + Assertions.assertThrows(InputMismatchException.class, () -> pon.validateNumbers(new String[]{"3", "-3"})); + } +} \ No newline at end of file