diff --git a/README.md b/README.md index 5d686e9f..2aebb793 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,28 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Maria Voronko* | 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/MariaVoronko/src/main/java/homework_1/HomeWork1.java) | The app that reads input arguments and prints them, until "error" argument. | +| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/traffic_light) | The app that reads a number of seconds from the beginning of the day and prints traffic light color at that moment. | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java) | The app that reads pyramid size and prints pyramid of 'x' of given size. | +| HW2 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_2/random_chars_table/RandomCharsTable.java) | The app that prints a table of random chars and finds odd or even letters in it. | +| HW2 | [Tests 2](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_2) | Tests for homework 2. | +| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_3/ImmutableCat.java) | To create an immutable class and write its requirements in comments. | +| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/custom_file_reader) | The app that reads data from file and prints it to the console. | +| HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/singleton) | Singleton design pattern implementation. | +| HW4 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_4/custom_annotation) | Annotation. | +| HW4 | [Tests 4](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_4) | Tests for homework 4. | +| HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_5/custom_regex_mathcer) | The app that checks if input string matches pattern. | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_5/power_of_number) | The app that calculates a number in a power using recursion. | +| HW5 | [Tests 5](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_5) | Tests for homework 5. | +| HW6 | [MapProblemsCollisionGenerator & MapProblemMutableGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_6) | Classes that create problems in HashMap. | +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/homework_7) | The functional interface with an abstract method that turns a Kitten to a Cat. | +| HW7 | [Tests 7](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/homework_7) | Tests for homework 7. | +| Course Project | [Sea Battle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/main/java/course_project) | The app tht plays Sea Battle game with user. | +| Course Project | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/MariaVoronko/src/test/java/course_project) | Tests for Sea Battle. | + +[Link to CodingBat](https://codingbat.com/done?user=mari.waranko@gmail.com&tag=3702089539) [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/build.gradle b/build.gradle index b91dc843..405f66d0 100644 --- a/build.gradle +++ b/build.gradle @@ -10,8 +10,18 @@ repositories { } dependencies { + 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' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + + testCompile("org.junit.jupiter:junit-jupiter-params:5.7.0") + + testImplementation "org.mockito:mockito-core:3.+" } test { diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..ed7ee7aa --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,11 @@ +package course_project; + +import course_project.services.GameService; + +public class Main { + + public static void main(String[] args) { + new GameService().run(); + } + +} diff --git a/src/main/java/course_project/enums/CellStatus.java b/src/main/java/course_project/enums/CellStatus.java new file mode 100644 index 00000000..f7ba7d79 --- /dev/null +++ b/src/main/java/course_project/enums/CellStatus.java @@ -0,0 +1,10 @@ +package course_project.enums; + +public enum CellStatus { + + FREE, + HAS_SHIP, + VISITED, + NOT_VISITED + +} diff --git a/src/main/java/course_project/enums/Response.java b/src/main/java/course_project/enums/Response.java new file mode 100644 index 00000000..e5399a0a --- /dev/null +++ b/src/main/java/course_project/enums/Response.java @@ -0,0 +1,10 @@ +package course_project.enums; + +public enum Response { + + MISSED, + HIT, + KILLED, + VISITED + +} diff --git a/src/main/java/course_project/objects/Cell.java b/src/main/java/course_project/objects/Cell.java new file mode 100644 index 00000000..c9599015 --- /dev/null +++ b/src/main/java/course_project/objects/Cell.java @@ -0,0 +1,35 @@ +package course_project.objects; + +import course_project.enums.CellStatus; + +import static course_project.enums.CellStatus.*; + +public class Cell { + + private final CellStatus status; + private final boolean gotShip; + + public Cell(CellStatus status, boolean gotShip) { + this.status = status; + this.gotShip = gotShip; + } + + public CellStatus getStatus() { + return status; + } + + public boolean hadShip() { + return gotShip; + } + + @Override + public String toString() { + if (status == VISITED) { + if(gotShip) { + return "X"; + } + return "e"; + } + return "-"; + } +} diff --git a/src/main/java/course_project/objects/GameData.java b/src/main/java/course_project/objects/GameData.java new file mode 100644 index 00000000..ff205824 --- /dev/null +++ b/src/main/java/course_project/objects/GameData.java @@ -0,0 +1,65 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.Move; +import course_project.objects.fields.ComputerField; +import course_project.objects.fields.Field; +import course_project.objects.fields.UserField; +import course_project.services.ShipLocationGenerator; + +import java.util.List; + +public class GameData { + + private final ComputerField computerField; + private final UserField userField; + private int computerShips = 10; + private int userShips = 10; + + public GameData(ShipLocationGenerator generator) { + computerField = generator.generateShips(); + userField = new UserField(); + } + + public ComputerField getComputerField() { + return computerField; + } + + public Field getUserField() { + return userField; + } + + public int getComputerShips() { + return computerShips; + } + + public int getUserShips() { + return userShips; + } + + public Response getResponseFromComputer(Move move) { + Response response = computerField.getResponse(move); + if (response == Response.KILLED) { + computerShips--; + } + return response; + } + + public void saveComputerMoveResult(Response response, Move move, List lastHit) { + if (response == Response.KILLED) { + userField.setVisitedAroundShip(lastHit); + userShips--; + } + userField.setCellStatus(move.getX(), move.getY(), CellStatus.VISITED); + } + + public boolean isUserFleetEmpty() { + return userShips == 0; + } + + public boolean isComputerFleetEmpty() { + return computerShips == 0; + } + +} diff --git a/src/main/java/course_project/objects/Move.java b/src/main/java/course_project/objects/Move.java new file mode 100644 index 00000000..91c0d8a6 --- /dev/null +++ b/src/main/java/course_project/objects/Move.java @@ -0,0 +1,30 @@ +package course_project.objects; + +public class Move { + + private final int x; + private final int y; + + public Move(int x, int y) { + this.x = x; + this.y = y; + } + + public Move(String move) { + x = move.charAt(0) - 65; + y = Integer.parseInt(move.substring(1)) - 1; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + @Override + public String toString() { + return (char) (x + 65) + "" + (y + 1); + } +} diff --git a/src/main/java/course_project/objects/fields/ComputerField.java b/src/main/java/course_project/objects/fields/ComputerField.java new file mode 100644 index 00000000..e0490f56 --- /dev/null +++ b/src/main/java/course_project/objects/fields/ComputerField.java @@ -0,0 +1,85 @@ +package course_project.objects.fields; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.Cell; +import course_project.objects.Move; +import course_project.objects.fields.Field; + +import java.util.Arrays; + +public class ComputerField extends Field { + + public ComputerField() { + for (Cell[] row : table) { + Arrays.fill(row, new Cell(CellStatus.FREE, false)); + } + } + + public Response getResponse(Move move) { + if (table[move.getX()][move.getY()].getStatus() == CellStatus.FREE) { + table[move.getX()][move.getY()] = new Cell(CellStatus.VISITED, false); + return Response.MISSED; + } + if (table[move.getX()][move.getY()].getStatus() == CellStatus.VISITED) { + return Response.VISITED; + } + if (table[move.getX()][move.getY()].getStatus() == CellStatus.HAS_SHIP) { + table[move.getX()][move.getY()] = new Cell(CellStatus.VISITED, true); + int x = move.getX(); + int y = move.getY(); + if (hasShipAround(x, y)) { + return Response.HIT; + } + int prevX = -1; + int prevY = -1; + while (true) { + if (x != 0 && x - 1 != prevX && table[x - 1][y].getStatus() == CellStatus.VISITED && table[x - 1][y].hadShip()) { + prevX = x; + x--; + continue; + } + if (x + 1 < 10 && x + 1 != prevX && table[x + 1][y].getStatus() == CellStatus.VISITED && table[x + 1][y].hadShip()) { + prevX = x; + x++; + continue; + } + if (y != 0 && y - 1 != prevY && table[x][y - 1].getStatus() == CellStatus.VISITED && table[x][y - 1].hadShip()) { + prevY = y; + y--; + continue; + } + if (y + 1 < 10 && y + 1 != prevY && table[x][y + 1].getStatus() == CellStatus.VISITED && table[x][y + 1].hadShip()) { + prevY = y; + y++; + continue; + } + if (hasShipAround(x, y)) { + return Response.HIT; + } + break; + } + } + return Response.KILLED; + } + + private boolean hasShipAround(int x, int y) { + return (x != 0 && table[x - 1][y].getStatus() == CellStatus.HAS_SHIP) + || (x + 1 < table.length && table[x + 1][y].getStatus() == CellStatus.HAS_SHIP) + || (y != 0 && table[x][y - 1].getStatus() == CellStatus.HAS_SHIP) + || (y + 1 < table[0].length && table[x][y + 1].getStatus() == CellStatus.HAS_SHIP); + } + + public void printField() { + System.out.println("Computer's field:"); + System.out.println(" 1 2 3 4 5 6 7 8 9 10"); + for (int i = 0; i < 10; i++) { + System.out.print((char) (i + 65)); + System.out.println(Arrays.toString(table[i])); + } + System.out.println("\tX - computer's ship you've destroyed."); + System.out.println("\te - empty cell you've checked."); + System.out.println("\t- - a cell you've not checked."); + } + +} diff --git a/src/main/java/course_project/objects/fields/Field.java b/src/main/java/course_project/objects/fields/Field.java new file mode 100644 index 00000000..655d63d8 --- /dev/null +++ b/src/main/java/course_project/objects/fields/Field.java @@ -0,0 +1,29 @@ +package course_project.objects.fields; + +import course_project.enums.CellStatus; +import course_project.objects.Cell; + +import java.util.Arrays; + +public abstract class Field { + + protected final Cell[][] table = new Cell[10][10]; + + public CellStatus getCellStatus(int x, int y) { + return table[x][y].getStatus(); + } + + public void setCellStatus(int x, int y, CellStatus newStatus) { + if (newStatus == CellStatus.HAS_SHIP) { + table[x][y] = new Cell(newStatus, true); + } else { + table[x][y] = new Cell(newStatus, false); + } + } + + public void printField() { + for (Cell[] row : table) { + System.out.println(Arrays.toString(row)); + } + } +} diff --git a/src/main/java/course_project/objects/fields/UserField.java b/src/main/java/course_project/objects/fields/UserField.java new file mode 100644 index 00000000..635e3c95 --- /dev/null +++ b/src/main/java/course_project/objects/fields/UserField.java @@ -0,0 +1,65 @@ +package course_project.objects.fields; + +import course_project.enums.CellStatus; +import course_project.objects.Cell; +import course_project.objects.Move; +import course_project.objects.fields.Field; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class UserField extends Field { + + public UserField() { + for (Cell[] row : table) { + Arrays.fill(row, new Cell(CellStatus.NOT_VISITED, false)); + } + } + + public void setVisitedAroundShip(List list) { + boolean isSameX = false; + if (list.size() == 1 || list.get(0).getX() == list.get(1).getX()) { + isSameX = true; + } + if (isSameX) { + Comparator byY = Comparator.comparing(Move::getY); + list.sort(byY); + int x = list.get(0).getX(); + int y1 = list.get(0).getY(); + int y2 = list.get(list.size() - 1).getY(); + for (int y = y1 - 1; y <= y2 + 1; y++) { + if (!(0 <= y && y < 10)) { + continue; + } + setCellStatus(x, y, CellStatus.VISITED); + if (x - 1 >= 0) { + setCellStatus(x - 1, y, CellStatus.VISITED); + } + if (x + 1 < 10) { + setCellStatus(x + 1, y, CellStatus.VISITED); + } + } + } else { + Comparator byX = Comparator.comparing(Move::getX); + list.sort(byX); + int y = list.get(0).getY(); + int x1 = list.get(0).getX(); + int x2 = list.get(list.size() - 1).getX(); + for (int x = x1 - 1; x <= x2 + 1; x++) { + if (!(0 <= x && x < 10)) { + continue; + } + setCellStatus(x, y, CellStatus.VISITED); + if (y - 1 >= 0) { + setCellStatus(x, y - 1, CellStatus.VISITED); + } + if (y + 1 < 10) { + setCellStatus(x, y + 1, CellStatus.VISITED); + } + } + } + } + +} diff --git a/src/main/java/course_project/services/GameService.java b/src/main/java/course_project/services/GameService.java new file mode 100644 index 00000000..59b56625 --- /dev/null +++ b/src/main/java/course_project/services/GameService.java @@ -0,0 +1,80 @@ +package course_project.services; + +import course_project.enums.Response; +import course_project.objects.GameData; +import course_project.objects.Move; + +import java.util.ArrayList; +import java.util.List; + +public class GameService { + + private final String WELCOME_MESSAGE = "Welcome to Sea Battle! You are playing with the computer now!"; + private final String USER_WIN_MESSAGE = "You won! Congratulations!!!"; + private final String COMPUTER_WIN_MESSAGE = "Computer won!"; + + public void run() { + UserService userService = new UserService(); + System.out.println(WELCOME_MESSAGE); + GameData data = new GameData(new ShipLocationGenerator()); + processMoves(userService, data); + } + + private void processMoves(UserService userService, GameData data) { + List lastHit = new ArrayList<>(); + boolean isUsersTurn = true; + while (!isGameFinished(data)) { + if (isUsersTurn) { + processUserMoves(userService, data); + isUsersTurn = false; + } else { + processComputerMoves(userService, data, lastHit); + isUsersTurn = true; + } + } + finishGame(data, userService); + } + + private void processUserMoves(UserService userService, GameData gameData) { + Response response; + do { + gameData.getComputerField().printField(); + response = gameData.getResponseFromComputer(userService.getMove()); + userService.printComputerResponse(response); + if (response == Response.KILLED) { + if (isGameFinished(gameData)) return; + } + } while (response == Response.HIT || response == Response.KILLED || response == Response.VISITED); + } + + private void processComputerMoves(UserService userService, GameData data, List lastHit) { + Response response; + do { + Move nextMove = MoveGenerator.generate(data.getUserField(), lastHit); + response = userService.completeComputerMove(nextMove); + if (response == Response.HIT || response == Response.KILLED) { + lastHit.add(nextMove); + } + data.saveComputerMoveResult(response, nextMove, lastHit); + if (response == Response.KILLED) { + lastHit.clear(); + if (isGameFinished(data)) return; + } + } while (response == Response.HIT || response == Response.KILLED); + } + + private boolean isGameFinished(GameData data) { + return data.isComputerFleetEmpty() || data.isUserFleetEmpty(); + } + + private void finishGame(GameData data, UserService userService) { + if (data.isUserFleetEmpty()) { + System.out.println(COMPUTER_WIN_MESSAGE); + } + if (data.isComputerFleetEmpty()) { + System.out.println(USER_WIN_MESSAGE); + } + userService.closeBuffer(); + } + +} diff --git a/src/main/java/course_project/services/InputService.java b/src/main/java/course_project/services/InputService.java new file mode 100644 index 00000000..db0fca29 --- /dev/null +++ b/src/main/java/course_project/services/InputService.java @@ -0,0 +1,26 @@ +package course_project.services; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class InputService { + + BufferedReader br; + + public InputService() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + public String getInput() { + try { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + public void closeBuffer() throws IOException { + br.close(); + } +} diff --git a/src/main/java/course_project/services/MoveGenerator.java b/src/main/java/course_project/services/MoveGenerator.java new file mode 100644 index 00000000..8a20429e --- /dev/null +++ b/src/main/java/course_project/services/MoveGenerator.java @@ -0,0 +1,64 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.fields.Field; +import course_project.objects.Move; + +import java.util.Comparator; +import java.util.List; + +import static java.lang.Math.random; + +public class MoveGenerator { + + public static Move generate(Field userField) { + int x = (int) (random() * 10); + int y = (int) (random() * 10); + while (userField.getCellStatus(x, y) != CellStatus.NOT_VISITED) { + x = (int) (random() * 10); + y = (int) (random() * 10); + } + return new Move(x, y); + } + + public static Move generate(Field userField, List lastHit) { + if (lastHit.size() == 0) { + return generate(userField); + } + int x = lastHit.get(0).getX(); + int y = lastHit.get(0).getY(); + + if (lastHit.size() == 1) { + if (x != 0 && userField.getCellStatus(x - 1, y) == CellStatus.NOT_VISITED) { + return new Move(x - 1, y); + } + if (x + 1 < 10 && userField.getCellStatus(x + 1, y) == CellStatus.NOT_VISITED) { + return new Move(x + 1, y); + } + if (y != 0 && userField.getCellStatus(x, y - 1) == CellStatus.NOT_VISITED) { + return new Move(x, y - 1); + } + return new Move(x, y + 1); + } + + if (x == lastHit.get(1).getX()) { + Comparator byY = Comparator.comparing(Move::getY); + lastHit.sort(byY); + y = Math.min(y, lastHit.get(lastHit.size() - 1).getY()); + if (y != 0 && userField.getCellStatus(x, y - 1) == CellStatus.NOT_VISITED) { + return new Move(x, y - 1); + } + y = Math.max(y, lastHit.get(lastHit.size() - 1).getY()); + return new Move(x, y + 1); + } + Comparator byX = Comparator.comparing(Move::getX); + lastHit.sort(byX); + x = Math.min(x, lastHit.get(lastHit.size() - 1).getX()); + if (x != 0 && userField.getCellStatus(x - 1, y) == CellStatus.NOT_VISITED) { + return new Move(x - 1, y); + } + x = Math.max(x, lastHit.get(lastHit.size() - 1).getX()); + return new Move(x + 1, y); + } + +} diff --git a/src/main/java/course_project/services/ShipLocationGenerator.java b/src/main/java/course_project/services/ShipLocationGenerator.java new file mode 100644 index 00000000..a7e0cd30 --- /dev/null +++ b/src/main/java/course_project/services/ShipLocationGenerator.java @@ -0,0 +1,97 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.fields.ComputerField; +import course_project.objects.fields.Field; + +import static java.lang.Math.random; + +public class ShipLocationGenerator { + + public ComputerField generateShips() { + ComputerField field = new ComputerField(); + placeShips(field, 1, 3); + placeShips(field, 2, 2); + placeShips(field, 3, 1); + placeShips(field, 4, 0); + return field; + } + + private void placeShips(ComputerField field, int amount, int coordDiff) { + for (int i = 0; i < amount; i++) { + boolean foundPlace = false; + while (!foundPlace) { + int x = (int) (random() * 10); + int y = (int) (random() * 10); + if (isValidPlace(field, x, x, y - coordDiff, y)) { + fillShip(field, x, x, y - coordDiff, y); + foundPlace = true; + } else if (isValidPlace(field, x, x + coordDiff, y, y)) { + fillShip(field, x, x + coordDiff, y, y); + foundPlace = true; + } else if (isValidPlace(field, x - coordDiff, x, y, y)) { + fillShip(field, x - coordDiff, x, y, y); + foundPlace = true; + } else if (isValidPlace(field, x, x, y, y + coordDiff)) { + fillShip(field, x, x, y, y + coordDiff); + foundPlace = true; + } + } + } + } + + private boolean isValidPlace(ComputerField field, int x1, int x2, int y1, int y2) { + if (isNotInRange0to9(x1) || isNotInRange0to9(x2) || isNotInRange0to9(y1) || isNotInRange0to9(y2)) { + return false; + } + if (x2 == x1) { + for (int y = y1 - 1; y <= y2 + 1; y++) { + if (isNotInRange0to9(y)) { + continue; + } + if (isNotFreeCell(field, x1, y)) { + return false; + } + if ((!isNotInRange0to9(x1 - 1) && isNotFreeCell(field, x1 - 1, y)) || + (!isNotInRange0to9(x1 + 1) && isNotFreeCell(field, x1 + 1, y))) { + return false; + } + } + } else { + for (int x = x1 - 1; x <= x2 + 1; x++) { + if (isNotInRange0to9(x)) { + continue; + } + if (isNotFreeCell(field, x, y1)) { + return false; + } + if ((!isNotInRange0to9(y1 - 1) && isNotFreeCell(field, x, y1 - 1)) || + (!isNotInRange0to9(y2 + 1) && isNotFreeCell(field, x, y1 + 1))) { + return false; + } + } + } + return true; + } + + private void fillShip(ComputerField field, int x1, int x2, int y1, int y2) { + if (x1 == x2) { + for (int i = y1; i <= y2; i++) { + field.setCellStatus(x1, i, CellStatus.HAS_SHIP); + } + } else { + for (int i = x1; i <= x2; i++) { + field.setCellStatus(i, y1, CellStatus.HAS_SHIP); + } + } + } + + private boolean isNotInRange0to9(int x) { + return !(0 <= x && x <= 9); + } + + private boolean isNotFreeCell(Field field, int x, int y) { + return field.getCellStatus(x, y) != CellStatus.FREE; + } + +} diff --git a/src/main/java/course_project/services/UserService.java b/src/main/java/course_project/services/UserService.java new file mode 100644 index 00000000..c143e021 --- /dev/null +++ b/src/main/java/course_project/services/UserService.java @@ -0,0 +1,81 @@ +package course_project.services; + +import course_project.objects.Move; +import course_project.enums.Response; + +import java.io.IOException; + +public class UserService { + + private final String MOVE_MESSAGE = "Make your move (e. g. D4): "; + private final String RESPONSE_MESSAGE = "\tEnter 0, you have no ship on this cell,\n" + + "\tEnter 1, if part of your ship is on this cell,\n" + + "\tEnter 2, if there is last/only not killed part os your ship.\n" + + "\tEnter a response (a digit from 0 to 2):"; + private final String VISITED_ALREADY_MESSAGE = "You have checked this cell already! Try to make a move again."; + private final String WRONG_MOVE_FORMAT_MESSAGE = "Wrong input format. Try again:"; + private final InputService inputService; + + public UserService() { + inputService = new InputService(); + } + + public Move getMove() { + System.out.println(MOVE_MESSAGE); + String input = inputService.getInput(); + input = input.toUpperCase(); + while (!isValidMove(input)) { + System.out.println(WRONG_MOVE_FORMAT_MESSAGE); + input = inputService.getInput(); + } + return new Move(input); + } + + public Response completeComputerMove(Move move) { + System.out.println("Computer's move: " + move); + System.out.println(RESPONSE_MESSAGE); + String input = inputService.getInput(); + while (!isValidMoveResponse(input)) { + System.out.println(WRONG_MOVE_FORMAT_MESSAGE); + input = inputService.getInput(); + } + return Response.values()[Integer.parseInt(input)]; + } + + public boolean isValidMoveResponse(String input) { + if (input != null) { + return input.matches("[0-2]"); + } + return false; + } + + public boolean isValidMove(String input) { + if (input != null) { + return input.matches("[A-J](10|[1-9])"); + } + return false; + } + + public void printComputerResponse(Response response) { + if (response == Response.VISITED) { + System.out.println(VISITED_ALREADY_MESSAGE); + } else { + if (response == Response.MISSED) { + System.out.println("Computer has no ship there. It's computer's turn to make a move."); + } else if (response == Response.HIT) { + System.out.println("You have hit the computer's ship. It's your turn ta make a move again!"); + } else { + System.out.println("You have destroyed one of computer's ships entirely. It's your turn ta make a move again!"); + } + } + } + + public void closeBuffer() { + try { + inputService.closeBuffer(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/homework_1/HomeWork1.java b/src/main/java/homework_1/HomeWork1.java new file mode 100644 index 00000000..b36a215d --- /dev/null +++ b/src/main/java/homework_1/HomeWork1.java @@ -0,0 +1,17 @@ +package homework_1; + +public class HomeWork1 { + + private static final String RED = "\u001B[31m"; + private static final String RESET = "\u001B[0m"; + + public static void main(String[] args) { + for(String argument: args){ + if(argument.equals("ошибка")){ + System.out.println(RED + "Тревога!" + RESET); + break; + } + System.out.println(argument + ": " + argument.length() + " букв"); + } + } +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java deleted file mode 100644 index 07c029a2..00000000 --- a/src/main/java/homework_1/Main.java +++ /dev/null @@ -1,9 +0,0 @@ -package homework_1; - -public class Main { - - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - -} diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..37e93643 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,9 @@ +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..55e04fc5 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,49 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + public void run() { + System.out.println("Please, input number:"); + String input = setInput(); + if (isValid(input)) { + printPyramid(Integer.parseInt(input)); + } else { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + } + + protected String setInput() { + try(BufferedReader br = + new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + private boolean isValid(String inputString) { + if(inputString == null) { + return false; + } + int pyramidSize; + try { + pyramidSize = Integer.parseInt(inputString); + } catch (NumberFormatException ex) { + return false; + } + return pyramidSize >= 0; + } + + private void printPyramid(int pyramidSize) { + for (int i = 1; i <= pyramidSize; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } +} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..be586c4b --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,8 @@ +package homework_2.random_chars_table; + +public class Main { + + public static void main(String[] args) { + 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..c2f58e05 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,82 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +public class RandomCharsTable { + + public void run() { + System.out.println("Please, enter array length, array width and strategy (odd or even):"); + String input = setInput(); + if (isValid(input)) { + char[][] randomCharsTable = new RandomCharsTableCreator(getRows(input), getColumns(input)).createTable(); + ArrayList selectedChars = findSelectedChars(randomCharsTable, isEven(input)); + printTable(randomCharsTable); + printSelection(selectedChars, isEven(input)); + } else { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + } + } + + protected String setInput() { + try(BufferedReader br = + new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + private boolean isValid(String inputString) { + if(inputString == null) { + return false; + } + return inputString.matches("\\d+ \\d+ (odd|even)"); + } + + private int getRows(String inputString) { + return Integer.parseInt(inputString.split(" ")[0]); + } + + private int getColumns(String inputString) { + return Integer.parseInt(inputString.split(" ")[1]); + } + + private boolean isEven(String inputString) { + return inputString.split(" ")[2].equals("even"); + } + + private ArrayList findSelectedChars(char[][] table, boolean isEven) { + ArrayList selectedChars = new ArrayList<>(); + for (char[] row : table) { + for (char ch : row) { + if ((isEven && ch % 2 == 0) || (!isEven && ch % 2 == 1)) { + selectedChars.add(ch); + } + } + } + return selectedChars; + } + + private void printTable(char[][] table) { + for (char[] row : table) { + System.out.print("|"); + for (char ch : row) { + System.out.print(ch + "|"); + } + System.out.println(); + } + } + + private void printSelection(ArrayList selectedChars, boolean isEven) { + if (isEven) { + System.out.print("Even letters - "); + } else { + System.out.print("Odd letters - "); + } + String letters = selectedChars.toString(); + System.out.println(letters.substring(1, letters.length() - 1)); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java new file mode 100644 index 00000000..353981be --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -0,0 +1,22 @@ +package homework_2.random_chars_table; + +public class RandomCharsTableCreator { + + private final int rows; + private final int columns; + + public RandomCharsTableCreator(int rows, int columns) { + this.rows = rows; + this.columns = columns; + } + + public char[][] createTable() { + char[][] table = new char[rows][columns]; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + table[i][j] = (char) ('A' + Math.random() * 26); + } + } + return table; + } +} 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..fbd5c4ca --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,12 @@ +package homework_2.traffic_light; + +public class Main { + + public static void main(String[] args) { + if (args.length != 0 && args[0].equals("ExtraMode")) { + new TrafficLightExtraMode().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..0b1d0c98 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,66 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + private static final String RESET = "\u001B[0m"; + private static final String RED = "\u001B[31m"; + private static final String YELLOW = "\u001B[33m"; + private static final String GREEN = "\u001B[32m"; + + public void run() { + System.out.println("Please, input time:"); + String input = setInput(); + if (isValid(input)) { + int seconds = getSeconds(input); + printColor(seconds); + } else { + printErrorMessage(); + } + } + + protected String setInput() { + try(BufferedReader br = + new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + + protected boolean isValid(String inputString) { + if(inputString == null) { + return false; + } + return inputString.matches("\\d+"); + } + + protected int getSeconds(String inputValue) { + return Integer.parseInt(inputValue); + } + + private void printColor(int seconds) { + if (isDayOver(seconds)) { + System.out.println("day is over"); + return; + } + if (seconds % 60 < 35) { + System.out.println(GREEN + "GREEN" + RESET); + } else if (seconds % 60 < 40 || seconds % 60 >= 55) { + System.out.println(YELLOW + "YELLOW" + RESET); + } else { + System.out.println(RED + "RED" + RESET); + } + } + + protected boolean isDayOver(int seconds) { + return seconds > 86399; + } + + protected void printErrorMessage() { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java new file mode 100644 index 00000000..d3e18457 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -0,0 +1,45 @@ +package homework_2.traffic_light; + +public class TrafficLightExtraMode extends TrafficLight { + + @Override + protected boolean isValid(String inputString) { + if(inputString == null) { + return false; + } + if (!inputString.contains(":")) { + return false; + } + String[] time = inputString.split(":"); + if (time.length != 3) { + return false; + } + try { + int hours = Integer.parseInt(time[0]); + int minutes = Integer.parseInt(time[1]); + int seconds = Integer.parseInt(time[2]); + if ((hours < 0) + || (minutes < 0 || minutes > 59) + || (seconds < 0 || seconds > 59)) { + return false; + } + } catch (NumberFormatException e) { + return false; + } + return true; + } + + @Override + protected int getSeconds(String inputString) { + String[] time = inputString.split(":"); + int hours = Integer.parseInt(time[0]); + int minutes = Integer.parseInt(time[1]); + int seconds = Integer.parseInt(time[2]); + return hours * 60 * 60 + minutes * 60 + seconds; + } + + @Override + protected void printErrorMessage() { + System.out.println("Only input in format hh:mm:ss is allowed"); + } +} diff --git a/src/main/java/homework_3/ImmutableCat.java b/src/main/java/homework_3/ImmutableCat.java new file mode 100644 index 00000000..ad69151e --- /dev/null +++ b/src/main/java/homework_3/ImmutableCat.java @@ -0,0 +1,68 @@ +package homework_3; + +import java.util.ArrayList; + +/* + Список требований к ImmutableClass: + - Класс должен быть final. + - Поля класса должны быть private. + - Поля класса должны быть final. + - Параметризированные конструкторы должны инициализировать поля ссылочного типа, + используя глубокое копирование. + - В методых класса не изменяем поля класса, а возвращем его измененную копию. + */ + +public final class ImmutableCat { + + private final String name; + private final int yearOfBirth; + private final ArrayList favouriteFood = new ArrayList<>(); + + + public ImmutableCat(String name, int yearOfBirth, ArrayList favouriteFood) { + this.name = name; + this.yearOfBirth = yearOfBirth; + this.favouriteFood.addAll(favouriteFood); + } + + public ImmutableCat(String name){ + this.name = name; + yearOfBirth = 2020; + } + + public ImmutableCat(){ + this.name = "Cat"; + yearOfBirth = 2020; + } + + public String getName() { + return name; + } + + public ImmutableCat setName(String name) { + return new ImmutableCat(name, this.yearOfBirth, this.favouriteFood); + } + + public int getYearOfBirth() { + return yearOfBirth; + } + + public ImmutableCat setYearOfBirth(int yearOfBirth) { + return new ImmutableCat(this.name, yearOfBirth, this.favouriteFood); + } + + public ArrayList getFavouriteFood() { + return new ArrayList<>(favouriteFood); + } + + public ImmutableCat setFavouriteFood(ArrayList favouriteFood) { + return new ImmutableCat(this.name, this.yearOfBirth, favouriteFood); + } + + public ImmutableCat addFavouriteFoodItem(String favouriteFoodItem) { + ArrayList copyFF = new ArrayList<>(favouriteFood); + copyFF.add(favouriteFoodItem); + return new ImmutableCat(this.name, this.yearOfBirth, copyFF); + } + +} diff --git a/src/main/java/homework_4/custom_annotation/Book.java b/src/main/java/homework_4/custom_annotation/Book.java new file mode 100644 index 00000000..1b08b74e --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Book.java @@ -0,0 +1,41 @@ +package homework_4.custom_annotation; + +import lombok.Data; + +import java.lang.reflect.Field; +import java.util.ArrayList; + +@Data +public class Book { + + @ImportantField(priority = 1) + private String title; + @ImportantField(priority = 3) + private String genre = "not specified"; + private String description = ""; + @ImportantField(priority = 2) + private String author = "not specified"; + private int year; + private String publisher = "not specified"; + @ImportantField(priority = 4) + private double cost = 0.00; + + public Book(String title) { + this.title = title; + } + + public void printImportant() throws IllegalAccessException { + ArrayList importantFields = new ArrayList<>(); + for (Field field : this.getClass().getDeclaredFields()) { + if (field.isAnnotationPresent(ImportantField.class)) { + importantFields.add(field); + } + } + FieldPriorityComparator comparator = new FieldPriorityComparator(); + importantFields.sort(comparator); + for (Field field : importantFields) { + System.out.println(field.getName() + ": " + field.get(this) + ";"); + } + } + +} diff --git a/src/main/java/homework_4/custom_annotation/FieldPriorityComparator.java b/src/main/java/homework_4/custom_annotation/FieldPriorityComparator.java new file mode 100644 index 00000000..96449f26 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/FieldPriorityComparator.java @@ -0,0 +1,15 @@ +package homework_4.custom_annotation; + +import java.lang.reflect.Field; +import java.util.Comparator; + +public class FieldPriorityComparator implements Comparator { + + @Override + public int compare(Field f1, Field f2) { + int priority1 = f1.getDeclaredAnnotation(ImportantField.class).priority(); + int priority2 = f2.getDeclaredAnnotation(ImportantField.class).priority(); + return priority1 - priority2; + } + +} diff --git a/src/main/java/homework_4/custom_annotation/ImportantField.java b/src/main/java/homework_4/custom_annotation/ImportantField.java new file mode 100644 index 00000000..941d62a0 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/ImportantField.java @@ -0,0 +1,18 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; + +//аннотация отмечает поля класса как важные +//priority - приоритет поля при выводе + +@Retention(RetentionPolicy.RUNTIME) +@Target(FIELD) +public @interface ImportantField { + + int priority(); + +} 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..70d3b132 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Main.java @@ -0,0 +1,13 @@ +package homework_4.custom_annotation; + +public class Main { + + public static void main(String[] args) throws IllegalAccessException { + Book book = new Book("My Book"); + book.setAuthor("Someone"); + book.setGenre("fantasy"); + book.setCost(300.0); + book.printImportant(); + } + +} 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..ce1482b9 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,53 @@ +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 { + + private final String fileName = "src/main/resources/custom_file_reader"; + + public void run1() throws IOException { + try (FileReader fileReader = new FileReader(fileName)) { + int charCode; + while ((charCode = fileReader.read()) != -1) { + processAndPrintChar(charCode); + } + System.out.println(); + } + } + + public void run2() throws IOException { + try (FileInputStream fileInputStream = new FileInputStream(fileName)) { + int charCode; + while ((charCode = fileInputStream.read()) != -1) { + processAndPrintChar(charCode); + } + System.out.println(); + } + } + + public void run3() throws IOException { + RandomAccessFile file = new RandomAccessFile(fileName, "r"); + FileChannel fileChannel = file.getChannel(); + ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size()); + while (fileChannel.read(byteBuffer) > 0) { + String content = new String(byteBuffer.array(), StandardCharsets.UTF_8); + content = content.replaceAll("[.,]", ""); + System.out.println(content); + byteBuffer.clear(); + } + fileChannel.close(); + file.close(); + } + + private void processAndPrintChar(int charCode) { + char ch = (char) charCode; + if (ch != ',' && ch != '.') { + System.out.print(ch); + } + } + +} diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java new file mode 100644 index 00000000..df3e83d4 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,14 @@ +package homework_4.custom_file_reader; + +import java.io.IOException; + +public class Main { + + public static void main(String[] args) throws IOException { + CustomFileReader cfr = new CustomFileReader(); + cfr.run1(); + cfr.run2(); + cfr.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..82cd6ab8 --- /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 singleton = Singleton.getInstance(); + } + +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..97d471f6 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,25 @@ +package homework_4.singleton; + +public class Singleton { + + private static Singleton singletonInstance; + private String state = "created"; + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + private Singleton() {} + + public static Singleton getInstance() { + if (singletonInstance == null) { + singletonInstance = new Singleton(); + } + return singletonInstance; + } + +} 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..646f0317 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,31 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + + private final String javaFolder = "(java(\\/\\w+)*\\/[A-Z][a-z, A-Z, \\d]*\\.java)"; + private final String regex = "src\\/(main\\/(" + javaFolder + "|resources\\/\\w+(\\.[a-z]+)?)|test\\/" + javaFolder + ")"; + + public void run() { + System.out.println("Regex for a file path in java project starting in src/\n" + + "Example: src/main/java/package_1/Class1.java"); + System.out.println(match()); + } + + private boolean match() { + return Pattern.matches(regex, readString()); + } + + private String readString() { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } +} 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..4dddddc1 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,10 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + CustomRegexMatcher crm = new CustomRegexMatcher(); + crm.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..737b1d9e --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,10 @@ +package homework_5.power_of_number; + +public class Main { + + public static void main(String[] args) { + PowerOfNumber pon = new PowerOfNumber(); + pon.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..75f6dd98 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,50 @@ +package homework_5.power_of_number; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.regex.Pattern; + +public class PowerOfNumber { + + public void run() { + System.out.println("Please, input number and power."); + String input = setInput(); + if (isValid(input)) { + System.out.println(numberToPower(getNumber(input), getPower(input))); + } else { + System.out.println("Only 2 non-negative integers are allowed"); + } + } + + private int numberToPower(int number, int power) { + if (power == 0) { + return 1; + } + return number * numberToPower(number, power - 1); + } + + private boolean isValid(String inputString) { + if(inputString == null) { + return false; + } + return Pattern.matches("\\d+\\s\\d+", inputString); + } + + private int getNumber(String inputString) { + return Integer.parseInt(inputString.split(" ")[0]); + } + + private int getPower(String inputString) { + return Integer.parseInt(inputString.split(" ")[1]); + } + + private String setInput() { + try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { + return br.readLine(); + } catch (IOException e) { + return null; + } + } + +} diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..8e8e6567 --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,30 @@ +package homework_6; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + + public static void main(String[] args) { + mapCollisionProblems(); + mapMutableProblems(); + } + + public static void mapCollisionProblems() { + MapProblemsCollisionGenerator mpcg1 = new MapProblemsCollisionGenerator("Generator 1"); + MapProblemsCollisionGenerator mpcg2 = new MapProblemsCollisionGenerator("Generator 2"); + Map collisionMap = new HashMap<>(); + collisionMap.put(mpcg1, 1); + collisionMap.put(mpcg2, 2); + System.out.println(collisionMap.toString()); + } + + public static void mapMutableProblems() { + MapProblemsMutableGenerator mpmg1 = new MapProblemsMutableGenerator(1000); + Map mutableKeyMap = new HashMap<>(); + mutableKeyMap.put(mpmg1, 1000); + mpmg1.setGeneratorID(2000); + System.out.println(mutableKeyMap.containsKey(mpmg1)); + } + +} diff --git a/src/main/java/homework_6/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..7eb62b6c --- /dev/null +++ b/src/main/java/homework_6/MapProblemsCollisionGenerator.java @@ -0,0 +1,34 @@ +package homework_6; + +public class MapProblemsCollisionGenerator { + + private final String generatorName; + + public MapProblemsCollisionGenerator(String generatorName) { + this.generatorName = generatorName; + } + + @Override + public int hashCode() { + return 1234; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (obj.getClass() == this.getClass()) { + return false; + } + return this.generatorName.equals(((MapProblemsCollisionGenerator) obj).generatorName); + } + + @Override + public String toString() { + return generatorName; + } +} diff --git a/src/main/java/homework_6/MapProblemsMutableGenerator.java b/src/main/java/homework_6/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..fd7803ad --- /dev/null +++ b/src/main/java/homework_6/MapProblemsMutableGenerator.java @@ -0,0 +1,34 @@ +package homework_6; + +public class MapProblemsMutableGenerator { + + private int generatorID; + + public MapProblemsMutableGenerator(int generatorID) { + this.generatorID = generatorID; + } + + public void setGeneratorID(int generatorID) { + this.generatorID = generatorID; + } + + @Override + public int hashCode() { + return Integer.hashCode(generatorID); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (obj.getClass() == this.getClass()) { + return false; + } + return this.generatorID == ((MapProblemsMutableGenerator) obj).generatorID; + } + +} diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..624e6c47 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,35 @@ +package homework_7; + +public class Cat { + + private final String name; + private final double weight; + private final int whiskersLength; + + public Cat(String name, double weight, int whiskersLength) { + this.name = name; + this.weight = weight; + this.whiskersLength = whiskersLength; + } + + public String getName() { + return name; + } + + public double getWeight() { + return weight; + } + + public int getWhiskersLength() { + return whiskersLength; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", weight=" + weight + + ", whiskers length=" + whiskersLength + + '}'; + } +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..e9b29c8a --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,31 @@ +package homework_7; + +public class Kitten { + + private final String name; + private final double weight; + private final int whiskersLength; + + public Kitten(String name, double weight, int whiskersLength) { + this.name = name; + this.weight = weight; + this.whiskersLength = whiskersLength; + } + + public String getName() { + return name; + } + + public double getWeight() { + return weight; + } + + @Override + public String toString() { + return "Kitten{" + + "name='" + name + '\'' + + ", weight=" + weight + + ", whiskersLength=" + whiskersLength + + '}'; + } +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..cf029011 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,7 @@ +package homework_7; + +public interface KittenToCatFunction { + + Cat grow(Kitten kitten); + +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..801fb0f7 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,14 @@ +package homework_7; + +public class Main { + + public static void main(String[] args) { + Kitten barsik = new Kitten("Barsik", 2.5, 4); + System.out.println(barsik.toString()); + + KittenToCatFunction ktc = kitten -> new Cat(kitten.getName(), kitten.getWeight() + 3, 10); + + Cat grownUpBarsik = ktc.grow(barsik); + System.out.println(grownUpBarsik.toString()); + } +} diff --git a/src/main/resources/custom_file_reader b/src/main/resources/custom_file_reader new file mode 100644 index 00000000..b6fb1981 --- /dev/null +++ b/src/main/resources/custom_file_reader @@ -0,0 +1,3 @@ +Hello, world! +second... line... +...=)... \ No newline at end of file diff --git a/src/test/java/course_project/objects/ComputerFieldTest.java b/src/test/java/course_project/objects/ComputerFieldTest.java new file mode 100644 index 00000000..a136ea94 --- /dev/null +++ b/src/test/java/course_project/objects/ComputerFieldTest.java @@ -0,0 +1,43 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.fields.ComputerField; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ComputerFieldTest { + + @Test + void initTest() { + ComputerField computerField = new ComputerField(); + + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + assertEquals(CellStatus.FREE, computerField.getCellStatus(i, j)); + } + } + } + + @Test + void getResponseTest() { + ComputerField computerField = new ComputerField(); + + assertEquals(Response.MISSED, computerField.getResponse(new Move(1, 5))); + assertEquals(Response.VISITED, computerField.getResponse(new Move(1, 5))); + + computerField.setCellStatus(6, 2, CellStatus.VISITED); + assertEquals(Response.VISITED, computerField.getResponse(new Move(6, 2))); + + computerField.setCellStatus(3, 7, CellStatus.HAS_SHIP); + assertEquals(Response.KILLED, computerField.getResponse(new Move(3, 7))); + + computerField.setCellStatus(9, 8, CellStatus.HAS_SHIP); + computerField.setCellStatus(9, 7, CellStatus.HAS_SHIP); + computerField.setCellStatus(9, 6, CellStatus.HAS_SHIP); + assertEquals(Response.HIT, computerField.getResponse(new Move(9, 7))); + assertEquals(Response.HIT, computerField.getResponse(new Move(9, 6))); + assertEquals(Response.KILLED, computerField.getResponse(new Move(9, 8))); + } +} diff --git a/src/test/java/course_project/objects/GameDataTest.java b/src/test/java/course_project/objects/GameDataTest.java new file mode 100644 index 00000000..9aa4618f --- /dev/null +++ b/src/test/java/course_project/objects/GameDataTest.java @@ -0,0 +1,39 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.enums.Response; +import course_project.objects.fields.ComputerField; +import course_project.services.ShipLocationGenerator; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class GameDataTest { + + @Test + void getResponseFromComputerTest() { + ComputerField computerField = new ComputerField(); + computerField.setCellStatus(4, 4, CellStatus.HAS_SHIP); + ShipLocationGenerator generator = Mockito.mock(ShipLocationGenerator.class); + Mockito.when(generator.generateShips()).thenReturn(computerField); + GameData gameData = new GameData(generator); + + assertEquals(Response.KILLED, gameData.getResponseFromComputer(new Move(4, 4))); + assertEquals(9, gameData.getComputerShips()); + } + + @Test + void saveComputerMoveResult() { + GameData gameData = new GameData(new ShipLocationGenerator()); + + List moves = new ArrayList<>(); + moves.add(new Move(1, 1)); + gameData.saveComputerMoveResult(Response.KILLED, moves.get(0), moves); + + assertEquals(9, gameData.getUserShips()); + } +} diff --git a/src/test/java/course_project/objects/MoveTest.java b/src/test/java/course_project/objects/MoveTest.java new file mode 100644 index 00000000..f1431185 --- /dev/null +++ b/src/test/java/course_project/objects/MoveTest.java @@ -0,0 +1,24 @@ +package course_project.objects; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MoveTest { + + @Test + void initMoveTest() { + Move move = new Move(0, 2); + + assertEquals(0, move.getX()); + assertEquals(2, move.getY()); + assertEquals("A3", move.toString()); + + move = new Move("B10"); + + assertEquals(1, move.getX()); + assertEquals(9, move.getY()); + assertEquals("B10", move.toString()); + } + +} diff --git a/src/test/java/course_project/objects/UserFieldTest.java b/src/test/java/course_project/objects/UserFieldTest.java new file mode 100644 index 00000000..e2142b7f --- /dev/null +++ b/src/test/java/course_project/objects/UserFieldTest.java @@ -0,0 +1,42 @@ +package course_project.objects; + +import course_project.enums.CellStatus; +import course_project.objects.fields.UserField; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UserFieldTest { + + @Test + void initTest() { + UserField userField = new UserField(); + + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + assertEquals(CellStatus.NOT_VISITED, userField.getCellStatus(i, j)); + } + } + } + + @Test + void setVisitedAroundShipTest() { + UserField userField = new UserField(); + + List moves = new ArrayList<>(); + moves.add(new Move(1, 2)); + moves.add(new Move(1, 3)); + moves.add(new Move(1, 4)); + userField.setVisitedAroundShip(moves); + + for (int i = 1; i < 6; i++) { + assertEquals(CellStatus.VISITED, userField.getCellStatus(1, i)); + assertEquals(CellStatus.VISITED, userField.getCellStatus(0, i)); + assertEquals(CellStatus.VISITED, userField.getCellStatus(2, i)); + } + } + +} diff --git a/src/test/java/course_project/services/MoveGeneratorTest.java b/src/test/java/course_project/services/MoveGeneratorTest.java new file mode 100644 index 00000000..2a9b15e0 --- /dev/null +++ b/src/test/java/course_project/services/MoveGeneratorTest.java @@ -0,0 +1,44 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.Move; +import course_project.objects.fields.UserField; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class MoveGeneratorTest { + + @Test + void generateTest() { + Move move = MoveGenerator.generate(new UserField()); + + assertTrue(0 <= move.getX() && move.getX() < 10); + assertTrue(0 <= move.getY() && move.getY() < 10); + } + + @Test + void generateWithLastHitTest() { + UserField userField = new UserField(); + userField.setCellStatus(3, 3, CellStatus.VISITED); + userField.setCellStatus(2, 3, CellStatus.VISITED); + List lastHit = new ArrayList<>(); + lastHit.add(new Move(3, 3)); + Move move = MoveGenerator.generate(userField, lastHit); + + assertEquals(4, move.getX()); + assertEquals(3, move.getY()); + + userField.setCellStatus(3, 4, CellStatus.VISITED); + lastHit.add(new Move(3, 4)); + move = MoveGenerator.generate(userField, lastHit); + + assertEquals(3, move.getX()); + assertEquals(2, move.getY()); + } + +} diff --git a/src/test/java/course_project/services/ShipLocationGeneratorTest.java b/src/test/java/course_project/services/ShipLocationGeneratorTest.java new file mode 100644 index 00000000..9aa00191 --- /dev/null +++ b/src/test/java/course_project/services/ShipLocationGeneratorTest.java @@ -0,0 +1,44 @@ +package course_project.services; + +import course_project.enums.CellStatus; +import course_project.objects.fields.ComputerField; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ShipLocationGeneratorTest { + + @Test + void generateShipsTest() { + ComputerField computerField = new ShipLocationGenerator().generateShips(); + + int shipCellCount = 0; + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (computerField.getCellStatus(i, j) == CellStatus.HAS_SHIP) { + shipCellCount++; + assertTrue(has0to2shipCellAround(computerField, i, j)); + + } + } + } + + assertEquals(20, shipCellCount); + } + + private boolean has0to2shipCellAround(ComputerField field, int x, int y) { + int hasShipCellCount = 0; + for (int i = x - 1; i <= x + 1; i++) { + for (int j = y - 1; j <= y + 1; j++) { + if (i > 9 || j > 9 || i < 0 || j < 0) { + continue; + } + if (field.getCellStatus(i, j) == CellStatus.HAS_SHIP) { + hasShipCellCount++; + } + } + } + return hasShipCellCount == 1 || hasShipCellCount == 2 || hasShipCellCount == 3; + } +} diff --git a/src/test/java/course_project/services/UserServiceTest.java b/src/test/java/course_project/services/UserServiceTest.java new file mode 100644 index 00000000..c1b78384 --- /dev/null +++ b/src/test/java/course_project/services/UserServiceTest.java @@ -0,0 +1,45 @@ +package course_project.services; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class UserServiceTest { + + @Test + void isValidMoveTest() { + UserService userService = new UserService(); + + assertTrue(userService.isValidMove("A1")); + assertTrue(userService.isValidMove("C10")); + assertTrue(userService.isValidMove("F8")); + assertTrue(userService.isValidMove("D4")); + assertTrue(userService.isValidMove("J10")); + + assertFalse(userService.isValidMove("D0")); + assertFalse(userService.isValidMove("F11")); + assertFalse(userService.isValidMove("M5")); + assertFalse(userService.isValidMove("d6")); + assertFalse(userService.isValidMove("5B")); + assertFalse(userService.isValidMove("string")); + assertFalse(userService.isValidMove("")); + assertFalse(userService.isValidMove("1 6")); + } + + @Test + void isValidMoveResponseTest() { + UserService userService = new UserService(); + + assertTrue(userService.isValidMoveResponse("0")); + assertTrue(userService.isValidMoveResponse("1")); + assertTrue(userService.isValidMoveResponse("2")); + + assertFalse(userService.isValidMoveResponse("3")); + assertFalse(userService.isValidMoveResponse("M5")); + assertFalse(userService.isValidMoveResponse("string")); + assertFalse(userService.isValidMoveResponse("MISSED")); + assertFalse(userService.isValidMoveResponse("")); + assertFalse(userService.isValidMoveResponse("1 6")); + } +} diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java new file mode 100644 index 00000000..42e0cce5 --- /dev/null +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -0,0 +1,81 @@ +package homework_2; + +import homework_2.pyramid_printer.PyramidPrinter; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PyramidPrinterTest extends base.UnitBase { + + private final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + private final String START_MESSAGE = "Please, input number:"; + + @Test + void correctInputTest1() { + setInput("2"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + } + + @Test + void correctInputTest2() { + setInput("8"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xxxx", getOutputLines()[3]); + assertEquals("xxxxxxxx", getOutputLines()[7]); + } + + @Test + void nullInputTest() { + setInput("0"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("", getOutputLines()[0]); + } + + @Test + void negativeInputTest() { + setInput("-10"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void stringInputTest() { + setInput("string"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void bigNumberInputTest() { + setInput("5666677772444198455342456"); + + new PyramidPrinter().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } +} diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java new file mode 100644 index 00000000..9a1dda73 --- /dev/null +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -0,0 +1,139 @@ +package homework_2; + +import homework_2.random_chars_table.RandomCharsTable; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class RandomCharsTableTest extends base.UnitBase { + + private final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + private final String START_MESSAGE = "Please, enter array length, array width and strategy (odd or even):"; + + @Test + void findOddTest() { + setInput("2 3 odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + String oddChar = getOutputLines()[getOutputLines().length - 1]; + removeFromOutput(oddChar); + oddChar = oddChar.replaceFirst("Odd letters - ", ""); + oddChar = oddChar.replaceAll(", ", ""); + for (char ch : oddChar.toCharArray()) { + assertEquals((int) ch % 2, 1); + } + + assertEquals(getOutputLines().length, 2); + int oddCount = 0; + for (String row : getOutputLines()) { + row = row.replaceAll("\\|", ""); + for (char ch : row.toCharArray()) { + assertTrue((65 <= (int) ch) && ((int) ch <= 91)); + if ((int) ch % 2 == 1) { + oddCount++; + } + } + } + assertEquals(oddCount, oddChar.toCharArray().length); + } + + @Test + void findEvenTest() { + setInput("5 4 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + String evenChar = getOutputLines()[getOutputLines().length - 1]; + removeFromOutput(evenChar); + evenChar = evenChar.replaceFirst("Even letters - ", ""); + evenChar = evenChar.replaceAll(", ", ""); + for (char ch : evenChar.toCharArray()) { + assertEquals((int) ch % 2, 0); + } + + assertEquals(getOutputLines().length, 5); + int evenCount = 0; + for (String row : getOutputLines()) { + row = row.replaceAll("\\|", ""); + for (char ch : row.toCharArray()) { + assertTrue((65 <= (int) ch) && ((int) ch <= 91)); + if ((int) ch % 2 == 0) { + evenCount++; + } + } + } + assertEquals(evenCount, evenChar.toCharArray().length); + } + + @Test + void biggerAmountOfArgumentsInputTest() { + setInput("3 4 8 odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void smallerAmountOfArgumentsInputTest() { + setInput("3 4"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void nullAndNegativeInputTest() { + setInput("-3 0 even"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void unrecognizedStrategyTest() { + setInput("3 8 hello"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void wrongNumberInputTest() { + setInput("u and odd"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void tooBigNumberInputTest() { + setInput("399372544437489926467 8 hello"); + + new RandomCharsTable().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } +} diff --git a/src/test/java/homework_2/TrafficLightExtraModeTest.java b/src/test/java/homework_2/TrafficLightExtraModeTest.java new file mode 100644 index 00000000..8c4b9239 --- /dev/null +++ b/src/test/java/homework_2/TrafficLightExtraModeTest.java @@ -0,0 +1,119 @@ +package homework_2; + +import homework_2.traffic_light.TrafficLightExtraMode; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TrafficLightExtraModeTest extends TrafficLightTest { + + private final String ERROR_MESSAGE = "Only input in format hh:mm:ss is allowed"; + + @Override + @Test + void getGreenTest() { + setInput("11:08:5"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("GREEN")); + } + + @Override + @Test + void getYellowTest() { + setInput("09:18:36"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Override + @Test + void getRedTest() { + setInput("01:59:49"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("RED")); + } + + @Override + @Test + void nullInputTest() { + setInput("00:00:00"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("GREEN")); + } + + @Override + @Test + void charInputTest() { + setInput("14:08:t"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Override + @Test + void stringInputTest() { + setInput("string"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Override + @Test + void tooBigInputTest() { + setInput("24:01:00"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("day is over", getOutput()); + } + + @Test + void wrongTimeParametersNumberTest() { + setInput("04:58"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void wrongTimeFormatTest() { + setInput("04:61:89"); + + new TrafficLightExtraMode().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + +} diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java new file mode 100644 index 00000000..740587d4 --- /dev/null +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -0,0 +1,90 @@ +package homework_2; + +import homework_2.traffic_light.TrafficLight; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TrafficLightTest extends base.UnitBase { + + protected final String START_MESSAGE = "Please, input time:"; + private final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + + @Test + void getGreenTest() { + setInput("5"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void getYellowTest() { + setInput("35"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void getRedTest() { + setInput("54"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("RED")); + } + + @Test + void nullInputTest() { + setInput("0"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void tooBigInputTest() { + setInput("86401"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("day is over", getOutput()); + } + + @Test + void stringInputTest() { + setInput("string"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void charInputTest() { + setInput("c"); + + new TrafficLight().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } +} diff --git a/src/test/java/homework_4/CustomFileReaderTest.java b/src/test/java/homework_4/CustomFileReaderTest.java new file mode 100644 index 00000000..a6ea3a2b --- /dev/null +++ b/src/test/java/homework_4/CustomFileReaderTest.java @@ -0,0 +1,69 @@ +package homework_4; + +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +public class CustomFileReaderTest extends base.UnitBase { + + private final String fileName = "src/main/resources/custom_file_reader"; + CustomFileReader cfr = new CustomFileReader(); + + public static Stream testCases() { + return Stream.of( + arguments("First test.\nHello, World...\n...last,, line.", "First test\nHello World\nlast line"), + arguments("..2 test,\n:)/|,:;.", "2 test\n:)/|:;"), + arguments("...", ""), + arguments(",,,", ""), + arguments("", "") + ); + } + + @ParameterizedTest + @MethodSource("testCases") + void run1Test(String fileContent, String expected) throws IOException { + try (PrintWriter pw = new PrintWriter(fileName)) { + pw.print(fileContent); + } + + cfr.run1(); + printOut(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCases") + void run2Test(String fileContent, String expected) throws IOException { + try (PrintWriter pw = new PrintWriter(fileName)) { + pw.print(fileContent); + } + + cfr.run2(); + printOut(); + + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCases") + void run3Test(String fileContent, String expected) throws IOException { + try (PrintWriter pw = new PrintWriter(fileName)) { + pw.print(fileContent); + } + + cfr.run2(); + printOut(); + + assertEquals(expected, getOutput()); + } + +} diff --git a/src/test/java/homework_4/ImportantFieldTest.java b/src/test/java/homework_4/ImportantFieldTest.java new file mode 100644 index 00000000..35d1726b --- /dev/null +++ b/src/test/java/homework_4/ImportantFieldTest.java @@ -0,0 +1,57 @@ +package homework_4; + +import homework_4.custom_annotation.Book; +import homework_4.custom_annotation.ImportantField; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ImportantFieldTest extends base.UnitBase { + + private Book book; + + @BeforeEach + void init() { + book = new Book("Some book"); + } + + @Test + void annotationTest() throws NoSuchFieldException { + ArrayList importantFields = new ArrayList<>(); + for (Field field : book.getClass().getDeclaredFields()) { + if (field.isAnnotationPresent(ImportantField.class)) { + importantFields.add(field); + } + } + + assertEquals(4, importantFields.size()); + assertEquals(1, book.getClass().getDeclaredField("title") + .getAnnotation(ImportantField.class).priority()); + assertEquals(2, book.getClass().getDeclaredField("author") + .getAnnotation(ImportantField.class).priority()); + assertEquals(3, book.getClass().getDeclaredField("genre") + .getAnnotation(ImportantField.class).priority()); + assertEquals(4, book.getClass().getDeclaredField("cost") + .getAnnotation(ImportantField.class).priority()); + } + + @Test + void printImportantTest() throws IllegalAccessException { + book.setCost(300.0); + + book.printImportant(); + printOut(); + + assertEquals(4, getOutputLines().length); + assertEquals("title: Some book;", getOutputLines()[0]); + assertTrue(getOutputLines()[1].contains("author")); + assertTrue(getOutputLines()[2].contains("genre")); + assertEquals("cost: 300.0;", getOutputLines()[3]); + } + +} diff --git a/src/test/java/homework_4/SingletonTest.java b/src/test/java/homework_4/SingletonTest.java new file mode 100644 index 00000000..11b6a593 --- /dev/null +++ b/src/test/java/homework_4/SingletonTest.java @@ -0,0 +1,26 @@ +package homework_4; + +import homework_4.singleton.Singleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SingletonTest { + + @Test + void singletonFeaturesTest() { + Singleton singleton1 = Singleton.getInstance(); + Singleton singleton2 = Singleton.getInstance(); + + assertEquals("created", singleton1.getState()); + assertEquals("created", singleton2.getState()); + + singleton1.setState("changed"); + + assertEquals("changed", singleton1.getState()); + assertEquals("changed", singleton2.getState()); + + assertEquals(singleton2, singleton1); + } + +} diff --git a/src/test/java/homework_5/CustomRegexMatcherTest.java b/src/test/java/homework_5/CustomRegexMatcherTest.java new file mode 100644 index 00000000..8c968446 --- /dev/null +++ b/src/test/java/homework_5/CustomRegexMatcherTest.java @@ -0,0 +1,69 @@ +package homework_5; + +import homework_5.custom_regex_matcher.CustomRegexMatcher; +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.params.provider.Arguments.arguments; + +public class CustomRegexMatcherTest extends base.UnitBase { + + private final String START_MESSAGE = "Regex for a file path in java project starting in src/\n" + + "Example: src/main/java/package_1/Class1.java"; + + @ParameterizedTest + @MethodSource("validTestCases") + void validInputTest(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("true", getOutput()); + } + + @ParameterizedTest + @MethodSource("invalidTestCases") + void invalidInputTest(String input) { + setInput(input); + + new CustomRegexMatcher().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals("false", getOutput()); + } + + public static Stream validTestCases() { + return Stream.of( + arguments("src/main/java/package_1/MyClass.java"), + arguments("src/main/java/package_1/subpackage/MyClass.java"), + arguments("src/main/java/MyClass.java"), + arguments("src/main/resources/my_file"), + arguments("src/main/resources/File.txt"), + arguments("src/main/resources/some_file.html"), + arguments("src/test/java/package_1/MyClassTest.java"), + arguments("src/main/java/package_1/subpackage/MyClassTest.java"), + arguments("src/main/java/MyTest.java") + ); + } + + public static Stream invalidTestCases() { + return Stream.of( + arguments("string"), + arguments("src/main/java/myClass.java"), + arguments("src/main/java/my_package.java/MyClass.java"), + arguments("src/main/resources/file.txt.html"), + arguments("src//main/java/package_1/subpackage/MyClass.java"), + arguments("src/main/java/package_1/subpackage/MyClassTest"), + arguments("src/main/java/package_1/subpackage/"), + arguments("src/main/resources/") + ); + } + +} diff --git a/src/test/java/homework_5/PowerOfNumberTest.java b/src/test/java/homework_5/PowerOfNumberTest.java new file mode 100644 index 00000000..38676da6 --- /dev/null +++ b/src/test/java/homework_5/PowerOfNumberTest.java @@ -0,0 +1,99 @@ +package homework_5; + +import homework_5.power_of_number.PowerOfNumber; +import org.junit.jupiter.api.Test; +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.params.provider.Arguments.arguments; + +public class PowerOfNumberTest extends base.UnitBase { + + private final String START_MESSAGE = "Please, input number and power."; + private final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; + + @Test + void negativeInputTest() { + setInput("-2 4"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void moreArgumentsTest() { + setInput("2 1 8"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void oneArgumentTest() { + setInput("5"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void noArgumentsTest() { + setInput(""); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @Test + void stringInputTest() { + setInput("string input"); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(ERROR_MESSAGE, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCases") + void calculationTest(String input, String expected) { + setInput(input); + + new PowerOfNumber().run(); + printOut(); + removeFromOutput(START_MESSAGE); + + assertEquals(expected, getOutput()); + } + + public static Stream testCases() { + return Stream.of( + arguments("2 2", "4"), + arguments("2 1", "2"), + arguments("4 0", "1"), + arguments("0 17", "0"), + arguments("3 5", "243"), + arguments("2 10", "1024"), + arguments("10 4", "10000"), + arguments("7 3", "343") + ); + } + +} diff --git a/src/test/java/homework_7/KittenToCatFunctionTest.java b/src/test/java/homework_7/KittenToCatFunctionTest.java new file mode 100644 index 00000000..9c7cc7ad --- /dev/null +++ b/src/test/java/homework_7/KittenToCatFunctionTest.java @@ -0,0 +1,23 @@ +package homework_7; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class KittenToCatFunctionTest { + + private KittenToCatFunction ktc = kitten -> new Cat(kitten.getName(), kitten.getWeight() + 3, 10); + + @Test + public void interfaceTest() { + Kitten barsik = new Kitten("Barsik", 2.5, 4); + + Cat grownUpBarsik = ktc.grow(barsik); + + assertEquals(Cat.class, grownUpBarsik.getClass()); + assertEquals(barsik.getName(), grownUpBarsik.getName()); + assertEquals(barsik.getWeight() + 3, grownUpBarsik.getWeight()); + assertEquals(10, grownUpBarsik.getWhiskersLength()); + } + +}