diff --git a/.gitignore b/.gitignore index 14f3f265..592a47b0 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,7 @@ hs_err_pid* out target *.iml -.idea \ No newline at end of file +.idea +/.idea/ +/gradle/ +/.DS_Store/ \ No newline at end of file diff --git a/README.md b/README.md index 5d686e9f..696b1c15 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,22 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Rodina Lera* | Number | Solution | Short description | --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | - +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2_1 | [Traffic light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_2/traffic_light) | The app that reads the number of seconds from the beginning of the day from the command line displays the color of the traffic light (green, yellow or red) | +| HW2_2 | [Pyramid printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_2/pyramid_printer) | The app that reads the number from the command line and print a pyramid with levels according to this number, this pyramid consists only of 'x' symbols | +| HW2_3 | [Random chars table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_2/random_chars_table) | The app that reads 2 numbers as size of a table and a strategy: even or odd, print this table consisting of random symbols from A to Z and then print all symbols in one line which are odd or even according to the strategy (their ASCII codes) | +| HW_3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_3) | Immutable class with fields (including reference type), several constructors, method which return new object and requirements for Immutable class in comments | +| HW_4_1 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_4/custom_file_reader) | The app which gets data from file and then print it without any commas and dots (there are different ways for reading from a file) | +| HW_4_2 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_4/singleton) | The app - singleton | +| HW_4_3 | [Custom annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_4/custom_annotation) | A custom annotation | +| HW_5_1 | [Power Of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_5/power_of_number) | The app which read number and its power and calculate the result. Recursion should be used here | +| HW_5_2 | [Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_5/custom_regex_matcher) | The app which read string and and check if this string matches with hardcoded regex in the app and get result: true or false | +| HW_6 | [Map Problems Generator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_6/map_problems_generator) | The app which create collisions in hashmap | +| HW_7 | [Kitten To Cat Function Interface](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/homework_7/kitten_to_cat_function) | The app which create an interface for turning a kitten into a cat | +| Course project | [Sea Battle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/Lera_Rodina/src/main/java/course_project) | A console Sea Battle Game (Player vs Computer version only)| + +[Link to Coding Bat](https://codingbat.com/done?user=lerarodina24@gmail.com&tag=9318549243) [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/build.gradle b/build.gradle index b91dc843..a6a33e64 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,8 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.0' + } test { diff --git a/src/main/java/couse_project/About b/src/main/java/couse_project/About new file mode 100644 index 00000000..2b2de22f --- /dev/null +++ b/src/main/java/couse_project/About @@ -0,0 +1,30 @@ + +Course project SEA BATTLE + +--------------------------------------- + +Here you can try to play Sea Battle game! + + +I developed a version of a game "Player vs Computer" + +Just to make a game a bit faster - all ships automatically are created randomly before starting this game. +And you might not spend time for creating it by yourself. + +There are: + 4-deck ships - 1 + 3-deck ships - 2 + 2-deck ships - 3 + 1-deck ships - 4 + + (Just because I ve remembered these rules since my childhood:)) + + After starting a game you see your seaMap (with blue color) and you should make your first move! + + If your/computer's ship is found, cell will have a yellow color. + If a ship is destroyed fully, a color is red. + If you/computer makes a mistake - you wil see just a white "star". + + I decided to make a console interface of game in Russian as our traditional game:) + + Hope this game will be convenient for you! diff --git a/src/main/java/couse_project/Color.java b/src/main/java/couse_project/Color.java new file mode 100644 index 00000000..e7237452 --- /dev/null +++ b/src/main/java/couse_project/Color.java @@ -0,0 +1,14 @@ +package couse_project; + +public class Color { + + static String blue = "\033[1;34m"; + static String red = "\033[1;31m"; + static String yellow = "\033[1;33m"; + static String white = "\033[1;37m"; + static String reset = "\033[0m"; + + public static String setColor(String text, String color) { + return color + text + reset; + } +} diff --git a/src/main/java/couse_project/Displayer.java b/src/main/java/couse_project/Displayer.java new file mode 100644 index 00000000..26702593 --- /dev/null +++ b/src/main/java/couse_project/Displayer.java @@ -0,0 +1,64 @@ +package couse_project; + +import java.io.IOException; +import java.util.HashMap; + +public class Displayer { + + private final String columns = " А Б В Г Д Е Ж З И К\n"; + private final String row = "%2d %s %s %s %s %s %s %s %s %s %s\n"; + private final HashMap mapSymbols = new HashMap() {{ + put(0, " "); // пустая клетка + put(1, Color.setColor("■", Color.blue)); // корабль + put(2, Color.setColor("□", Color.yellow)); // подбитый корабль + put(3, Color.setColor("X", Color.red)); // разрушенный корабль + put(4, Color.setColor("*", Color.white)); // промах + }}; + private final HashMap radarSymbols = new HashMap() {{ + put(0, " "); // пустая клетка + put(1, " "); // корабль + put(2, Color.setColor("□", Color.yellow)); // подбитый корабль + put(3, Color.setColor("X", Color.red)); // разрушенный корабль + put(4, Color.setColor("*", Color.white)); // промах + }}; + + public void clearScreen() throws IOException, InterruptedException { + String os = System.getProperty("os.name").toLowerCase(); + if (os.contains("win")) { + new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); + } else if (os.contains("nix") || os.contains("nux")) { + new ProcessBuilder("terminal", "/c", "clear").inheritIO().start().waitFor(); + } + System.out.println(); + } + + public void displayMap(SeaMap map) { + StringBuilder mapImage = new StringBuilder(); + mapImage.append(columns); + for (int i = 0; i < map.size()[0]; i++) { + mapImage.append(String.format(row, i + 1, + mapSymbols.get(map.getCell(i, 0)), mapSymbols.get(map.getCell(i, 1)), + mapSymbols.get(map.getCell(i, 2)), mapSymbols.get(map.getCell(i, 3)), + mapSymbols.get(map.getCell(i, 4)), mapSymbols.get(map.getCell(i, 5)), + mapSymbols.get(map.getCell(i, 6)), mapSymbols.get(map.getCell(i, 7)), + mapSymbols.get(map.getCell(i, 8)), mapSymbols.get(map.getCell(i, 9)))); + } + mapImage.append("\n"); + System.out.print(mapImage); + } + + public void displayRadar(SeaMap radar) { + StringBuilder radarImage = new StringBuilder(); + radarImage.append(columns); + for (int i = 0; i < radar.size()[0]; i++) { + radarImage.append(String.format(row, i + 1, + radarSymbols.get(radar.getCell(i, 0)), radarSymbols.get(radar.getCell(i, 1)), + radarSymbols.get(radar.getCell(i, 2)), radarSymbols.get(radar.getCell(i, 3)), + radarSymbols.get(radar.getCell(i, 4)), radarSymbols.get(radar.getCell(i, 5)), + radarSymbols.get(radar.getCell(i, 6)), radarSymbols.get(radar.getCell(i, 7)), + radarSymbols.get(radar.getCell(i, 8)), radarSymbols.get(radar.getCell(i, 9)))); + } + radarImage.append("\n"); + System.out.print(radarImage); + } +} diff --git a/src/main/java/couse_project/Game.java b/src/main/java/couse_project/Game.java new file mode 100644 index 00000000..0d1bcd83 --- /dev/null +++ b/src/main/java/couse_project/Game.java @@ -0,0 +1,34 @@ +package couse_project; + +import java.io.IOException; + +public class Game { + Player playerOne; + RandomIntelligence playerTwo; + + public Game(Player playerOne, RandomIntelligence playerTwo) { + this.playerOne = playerOne; + this.playerTwo = playerTwo; + } + + public void startGame() throws IOException, InterruptedException { + Displayer displayer = new Displayer(); + while (true) { + displayer.clearScreen(); + displayer.displayMap(playerOne.getMap()); + displayer.displayRadar(playerOne.getRadar()); + if (playerOne.shoot()) { + System.out.println("Отлично! Сделайте еще один ход:"); + continue; + } + + while (true) { + if (playerTwo.shoot()) { + System.out.println("Наш корабль попал под обстрел!"); + } else { + break; + } + } + } + } +} diff --git a/src/main/java/couse_project/Main.java b/src/main/java/couse_project/Main.java new file mode 100644 index 00000000..bf284b65 --- /dev/null +++ b/src/main/java/couse_project/Main.java @@ -0,0 +1,17 @@ +package couse_project; + +import java.io.IOException; + +public class Main { + + public static void main(String[] args) throws IOException, InterruptedException { + SeaMap mapOne = new SeaMap(); + SeaMap mapTwo = new SeaMap(); + + Player playerOne = new Player("Lera", mapOne, mapTwo); + RandomIntelligence playerTwo = new RandomIntelligence(mapTwo, mapOne); + + Game gameSession = new Game(playerOne, playerTwo); + gameSession.startGame(); + } +} diff --git a/src/main/java/couse_project/Player.java b/src/main/java/couse_project/Player.java new file mode 100644 index 00000000..8be8fb64 --- /dev/null +++ b/src/main/java/couse_project/Player.java @@ -0,0 +1,72 @@ +package couse_project; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Scanner; + +public class Player { + final private String name; + private final SeaMap map; + private final SeaMap radar; + final private String[] commands = new String[]{ + "А1", "А2", "А3", "А4", "А5", "А6", "А7", "А8", "А9", "А10", + "Б1", "Б2", "Б3", "Б4", "Б5", "Б6", "Б7", "Б8", "Б9", "Б10", + "В1", "В2", "В3", "В4", "В5", "В6", "В7", "В8", "В9", "В10", + "Г1", "Г2", "Г3", "Г4", "Г5", "Г6", "Г7", "Г8", "Г9", "Г10", + "Д1", "Д2", "Д3", "Д4", "Д5", "Д6", "Д7", "Д8", "Д9", "Д10", + "Е1", "Е2", "Е3", "Е4", "Е5", "Е6", "Е7", "Е8", "Е9", "Е10", + "Ж1", "Ж2", "Ж3", "Ж4", "Ж5", "Ж6", "Ж7", "Ж8", "Ж9", "Ж10", + "З1", "З2", "З3", "З4", "З5", "З6", "З7", "З8", "З9", "З10", + "И1", "И2", "И3", "И4", "И5", "И6", "И7", "И8", "И9", "И10", + "К1", "К2", "К3", "К4", "К5", "К6", "К7", "К8", "К9", "К10", + }; + final private HashMap commandsMap = new HashMap() {{ + put("А", 0); + put("Б", 1); + put("В", 2); + put("Г", 3); + put("Д", 4); + put("Е", 5); + put("Ж", 6); + put("З", 7); + put("И", 8); + put("К", 9); + }}; + + public Player(String name, SeaMap map, SeaMap radar) { + this.name = name; + this.map = map; + this.radar = radar; + } + + public boolean shoot() { + Scanner in = new Scanner(System.in); + System.out.println("Ваш ход:"); + String command = in.nextLine(); + + if (Arrays.asList(commands).contains(command)) { + System.out.println(command.toUpperCase().charAt(0)); + + int x = commandsMap.get((Character.toString(command.toUpperCase().charAt(0)))); + int y = Integer.parseInt(Character.toString(command.charAt(1))) - 1; + + if (radar.isFreeEnterCell(x, y)) { + return radar.registerShot(x, y); + } + } else { + System.out.println("Ошибка формата данных"); + System.out.println("Попробуйте, пожалуйста, ещё раз"); + } + + shoot(); + return false; + } + + public SeaMap getMap() { + return map; + } + + public SeaMap getRadar() { + return radar; + } +} \ No newline at end of file diff --git a/src/main/java/couse_project/RandomIntelligence.java b/src/main/java/couse_project/RandomIntelligence.java new file mode 100644 index 00000000..95e5a963 --- /dev/null +++ b/src/main/java/couse_project/RandomIntelligence.java @@ -0,0 +1,26 @@ +package couse_project; + +import java.util.Random; + +public class RandomIntelligence { + private SeaMap map; + private final SeaMap radar; + + public RandomIntelligence(SeaMap map, SeaMap radar) { + this.map = map; + this.radar = radar; + } + + public boolean shoot() { + Random random = new Random(); + int x = random.nextInt(10); + int y = random.nextInt(10); + + if (radar.isFreeEnterCell(x, y)) { + return radar.registerShot(x, y); + } + + shoot(); + return false; + } +} diff --git a/src/main/java/couse_project/SeaMap.java b/src/main/java/couse_project/SeaMap.java new file mode 100644 index 00000000..2806decd --- /dev/null +++ b/src/main/java/couse_project/SeaMap.java @@ -0,0 +1,326 @@ +package couse_project; + +public class SeaMap implements Cloneable { + private final int[][] field = new int[10][10]; + + public SeaMap() { + randomShipsFill(); + } + + public SeaMap clone() throws CloneNotSupportedException { + return (SeaMap) super.clone(); + } + + public int[][] getField() { + return field; + } + + public int[] size() { + return new int[]{10, 10}; + } + + public int getCell(int row, int col) { + return field[row][col]; + } + + public boolean cellIsEmpty(int x, int y) { + return field[y][x] == 0; + } + + public boolean isHealthyShip(int x, int y) { + return field[y][x] == 1; + } + + public boolean isWreckedShip(int x, int y) { + return field[y][x] == 2; + } + + public boolean isFreeEnterCell(int x, int y) { + return field[y][x] == 0 || field[y][x] == 1; + } + + public void randomShipsFill() { + java.util.Random random = new java.util.Random(); + int[] shipsSizes = new int[]{4, 3, 3, 2, 2, 2, 1, 1, 1, 1}; + + for (int size : shipsSizes) { + int x = random.nextInt(10); + int y = random.nextInt(10); + int rotate = random.nextInt(2); + Ship ship = new Ship(size, x, y, rotate == 1); + while (!canSetShip(ship)) { + x = random.nextInt(10); + y = random.nextInt(10); + rotate = random.nextInt(2); + ship = new Ship(size, x, y, rotate == 1); + } + + for (int i = 0; i < size; i++) { + if (ship.isRotate()) { + field[y + i][x] = 1; + } else { + field[y][x + i] = 1; + } + } + } + } + + private boolean canSetShip(Ship ship) { + if (ship.getX() < 0 || ship.getY() < 0 || field.length <= ship.getX() || field.length <= ship.getY()) { + return false; + } + if (ship.isRotate() && field.length <= ship.getY() + ship.getSize()) { + return false; + } + if (!ship.isRotate() && field.length <= ship.getX() + ship.getSize()) { + return false; + } + + int minX = Math.max(0, ship.getX() - 1); + int minY = Math.max(0, ship.getY() - 1); + int maxX = Math.min(field.length - 1, ship.getX() + 1 + (ship.isRotate() ? 0 : ship.getSize())); + int maxY = Math.min(field.length - 1, ship.getY() + 1 + (ship.isRotate() ? ship.getSize() : 0)); + + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + if (!cellIsEmpty(x, y)) { + return false; + } + } + } + return true; + } + + public boolean registerShot(int x, int y) { + if (cellIsEmpty(x, y)) { + field[y][x] = 4; + return false; + } else if (isHealthyShip(x, y)) { + field[y][x] = 2; + if (!shipIsAlive(x, y)) { + markDestroyedShip(x, y); + } + return true; + } + return false; + } + + private boolean shipIsAlive(int x, int y) { + int[] env = new int[]{-1, -1, -1, -1}; + if (x != 0) { + env[0] = x - 1; + } + if (x != 9) { + env[1] = x + 1; + } + if (y != 0) { + env[2] = y - 1; + } + if (y != 9) { + env[3] = y + 1; + } + + if (isVerticalShip(x, y)) { + for (int i = 2; i < env.length; i++) { + if (env[i] != -1) { + if (field[env[i]][x] == 1) { + return true; + } else if (field[env[i]][x] == 2) { + int positionY = y; + + while (positionY > 0 && (field[positionY][x] != 0 && field[positionY][x] != 4)) { + if (field[positionY][x] == 1) { + return true; + } + positionY -= 1; + } + + while (positionY < 9 && (field[positionY][x] != 0 && field[positionY][x] != 4)) { + if (field[positionY][x] == 1) { + return true; + } + positionY += 1; + } + + if (field[positionY][x] == 1) { + return true; + } + } + } + } + } else { + for (int i = 0; i < env.length / 2; i++) { + if (env[i] != -1) { + if (field[y][env[i]] == 1) { + return true; + } else if (field[y][env[i]] == 2) { + int positionX = x; + + while (positionX > 0 && (field[y][positionX] != 0 && field[y][positionX] != 4)) { + if (field[y][positionX] == 1) { + return true; + } + positionX -= 1; + } + + while (positionX < 9 && (field[y][positionX] != 0 && field[y][positionX] != 4)) { + if (field[y][positionX] == 1) { + return true; + } + positionX += 1; + } + + if (field[y][positionX] == 1) { + return true; + } + } + } + } + } + return false; + } + + private void markDestroyedShip(int x, int y) { + if (isVerticalShip(x, y)) { + int positionY = y; + while (positionY > 0 && (field[positionY][x] != 0 && field[positionY][x] != 4)) { + positionY -= 1; + } + if (field[positionY][x] != 1 && field[positionY][x] != 2) { + positionY += 1; + } + + while (positionY < 9 && (field[positionY][x] != 0 && field[positionY][x] != 4)) { + field[positionY][x] = 3; + + if (positionY > 0) { + if (field[positionY - 1][x] == 0) { + field[positionY - 1][x] = 4; + } + if (x + 1 <= 9) { + if (field[positionY - 1][x + 1] == 0) { + field[positionY - 1][x + 1] = 4; + } + } + if (x - 1 >= 0) { + if (field[positionY - 1][x - 1] == 0) { + field[positionY - 1][x - 1] = 4; + } + } + } + + if (x > 0) { + if (field[positionY][x - 1] == 0) { + field[positionY][x - 1] = 4; + } + } + + if (x < 9) { + if (field[positionY][x + 1] == 0) { + field[positionY][x + 1] = 4; + } + } + + if (field[positionY + 1][x] == 0) { + field[positionY + 1][x] = 4; + } + + if (x + 1 <= 9) { + if (field[positionY + 1][x + 1] == 0) { + field[positionY + 1][x + 1] = 4; + } + } + + if (x - 1 >= 0) { + if (field[positionY + 1][x - 1] == 0) { + field[positionY + 1][x - 1] = 4; + } + } + + positionY += 1; + } + } else { + int positionX = x; + while (positionX > 0 && (field[y][positionX] != 0 && field[y][positionX] != 4)) { + positionX -= 1; + } + if (field[y][positionX] != 1 && field[y][positionX] != 2) { + positionX += 1; + } + + while (positionX < 9 && (field[y][positionX] != 0 && field[y][positionX] != 4)) { + field[y][positionX] = 3; + + if (positionX > 0) { + if (field[y][positionX - 1] == 0) { + field[y][positionX - 1] = 4; + } + if (y + 1 <= 9) { + if (field[y + 1][positionX - 1] == 0) { + field[y + 1][positionX - 1] = 4; + } + } + if (y - 1 >= 0) { + if (field[y - 1][positionX - 1] == 0) { + field[y - 1][positionX - 1] = 4; + } + } + } + + if (y > 0) { + if (field[y - 1][positionX] == 0) { + field[y - 1][positionX] = 4; + } + } + + if (y < 9) { + if (field[y + 1][positionX] == 0) { + field[y + 1][positionX] = 4; + } + } + + if (field[y][positionX + 1] == 0) { + field[y][positionX + 1] = 4; + } + if (y + 1 <= 9) { + if (field[y + 1][positionX + 1] == 0) { + field[y + 1][positionX + 1] = 4; + } + } + if (y - 1 >= 0) { + if (field[y - 1][positionX + 1] == 0) { + field[y - 1][positionX + 1] = 4; + } + } + + positionX += 1; + } + } + } + + private boolean isVerticalShip(int x, int y) { + int[] env = new int[]{-1, -1, -1, -1}; + if (x != 0) { + env[0] = x - 1; + } + if (x != 9) { + env[1] = x + 1; + } + if (y != 0) { + env[2] = y - 1; + } + if (y != 9) { + env[3] = y + 1; + } + + for (int i = 0; i < env.length / 2; i++) { + if (env[i] != -1) { + if (field[y][env[i]] == 1 || field[y][env[i]] == 2) { + return false; + } + } + } + return true; + } + +} diff --git a/src/main/java/couse_project/Ship.java b/src/main/java/couse_project/Ship.java new file mode 100644 index 00000000..c339f715 --- /dev/null +++ b/src/main/java/couse_project/Ship.java @@ -0,0 +1,41 @@ +package couse_project; + +public class Ship { + private final int size; + private final int x; + private final int y; + private final boolean rotate; + + public Ship(int size, int x, int y, boolean rotate) { + this.size = size; + this.x = x; + this.y = y; + this.rotate = rotate; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getSize() { + return size; + } + + public boolean isRotate() { + return rotate; + } + + @Override + public String toString() { + return "Ship{" + + "size=" + size + + ", x=" + x + + ", y=" + y + + ", rotate=" + rotate + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..8f615c6b 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -2,8 +2,16 @@ public class Main { - public static void main(String[] args) { - System.out.println("Hello homework!"); - } + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public static void main(String[] args) { + for (String arg : args) { + if ("error".equals(arg)) { + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); + break; + } + System.out.println(arg + ": " + arg.length() + " letter/s"); + } + } } 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..70347987 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,48 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + private static void printPyramid(int levelsOfPyramid) { + for (int i = 1; i <= levelsOfPyramid; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } + + public void run() { + System.out.println("Please type a positive integer number:"); + String inputData = readData(); + int getResult = executeProgram(inputData); + printPyramid(getResult); + } + + private int executeProgram(String dataFromInput) { + int levelsOfPyramid = 0; + try { + levelsOfPyramid = Integer.parseInt(dataFromInput); + if (levelsOfPyramid < 0) { + throw new NumberFormatException(); + } + } catch (NumberFormatException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + return levelsOfPyramid; + } + + private String readData() { + String inputData = null; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + inputData = reader.readLine(); + } catch (IOException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + return inputData; + } +} + diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..682fe366 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,7 @@ +package homework_2.random_chars_table; + +public class Main { + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..f41173f6 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,89 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.InputMismatchException; +import java.util.NoSuchElementException; +import java.util.Scanner; + +public class RandomCharsTable { + + private static void randomCharsTable(int lengthOfTable, int widthOfTable, String strategy) { + + char[][] randomCharsTable = new char[lengthOfTable][widthOfTable]; + + int minRand = 'A'; + int maxRand = 'Z'; + for (int i = 0; i < lengthOfTable; i++) { + for (int j = 0; j < widthOfTable; j++) { + randomCharsTable[i][j] = (char) ((int) (Math.random() * (maxRand - minRand + 1) + minRand)); + System.out.print("| " + randomCharsTable[i][j] + " | "); + } + System.out.println(); + } + + if ("even".equals(strategy.toLowerCase())) { + System.out.print("Even letters - "); + } + + if ("odd".equals(strategy.toLowerCase())) { + System.out.print("Odd letters - "); + } + + StringBuffer stringBuffer = new StringBuffer(); + + for (int i = 0; i < lengthOfTable; i++) { + for (int j = 0; j < widthOfTable; j++) { + int codeOfChar = randomCharsTable[i][j]; + if ("even".equals(strategy.toLowerCase())) { + if (codeOfChar % 2 == 0) { + stringBuffer.append(" ").append((char) codeOfChar).append(" ,"); + } + } + + if ("odd".equals(strategy.toLowerCase())) { + if (codeOfChar % 2 != 0) { + stringBuffer.append(" ").append((char) codeOfChar).append(" ,"); + } + } + } + } + + if (stringBuffer.length() != 1 && stringBuffer.length() != 0) { + stringBuffer.deleteCharAt(stringBuffer.length() - 1); + stringBuffer.deleteCharAt(stringBuffer.length() - 1); + } + } + + public void run() { + System.out.println("Please type size of a table: 2 numbers and strategy - even or odd:"); + String inputData = readData(); + try (Scanner inputDataSeparate = new Scanner(inputData)) { + int lengthOfTable = inputDataSeparate.nextInt(); + int widthOfTable = inputDataSeparate.nextInt(); + String strategy = inputDataSeparate.next(); + if (lengthOfTable <= 0 || widthOfTable <= 0) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + return; + } + if (!"even".equalsIgnoreCase(strategy) && !"odd".equalsIgnoreCase(strategy)) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + return; + } + randomCharsTable(lengthOfTable, widthOfTable, strategy); + } catch (NegativeArraySizeException | NoSuchElementException e) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + } + } + + private String readData() { + String inputData; + try (Scanner scanner = new Scanner(System.in)) { + inputData = scanner.nextLine(); + } catch (NoSuchElementException e) { + return "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + } + return inputData; + } +} diff --git a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java new file mode 100644 index 00000000..f18bcad5 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -0,0 +1,58 @@ +package homework_2.traffic_light; + +import java.util.Scanner; + +public class ExtraTrafficLight { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; + + private static void trafficLight(String inputStr) { + String[] arr; + + if (!inputStr.matches("\\d\\d:\\d\\d:\\d\\d")) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } else { + arr = inputStr.split(":"); + int hoursSec = Integer.parseInt(arr[0]) * 60 * 60; + int minutesSec = Integer.parseInt(arr[1]) * 60; + int seconds = Integer.parseInt(arr[2]); + + if (hoursSec > 24 * 60 * 60 || minutesSec > 60 * 60 || seconds >= 60) { + System.out.println("The day is over"); + return; + } + + int timeInSeconds = seconds + minutesSec * 60 + hoursSec * 60 * 60; + int cycleOfTrafficLight = 60; + int secForLight = timeInSeconds % cycleOfTrafficLight; + + if (secForLight >= 0 && secForLight < 35) { + System.out.println(ANSI_GREEN + "GREEN" + ANSI_RESET); + } + if (secForLight >= 35 && secForLight < 40 || secForLight >= 55) { + System.out.println(ANSI_YELLOW + "YELLOW" + ANSI_RESET); + } + if (secForLight >= 40 && secForLight < 55) { + System.out.println(ANSI_RED + "RED" + ANSI_RESET); + } + } + } + + public void run() { + System.out.println("Please type your current time in HH:MM:SS format:"); + String inputData = readData(); + trafficLight(inputData); + } + + private String readData() { + try (Scanner scanner = new Scanner(System.in)) { + String str = scanner.nextLine(); + return str; + } catch (NumberFormatException e) { + return "Only 1 non-negative integer is allowed as passed parameter"; + } + } +} 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..91c7f21b --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,14 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args) { + /* if you need to launch a program with Extra mode (with another format of current time) - + add "extramode" to your Program arguments + */ + if (args[0].equalsIgnoreCase("extramode")) { + new ExtraTrafficLight().run(); + } else { + new TrafficLight().run(); + } + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..271add98 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,57 @@ +package homework_2.traffic_light; + +import java.util.NoSuchElementException; +import java.util.Scanner; + +public class TrafficLight { + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; + + private static void trafficLight(String secondsStr) { + int seconds = 0; + try { + seconds = Integer.parseInt(secondsStr); + if (seconds < 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + return; + } else if (seconds > 86399) { + System.out.println("The day is over"); + return; + } + } catch (NumberFormatException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + return; + } + + int cycleOfTrafficLight = 60; + int secForLight = seconds % cycleOfTrafficLight; + + if (secForLight < 35) { + System.out.println(ANSI_GREEN + "GREEN" + ANSI_RESET); + } + if (secForLight >= 35 && secForLight < 40 || secForLight >= 55) { + System.out.println(ANSI_YELLOW + "YELLOW" + ANSI_RESET); + } + if (secForLight >= 40 && secForLight < 55) { + System.out.println(ANSI_RED + "RED" + ANSI_RESET); + } + } + + public void run() { + System.out.println("Please type your current time in seconds:"); + String inputData = readData(); + trafficLight(inputData); + } + + private String readData() { + String str; + try (Scanner scanner = new Scanner(System.in)) { + str = scanner.nextLine(); + } catch (NoSuchElementException e) { + return "Only 1 non-negative integer is allowed as passed parameter"; + } + return str; + } +} diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..7cb2ed3b --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,67 @@ +package homework_3; + +import java.util.ArrayList; +import java.util.Arrays; + +/** + * A Strategy for Defining Immutable Objects (from the official Oracle documentation) + *

+ * 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. + */ + +final public class ImmutableClass { + + // Values must be between 0 and 255 (RGB) + final private ArrayList dataColor; + final private StringBuilder name; + + private void check(Integer red, + Integer green, + Integer blue) { + if (red < 0 || red > 255 + || green < 0 || green > 255 + || blue < 0 || blue > 255) { + throw new IllegalArgumentException(); + } + } + + public ImmutableClass(ArrayList dataColor, + StringBuilder name) { + check(dataColor.get(0), dataColor.get(1), dataColor.get(2)); + this.dataColor = new ArrayList<>(dataColor); + this.name = new StringBuilder(name); + } + + + public ArrayList getColorData() + { + return new ArrayList<>(dataColor); + } + + public StringBuilder getName() { + return new StringBuilder(name); + } + + public ImmutableClass invert() { + return new ImmutableClass(new ArrayList<>(Arrays.asList(255 - dataColor.get(0), + 255 - dataColor.get(1), + 255 - dataColor.get(2)) + ), new StringBuilder("Inverse of " + name)); + } + + public ImmutableClass getInstance() { + return new ImmutableClass(getColorData(), getName()); + } +} diff --git a/src/main/java/homework_4/custom_annotation/Init.java b/src/main/java/homework_4/custom_annotation/Init.java new file mode 100644 index 00000000..1e872b88 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Init.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.METHOD) +public @interface Init { + +} diff --git a/src/main/java/homework_4/custom_annotation/JsonElement.java b/src/main/java/homework_4/custom_annotation/JsonElement.java new file mode 100644 index 00000000..db4fd7b8 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/JsonElement.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.FIELD) +public @interface JsonElement { + public String key() default ""; +} diff --git a/src/main/java/homework_4/custom_annotation/JsonSerializable.java b/src/main/java/homework_4/custom_annotation/JsonSerializable.java new file mode 100644 index 00000000..76be1fa9 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/JsonSerializable.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 JsonSerializable { + +} diff --git a/src/main/java/homework_4/custom_annotation/JsonSerializationException.java b/src/main/java/homework_4/custom_annotation/JsonSerializationException.java new file mode 100644 index 00000000..61b2be3f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/JsonSerializationException.java @@ -0,0 +1,10 @@ +package homework_4.custom_annotation; + +public class JsonSerializationException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public JsonSerializationException(String message) { + super(message); + } +} diff --git a/src/main/java/homework_4/custom_annotation/ObjectToJsonConverter.java b/src/main/java/homework_4/custom_annotation/ObjectToJsonConverter.java new file mode 100644 index 00000000..44af575b --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/ObjectToJsonConverter.java @@ -0,0 +1,67 @@ +package homework_4.custom_annotation; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +public class ObjectToJsonConverter { + public String convertToJson(Object object) throws JsonSerializationException { + try { + + checkIfSerializable(object); + initializeObject(object); + return getJsonString(object); + + } catch (Exception e) { + throw new JsonSerializationException(e.getMessage()); + } + } + + private void checkIfSerializable(Object object) { + if (Objects.isNull(object)) { + throw new JsonSerializationException("Can't serialize a null object"); + } + + Class clazz = object.getClass(); + if (!clazz.isAnnotationPresent(JsonSerializable.class)) { + throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable"); + } + } + + private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class clazz = object.getClass(); + for (Method method : clazz.getDeclaredMethods()) { + if (method.isAnnotationPresent(Init.class)) { + method.setAccessible(true); + method.invoke(object); + } + } + } + + private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException { + Class clazz = object.getClass(); + Map jsonElementsMap = new HashMap<>(); + for (Field field : clazz.getDeclaredFields()) { + field.setAccessible(true); + if (field.isAnnotationPresent(JsonElement.class)) { + jsonElementsMap.put(getKey(field), (String) field.get(object)); + } + } + + String jsonString = jsonElementsMap.entrySet() + .stream() + .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"") + .collect(Collectors.joining(",")); + return "{" + jsonString + "}"; + } + + private String getKey(Field field) { + String value = field.getAnnotation(JsonElement.class) + .key(); + return value.isEmpty() ? field.getName() : value; + } +} diff --git a/src/main/java/homework_4/custom_annotation/Person.java b/src/main/java/homework_4/custom_annotation/Person.java new file mode 100644 index 00000000..f442239e --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Person.java @@ -0,0 +1,65 @@ +package homework_4.custom_annotation; + +@JsonSerializable +public class Person { + @JsonElement + private String firstName; + @JsonElement + private String lastName; + @JsonElement(key = "personAge") + private String age; + + private String address; + + public Person(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Person(String firstName, String lastName, String age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + @Init + private void initNames() { + this.firstName = this.firstName.substring(0, 1) + .toUpperCase() + this.firstName.substring(1); + this.lastName = this.lastName.substring(0, 1) + .toUpperCase() + this.lastName.substring(1); + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAge() { + return age; + } + + public void setAge(String age) { + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..eeeade66 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,86 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class CustomFileReader { + + public String file; + public Path path; + + public CustomFileReader(String file) { + this.file = file; + } + + public CustomFileReader(Path path) { + this.path = path; + } + + public void run1() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(file)); + StringBuilder stringBuilder = new StringBuilder(); + String currentLine = reader.readLine(); + while (currentLine != null) { + stringBuilder.append(currentLine).append("\n"); + currentLine = reader.readLine(); + } + System.out.println(stringBuilder.toString().replaceAll("[.,]", "")); + reader.close(); + + } + + public void run2() throws FileNotFoundException { + Scanner scanner = new Scanner(new File(file)); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + String newLine = currentLine.replaceAll("[.,]", ""); + System.out.print(newLine); + } + scanner.close(); + } + + public void run3() throws IOException { + List read = Files.readAllLines(path); + StringBuilder res = new StringBuilder(); + for (String s : read) { + res.append(s.replaceAll("[,.]", "")); + } + System.out.println(res.toString()); + } + + public void run4() throws IOException { + BufferedReader reader = Files.newBufferedReader(path); + StringBuilder stringBuilder = new StringBuilder(); + String currentLine = reader.readLine(); + while (currentLine != null) { + stringBuilder.append(currentLine).append("\n"); + currentLine = reader.readLine(); + } + System.out.println(stringBuilder.toString().replaceAll("[.,]", "")); + reader.close(); + } + + public void run5() throws IOException { + RandomAccessFile reader = new RandomAccessFile(file, "r"); + FileChannel channel = reader.getChannel(); + + int bufferSize = 1024; + if (bufferSize > channel.size()) { + bufferSize = (int) channel.size(); + } + ByteBuffer buff = ByteBuffer.allocate(bufferSize); + channel.read(buff); + buff.flip(); + + System.out.println(new String(buff.array()).replaceAll("[,.]", "")); + + channel.close(); + reader.close(); + } +} 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..642756ba --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,13 @@ +package homework_4.custom_file_reader; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class Main { + public static void main(String[] args) throws IOException { + String file = "src/main/resources/custom_file_reader/fileTest.txt"; + Path path = Paths.get("src/main/resources/custom_file_reader/fileTest.txt"); + new CustomFileReader(path).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..3e868e3b --- /dev/null +++ b/src/main/java/homework_4/singleton/Main.java @@ -0,0 +1,21 @@ +package homework_4.singleton; + +public class Main { + public static void main(String[] args) { + Singleton object1 = Singleton.getInstance("hey"); + if (object1 != null) { + object1.Set(100); + object1.Print(); + } else { + System.out.println("object 1 is null"); + } + + Singleton object2 = Singleton.getInstance("hello"); + if (object2 != null) { + object2.Set(999); + object2.Print(); + } else { + System.out.println("object 2 is null"); + } + } +} 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..d5c9126d --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,27 @@ +package homework_4.singleton; + +public class Singleton { + private static Singleton instance; + private int x; + public String value; + + private Singleton(String value) { + x = 0; + this.value = value; + } + + public static Singleton getInstance(String value) { + if (instance == null) { + instance = new Singleton(value); + } + return instance; + } + + public void Set(int newX) { + x = newX; + } + + public void Print() { + System.out.println("x = " + x); + } +} 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..1614132e --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,21 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; + +public class CustomRegexMatcher { + public void run() { + System.out.println("Please enter a valid ipv4 address: "); + String address = ""; + try (Scanner scanner = new Scanner(System.in)) { + if (scanner.hasNextLine()) { + address = scanner.nextLine().trim(); + } + System.out.println(isipv4Addr(address)); + } + } + + private boolean isipv4Addr(String s) { + String regex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?)$"; + return s.matches(regex); + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..f8b52c06 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..930f2040 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..1298d536 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,32 @@ +package homework_5.power_of_number; + +import java.util.Scanner; + +public class PowerOfNumber { + + private static final String ERR_MESSAGE = "Only 2 non-negative integers are allowed"; + + public void run() { + System.out.println("Please enter number and power of this number: "); + String inputString = ""; + try (Scanner scanner = new Scanner(System.in)) { + if (scanner.hasNextLine()) { + inputString = scanner.nextLine().trim(); + } + if (!inputString.matches("\\d+\\s+\\d+")) { + System.out.println(ERR_MESSAGE); + } else { + int number = Integer.parseInt(inputString.split("\\s+")[0]); + int power = Integer.parseInt(inputString.split("\\s+")[1]); + System.out.println(powerOfN(number, power)); + } + } + } + + private int powerOfN(int number, int pow) { + if (pow == 0) { + return 1; + } + return powerOfN(number, pow - 1) * number; + } +} 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..5f02649f --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,41 @@ +package homework_6.map_problems_generator; + +import java.util.HashMap; + +public class Main { + public static void main(String[] args) { + HashMap container_mutable_gen = new HashMap<>(); + + MapProblemsMutableGenerator generator_one = new MapProblemsMutableGenerator(new StringBuilder("one")); + MapProblemsMutableGenerator generator_two = new MapProblemsMutableGenerator(new StringBuilder("two")); + container_mutable_gen.put(generator_one, "one"); + container_mutable_gen.put(generator_two, "two"); + + String resultTwo_valid = container_mutable_gen.get(generator_two); + + System.out.println("resultTwo_valid = " + resultTwo_valid); + + generator_two.setKey(new StringBuilder("collision")); + + String resultTwo_invalid = container_mutable_gen.get(generator_two); + + System.out.println("resultTwo_invalid = " + resultTwo_invalid); + + + HashMap container_problems_coll_gen = new HashMap<>(); + + MapProblemsCollisionGenerator one_collision_gen = new MapProblemsCollisionGenerator(new StringBuilder("one")); + MapProblemsCollisionGenerator two_collision_gen = new MapProblemsCollisionGenerator(new StringBuilder("two")); + MapProblemsCollisionGenerator three_collision_gen = new MapProblemsCollisionGenerator(new StringBuilder("three")); + + + container_problems_coll_gen.put(one_collision_gen, "one"); + container_problems_coll_gen.put(two_collision_gen, "two"); + container_problems_coll_gen.put(three_collision_gen, "three"); + + System.out.println("Count of collision in one_collision_gen = " + one_collision_gen.getCountCollision()); + System.out.println("Count of collision in two_collision_gen = " + two_collision_gen.getCountCollision()); + System.out.println("Count of collision in three_collision_gen = " + three_collision_gen.getCountCollision()); + } + +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..83f57393 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java @@ -0,0 +1,36 @@ +package homework_6.map_problems_generator; + +import java.util.Objects; + +public class MapProblemsCollisionGenerator { + + private Integer countCollision = 0; + private StringBuilder key; + + public MapProblemsCollisionGenerator(StringBuilder key) { + this.key = key; + } + + public void setKey(StringBuilder key) { + this.key = key; + } + + public Integer getCountCollision() + { + return countCollision; + } + + @Override + public boolean equals(Object o) { + countCollision++; + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsCollisionGenerator that = (MapProblemsCollisionGenerator) o; + return key.equals(that.key); + } + + @Override + public int hashCode() { + return 1; + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..8fb40113 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -0,0 +1,28 @@ +package homework_6.map_problems_generator; + +import java.util.Objects; + +public class MapProblemsMutableGenerator{ + private StringBuilder key; + + public MapProblemsMutableGenerator(StringBuilder key) { + this.key = key; + } + + public void setKey(StringBuilder key) { + this.key = key; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return key.equals(that.key); + } + + @Override + public int hashCode() { + return Objects.hash(key); + } +} diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..835f2fcc --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,42 @@ +package homework_7; + +public class Cat { + + private final String breed; + private final int age; + private final String colour; + private final int weight; + + public Cat(String breed, int age, String colour, int weight) { + this.breed = breed; + this.age = age; + this.colour = colour; + this.weight = weight; + } + + public String getBreed() { + return breed; + } + + public int getAge() { + return age; + } + + public String getColour() { + return colour; + } + + public int getWeight() { + return weight; + } + + @Override + public String toString() { + return "Cat{" + + "breed='" + breed + '\'' + + ", age=" + age + + ", colour=" + colour + + ", weight=" + weight + + '}'; + } +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..72da4b21 --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,41 @@ +package homework_7; + +public class Kitten { + private final String breed; + private final int age; + private final String colour; + private final String favoriteMeal; + + public Kitten(String breed, int age, String colour, String favoriteMeal) { + this.breed = breed; + this.age = age; + this.colour = colour; + this.favoriteMeal = favoriteMeal; + } + + public String getBreed() { + return breed; + } + + public int getAge() { + return age; + } + + public String getColour() { + return colour; + } + + public String getFavoriteMeal() { + return favoriteMeal; + } + + @Override + public String toString() { + return "Kitten{" + + "breed='" + breed + '\'' + + ", age=" + age + + ", colour=" + colour + + ", favoriteMeal='" + favoriteMeal + '\'' + + '}'; + } +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..7005f8c6 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,7 @@ +package homework_7; + +@FunctionalInterface +public interface KittenToCatFunction { + + C grow(T object); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..4ed83715 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,18 @@ +package homework_7; + +import java.util.Random; + +public class Main { + public static void main(String[] args) { + Kitten kitten = new Kitten("bobtail", 2, "grey", "chicken"); + System.out.println(kitten); + + KittenToCatFunction transform = newKitten -> new Cat(newKitten.getBreed(), new Random().nextInt(12) + 1, newKitten.getColour(), 3); + + Cat cat = transform.grow(kitten); + System.out.println(); + System.out.println(cat); + } + +} + diff --git a/src/main/resources/custom_file_reader/emptyFileForTests.txt b/src/main/resources/custom_file_reader/emptyFileForTests.txt new file mode 100644 index 00000000..e69de29b diff --git a/src/main/resources/custom_file_reader/fileDotsCommasOnly.txt b/src/main/resources/custom_file_reader/fileDotsCommasOnly.txt new file mode 100644 index 00000000..17b12b42 --- /dev/null +++ b/src/main/resources/custom_file_reader/fileDotsCommasOnly.txt @@ -0,0 +1 @@ +,.,.,.,.,.,.,.,.,.,.,.,.,., \ No newline at end of file diff --git a/src/main/resources/custom_file_reader/fileTest.txt b/src/main/resources/custom_file_reader/fileTest.txt new file mode 100644 index 00000000..4a58d843 --- /dev/null +++ b/src/main/resources/custom_file_reader/fileTest.txt @@ -0,0 +1 @@ +dfgdfg,dg.d.gdfg,g,dfg.df,g.fdg,df.gf.g,,,,,,fdg.dfg.dfg.df.gdf.,g, \ 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..1212a5bf --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,82 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterTest extends UnitBase { + + @Test + void EmptyInputTest() { + setInput(""); + + new PyramidPrinter().run(); + removeFromOutput("Please type a positive integer number:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void NullInputTest() { + setInput("0"); + + new PyramidPrinter().run(); + removeFromOutput("Please type a positive integer number:"); + assertEquals("", + getOutputLines()[0]); + } + + @Test + void CorrectInputTest() { + setInput("5"); + + new PyramidPrinter().run(); + removeFromOutput("Please type a positive integer number:"); + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + assertEquals("xxxx", getOutputLines()[3]); + assertEquals("xxxxx", getOutputLines()[4]); + } + + @Test + void NegativeInputTest() { + setInput("-5"); + + new PyramidPrinter().run(); + removeFromOutput("Please type a positive integer number:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void LongNotIntInputTest() { + setInput("99999999999999999"); + + new PyramidPrinter().run(); + removeFromOutput("Please type a positive integer number:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void StringInputTest() { + setInput("hello"); + + new PyramidPrinter().run(); + removeFromOutput("Please type a positive integer number:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void DoubleInputTest() { + setInput("0.5"); + + new PyramidPrinter().run(); + removeFromOutput("Please type a positive integer number:"); + 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..d87c9adf --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,69 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class RandomCharsTableTest extends UnitBase { + + @Test + void EmptyInputTest() { + setInput(""); + + new RandomCharsTable().run(); + removeFromOutput("Please type size of a table: 2 numbers and strategy - even or odd:"); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", + getOutputLines()[0]); + } + + @Test + void NullSizeInputTest() { + setInput("0 0 odd"); + + new RandomCharsTable().run(); + removeFromOutput("Please type size of a table: 2 numbers and strategy - even or odd:"); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", + getOutputLines()[0]); + } + + @Test + void NegativeInputTest() { + setInput("-3 4 even"); + + new RandomCharsTable().run(); + removeFromOutput("Please type size of a table: 2 numbers and strategy - even or odd:"); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", + getOutputLines()[0]); + } + + @Test + void WrongStrategyInputTest() { + setInput("3 4 fghgfhgfh"); + + new RandomCharsTable().run(); + removeFromOutput("Please type size of a table: 2 numbers and strategy - even or odd:"); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", + getOutputLines()[0]); + } + + @Test + void OnlyStringInputTest() { + setInput("hello"); + + new RandomCharsTable().run(); + removeFromOutput("Please type size of a table: 2 numbers and strategy - even or odd:"); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", + getOutputLines()[0]); + } + + @Test + void WrongNumberOfParamsInputTest() { + setInput("123"); + + new RandomCharsTable().run(); + removeFromOutput("Please type size of a table: 2 numbers and strategy - even or odd:"); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", + getOutputLines()[0]); + } +} 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..8630513d --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,119 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import homework_2.pyramid_printer.PyramidPrinter; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class TrafficLightTest extends UnitBase { + @Test + void EmptyInputTest() { + setInput(""); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void NullGreenColorInputTest() { + setInput("0"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("[32mGREEN\u001B[0m", + getOutputLines()[0]); + } + + @Test + void GreenColorInputTest() { + setInput("5"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("[32mGREEN\u001B[0m", + getOutputLines()[0]); + } + + @Test + void YellowColorInputTest() { + setInput("35"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("[33mYELLOW\u001B[0m", + getOutputLines()[0]); + } + + @Test + void RedColorInputTest() { + setInput("54"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("[31mRED\u001B[0m", + getOutputLines()[0]); + } + + @Test + void DayIsOverInputTest() { + setInput("86400"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("The day is over", + getOutputLines()[0]); + } + + @Test + void NegativeInputTest() { + setInput("-55"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void StringInputTest() { + setInput("hello"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void DoubleInputTest() { + setInput("0.5"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void LongInputTest() { + setInput("999999999999999"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + getOutputLines()[0]); + } + + @Test + void TwoArgumentsInputTest() { + setInput("5 7"); + + new TrafficLight().run(); + removeFromOutput("Please type your current time in seconds:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", + 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..e2ba7526 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,27 @@ +package homework_4.custom_annotation; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CustomAnnotationTest { + + @Test + public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException { + Object object = new Object(); + ObjectToJsonConverter serializer = new ObjectToJsonConverter(); + assertThrows(JsonSerializationException.class, () -> { + serializer.convertToJson(object); + }); + } + + @Test + public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException { + Person person = new Person("John", "Ivanov", "50"); + ObjectToJsonConverter serializer = new ObjectToJsonConverter(); + String jsonString = serializer.convertToJson(person); + assertEquals( + "{\"personAge\":\"50\",\"firstName\":\"John\",\"lastName\":\"Ivanov\"}", + jsonString); + } +} 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..09a3c161 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,169 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class CustomFileReaderTest extends UnitBase { + + @Test() + public void givenWrongFile_whenRun1_thenException() { + String file = "src/main/resources/custom_file_reader/djfhghdjfg.txt"; + Assertions.assertThrows(IOException.class, () -> { + new CustomFileReader(file).run1(); + }); + } + + @Test + public void givenEmptyFile_whenRun1_thenEmpty() throws IOException { + String file = "src/main/resources/custom_file_reader/emptyFileForTests.txt"; + new CustomFileReader(file).run1(); + assertEquals("", getOutput()); + } + + @Test + public void givenFileDotsCommasOnly_whenRun1_thenEmpty() throws IOException { + String file = "src/main/resources/custom_file_reader/fileDotsCommasOnly.txt"; + new CustomFileReader(file).run1(); + assertEquals("", getOutput()); + } + + @Test + public void givenTextFile_whenRun1_thenNewText() throws IOException { + String file = "src/main/resources/custom_file_reader/fileTest.txt"; + new CustomFileReader(file).run1(); + assertEquals("dfgdfgdgdgdfggdfgdfgfdgdfgfgfdgdfgdfgdfgdfg", getOutput()); + } + + @Test() + public void givenWrongFile_whenRun2_thenException() { + String file = "src/main/resources/custom_file_reader/djfhghdjfg.txt"; + Assertions.assertThrows(FileNotFoundException.class, () -> { + new CustomFileReader(file).run2(); + }); + } + + @Test + public void givenEmptyFile_whenRun2_thenEmpty() throws FileNotFoundException { + String file = "src/main/resources/custom_file_reader/emptyFileForTests.txt"; + new CustomFileReader(file).run2(); + assertEquals("", getOutput()); + } + + @Test + public void givenFileDotsCommasOnly_whenRun2_thenEmpty() throws FileNotFoundException { + String file = "src/main/resources/custom_file_reader/fileDotsCommasOnly.txt"; + new CustomFileReader(file).run2(); + assertEquals("", getOutput()); + } + + @Test + public void givenTextFile_whenRun2_thenNewText() throws FileNotFoundException { + String file = "src/main/resources/custom_file_reader/fileTest.txt"; + new CustomFileReader(file).run2(); + assertEquals("dfgdfgdgdgdfggdfgdfgfdgdfgfgfdgdfgdfgdfgdfg", getOutput()); + } + + @Test() + public void givenWrongFile_whenRun3_thenException() { + Path path = Paths.get("src/main/resources/custom_file_reader/fhfghfghfgh.txt"); + ; + Assertions.assertThrows(IOException.class, () -> { + new CustomFileReader(path).run3(); + }); + } + + @Test + public void givenEmptyFile_whenRun3_thenEmpty() throws IOException { + Path path = Paths.get("src/main/resources/custom_file_reader/emptyFileForTests.txt"); + ; + new CustomFileReader(path).run3(); + assertEquals("", getOutput()); + } + + @Test + public void givenFileDotsCommasOnly_whenRun3_thenEmpty() throws IOException { + Path path = Paths.get("src/main/resources/custom_file_reader/fileDotsCommasOnly.txt"); + ; + new CustomFileReader(path).run3(); + assertEquals("", getOutput()); + } + + @Test + public void givenTextFile_whenRun3_thenNewText() throws IOException { + Path path = Paths.get("src/main/resources/custom_file_reader/fileTest.txt"); + ; + new CustomFileReader(path).run3(); + assertEquals("dfgdfgdgdgdfggdfgdfgfdgdfgfgfdgdfgdfgdfgdfg", getOutput()); + } + + @Test() + public void givenWrongFile_whenRun4_thenException() { + Path path = Paths.get("src/main/resources/custom_file_reader/fhfghfghfgh.txt"); + ; + Assertions.assertThrows(IOException.class, () -> { + new CustomFileReader(path).run4(); + }); + } + + @Test + public void givenEmptyFile_whenRun4_thenEmpty() throws IOException { + Path path = Paths.get("src/main/resources/custom_file_reader/emptyFileForTests.txt"); + ; + new CustomFileReader(path).run4(); + assertEquals("", getOutput()); + } + + @Test + public void givenFileDotsCommasOnly_whenRun4_thenEmpty() throws IOException { + Path path = Paths.get("src/main/resources/custom_file_reader/fileDotsCommasOnly.txt"); + ; + new CustomFileReader(path).run4(); + assertEquals("", getOutput()); + } + + @Test + public void givenTextFile_whenRun4_thenNewText() throws IOException { + Path path = Paths.get("src/main/resources/custom_file_reader/fileTest.txt"); + ; + new CustomFileReader(path).run4(); + assertEquals("dfgdfgdgdgdfggdfgdfgfdgdfgfgfdgdfgdfgdfgdfg", getOutput()); + } + + @Test() + public void givenWrongFile_whenRun5_thenException() { + String file = "src/main/resources/custom_file_reader/djfhghdjfg.txt"; + Assertions.assertThrows(IOException.class, () -> { + new CustomFileReader(file).run5(); + }); + } + + @Test + public void givenEmptyFile_whenRun5_thenEmpty() throws IOException { + String file = "src/main/resources/custom_file_reader/emptyFileForTests.txt"; + new CustomFileReader(file).run5(); + assertEquals("", getOutput()); + } + + @Test + public void givenFileDotsCommasOnly_whenRun5_thenEmpty() throws IOException { + String file = "src/main/resources/custom_file_reader/fileDotsCommasOnly.txt"; + new CustomFileReader(file).run5(); + assertEquals("", getOutput()); + } + + @Test + public void givenTextFile_whenRun5_thenNewText() throws IOException { + String file = "src/main/resources/custom_file_reader/fileTest.txt"; + new CustomFileReader(file).run5(); + assertEquals("dfgdfgdgdgdfggdfgdfgfdgdfgfgfdgdfgdfgdfgdfg", getOutput()); + } + +} 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..eef822b7 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,16 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class SingletonTest { + + @Test + public void givenSingleton_whenCreateTwo_thenSameValues() { + Singleton singleton = Singleton.getInstance("Dog"); + Singleton anotherSingleton = Singleton.getInstance("Cat"); + assertEquals(singleton.value, anotherSingleton.value); + } + +} 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..160af559 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,60 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import homework_5.power_of_number.PowerOfNumber; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomRegexMatcherTest extends UnitBase { + @ParameterizedTest + @MethodSource("validInput") + void ValidInput(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput("Please enter a valid ipv4 address: "); + + assertEquals(getOutput(), "true"); + } + + @ParameterizedTest + @MethodSource("invalidInput") + void InvalidInput(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput("Please enter a valid ipv4 address: "); + + assertEquals(getOutput(), "false"); + } + + private static Stream validInput() { + return Stream.of( + Arguments.of("172.16.254.1"), + Arguments.of("255.255.255.255"), + Arguments.of("172.21.118.45"), + Arguments.of("0.0.0.3"), + Arguments.of("192.168.0.17") + ); + } + + private static Stream invalidInput() { + return Stream.of( + Arguments.of("1.2.3.0"), + Arguments.of("0.0.0.256"), + Arguments.of("x.y.z.t"), + Arguments.of("1...1"), + Arguments.of("1.1.1"), + Arguments.of("1.1.1.1.1"), + Arguments.of("1000.1.1.1"), + Arguments.of("1.2.3.04") + ); + } +} 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..a06295ea --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,62 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PowerOfNumberTest extends UnitBase { + @ParameterizedTest + @MethodSource("validInput") + void ValidInput(String input, String result) { + setInput(input); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please enter number and power of this number: "); + + assertEquals(getOutput(), result); + } + + @ParameterizedTest + @MethodSource("invalidInput") + void InvalidInput(String input) { + setInput(input); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput("Please enter number and power of this number: "); + + assertTrue(getOutput().contains("Only 2 non-negative integers are allowed")); + } + + private static Stream validInput() { + return Stream.of( + Arguments.of("2 2", "4"), + Arguments.of("2 1", "2"), + Arguments.of("2 0", "1"), + Arguments.of("0 2", "0"), + Arguments.of("0 0", "1"), + Arguments.of("10 2", "100"), + Arguments.of("2 10", "1024") + ); + } + + private static Stream invalidInput() { + return Stream.of( + Arguments.of("-300 1"), + Arguments.of("1 -300"), + Arguments.of("-30 -30"), + Arguments.of("hello"), + Arguments.of("one two"), + Arguments.of("1 2 3 4"), + Arguments.of("10"), + Arguments.of(" ") + ); + } +}