diff --git a/README.md b/README.md index 5d686e9f..8e627300 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,26 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Gabdrakhimova Regina* | 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/ReginaGabdrakhimova/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_2/traffic_light ) | The app reads input argument of seconds from the beginning of the day and shows the traffic light | +| | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_2/pyramid_printer ) | The app reads input argument and builds the required pyramid of letters | +| | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_2/random_chars_table ) | The app reads input arguments and prints a table of random letters based on the data | +| | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/test/java/homework_2_tests ) | Tests to homework_2 | +| HW3 | [Immutable class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_3/immutable_class ) | Immutable class describing the required contents of my bag | +| | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/test/java/homework_3_tests ) | Tests to homework_3 | +| HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_4/singleton ) | Singleton app | +| | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_4/custom_file_reader ) | The app reads a file in different ways and outputs text excluding the characters "," and ".". | +| | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_4/custom_annotation ) | Student class uses custom annotation StudentInformation to fill fields in class constructor. | +| | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/test/java/homework_4_tests ) | Tests to homework_4 | +| HW5 | [Custom Regex Matcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_5/custom_regex_matcher ) | The app reads input string and checks password strength | +| | [Power Of Number](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_5/power_of_number ) | The app reads input arguments(number and power) and prints number raised to the power | +| | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/test/java/homework_5_tests ) | Tests to homework_5 | +| HW6 | [Map Problems Generator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_6/map_problems_generator ) | The app shows case with collision in hashmap and case when it is impossible to get object by key from hashmap | +| HW7 | [Kitten To Cat Function](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/homework_7 ) | KittenToCatFunction interface, whose abstract grow() method can only accept Kitten and inheritors and return only Cat and inheritors | +| Course Project | [Sea Battle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/main/java/course_project ) | Sea Battle Game | +| | [Tests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/ReginaGabdrakhimova/src/test/java/course_project_test ) | Course project tests | -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to CodingBat](https://codingbat.com/done?user=gabdrakhimovarr@gmail.com&tag=707251349) diff --git a/build.gradle b/build.gradle index b91dc843..aee2580c 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.6.2") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-params:5.6.2") } test { diff --git a/src/main/java/course_project/Game.java b/src/main/java/course_project/Game.java new file mode 100644 index 00000000..952f07cd --- /dev/null +++ b/src/main/java/course_project/Game.java @@ -0,0 +1,195 @@ +package course_project; + +import java.util.Random; +import java.util.Scanner; + +public class Game { + private static boolean isFinish = false; + private static GameField additionalFieldForComp; + private static GameField additionalFieldForHuman; + private static final String ERROR_MESSAGE = "Input must contain letter from A to J and number from 1 to 10 without a space, please try again:"; + + public void run() { + System.out.println("Hey! Mr computer invites you to play sea battle! The ships are already positioned across the field.\n" + + "Shoot and hit enemy ships. If you shoot successfully, you can shoot again, and the enemy misses a turn. \n" + + "The game continues until one of the players (you or computer) shoot all the enemy ships. \n"); + + Player human = new Player(); + Player comp = new Player(); + + human.printField(comp); + + battle(human, comp); + } + + public void battle(Player human, Player comp) { + Scanner sc = new Scanner(System.in); + additionalFieldForComp = new GameField(false); + additionalFieldForHuman = new GameField(false); + + while (!isFinish) { + boolean humanShotOnTarget = true; + boolean compShotOnTarget = true; + + while (humanShotOnTarget) { + System.out.println("Enter the coordinate of the opponent's field (for example A1):"); + int[] input = readInput(sc); + int x = input[0]; + int y = input[1]; + + humanShotOnTarget = changeCellStatus(x, y, comp); + if (humanShotOnTarget) { + human.printField(comp); + System.out.println("You were lucky! Shoot again, computer skips."); + } + + if (checkFinishOfGame(comp.getNumHitCells(), human.getNumHitCells())) { + isFinish = true; + return; + } + } + + comp.setNumOfLastShots(0); + + while (compShotOnTarget) { + int[] enemyMove = enemyMove(); + int enemyX = enemyMove[0]; + int enemyY = enemyMove[1]; + + compShotOnTarget = changeCellStatus(enemyX, enemyY, human); + + if (compShotOnTarget) + comp.setNumOfLastShots(comp.getNumOfLastShots()+1); + + if (checkFinishOfGame(comp.getNumHitCells(), human.getNumHitCells())) { + isFinish = true; + return; + } + } + + human.printField(comp); + + if (comp.getNumOfLastShots() > 0) + System.out.println("\nComputer hit well, it fired " + comp.getNumOfLastShots() + " additional shots, you missed a move."); + } + } + + private int[] enemyMove() { + boolean shot = false; + int x = 0, y = 0; + while (!shot) { + x = new Random().nextInt(9)+1; + y = new Random().nextInt(9)+1; + + // Moment was provided when random coordinate of computer shot could fall into filled cell. + // The cycle will continue until computer enters empty cell. + if (additionalFieldForComp.cells[x][y] == GameField.CellStatus.FREE) { + additionalFieldForComp.cells[x][y] = GameField.CellStatus.FILLED; + shot = true; + } + } + + return new int[]{x, y}; + } + + private boolean checkFinishOfGame(int compNumHitCells, int humanNumHitCells) { + if (humanNumHitCells == 20) { + System.out.println("Computer is winner! Don't be upset, you are great too!"); + return true; + } else if (compNumHitCells == 20) { + System.out.println("You are winner! Congratulations!"); + return true; + } + return false; + } + + private boolean changeCellStatus(int x, int y, Player player) { + boolean shotOnTarget = false; + if (player.getField().cells[x][y] == GameField.CellStatus.FREE) { + player.getField().cells[x][y] = GameField.CellStatus.FAULT; + shotOnTarget = false; + } else if (player.getField().cells[x][y] == GameField.CellStatus.SHIP) { + player.getField().cells[x][y] = GameField.CellStatus.HIT; + shotOnTarget = true; + player.increaseNumHitCells(); + } + + return shotOnTarget; + } + + public static int[] readInput(Scanner sc) { + + int[] input = new int[2]; + boolean correctInput = false; + + boolean shot = false; + while (!shot) { + String str = sc.nextLine(); + correctInput = checkingCorrectInput(str); + + if (correctInput) { + input[0] = convertX(str.substring(0,1)); + input[1] = Integer.parseInt(str.substring(1)); + + if (additionalFieldForHuman.cells[input[0]][input[1]] == GameField.CellStatus.FREE) { + additionalFieldForHuman.cells[input[0]][input[1]] = GameField.CellStatus.FILLED; + shot = true; + } else { + System.out.println("You've already shot this cage. Enter coordinate of free cell:"); + shot = false; + } + } else System.out.println(ERROR_MESSAGE); + } + + return input; + } + + public static boolean checkingCorrectInput(String str) { + int[] input = new int[2]; + boolean correctInput = false; + if (str.length() < 2 || str.length() > 3) { + return false; + } + + if (str.substring(0,1).matches("[A-J]") && str.substring(1).matches("[0-9]{1,2}")) { + try { + input[1] = Integer.parseInt(str.substring(1)); + if (input[1] > 0 && input[1] < 11) + correctInput = true; + } catch (NumberFormatException ex) { + correctInput = false; + } + } else { + correctInput = false; + } + + return correctInput; + } + + public static int convertX(String s) { + switch (s) { + case ("A"): + return 1; + case ("B"): + return 2; + case ("C"): + return 3; + case ("D"): + return 4; + case ("E"): + return 5; + case ("F"): + return 6; + case ("G"): + return 7; + case ("H"): + return 8; + case ("I"): + return 9; + case ("J"): + return 10; + } + + return 0; + } +} diff --git a/src/main/java/course_project/GameField.java b/src/main/java/course_project/GameField.java new file mode 100644 index 00000000..749d8947 --- /dev/null +++ b/src/main/java/course_project/GameField.java @@ -0,0 +1,89 @@ +package course_project; + +import java.util.Random; + +public class GameField { + + public CellStatus[][] cells; + + public GameField(boolean isMainField) { + cells = new CellStatus[12][12]; + for (int i = 0; i < 12; i++) { + for (int j = 0; j < 12; j++) { + cells[i][j] = CellStatus.FREE; + } + } + + if (isMainField) { + createShip(4); + createShip(3); + createShip(3); + createShip(2); + createShip(2); + createShip(2); + createShip(1); + createShip(1); + createShip(1); + createShip(1); + } + } + + public enum CellStatus { + FREE, + FAULT, + HIT, + SHIP, + FILLED + } + + public void createShip(int deckNum) { + boolean enoughSpaceAround = false; + int[] coordinates = new int[]{0,0}; + boolean horizontal = new Random().nextBoolean(); + + while (!enoughSpaceAround) { + coordinates = setRandomCoordinates(deckNum, horizontal); + enoughSpaceAround = checkSpaceAround(coordinates[0], coordinates[1], deckNum, horizontal); + } + + setStatusShipInCell(deckNum, horizontal, coordinates); + } + + public boolean checkSpaceAround(int x, int y, int num, boolean horizontal) { + if (horizontal) { + for (int i = x-1; i < x+num+1; i++) { + for (int j = y-1; j < y+2; j++) { + if (cells[i][j] == CellStatus.SHIP) return false; + } + } + } else { + for (int i = x-1; i < x+2; i++) { + for (int j = y-1; j < y+num+1; j++) { + if (cells[i][j] == CellStatus.SHIP) return false; + } + } + } + + return true; + } + + private int[] setRandomCoordinates(int deckNum, boolean horizontal) { + int x = new Random().nextInt(10-deckNum)+1; + int y = new Random().nextInt(9)+1; + + if (horizontal) return new int[]{x, y}; + else return new int[]{y, x}; + } + + public void setStatusShipInCell(int deckNum, boolean horizontal, int[] coordinates) { + if (horizontal) { + for (int i = 0; i < deckNum; i++) { + cells[coordinates[0]+i][coordinates[1]] = CellStatus.SHIP; + } + } else { + for (int i = 0; i < deckNum; i++) { + cells[coordinates[0]][coordinates[1]+i] = CellStatus.SHIP; + } + } + } +} diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..3e49745f --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,7 @@ +package course_project; + +public class Main { + public static void main(String[] args) { + new Game().run(); + } +} diff --git a/src/main/java/course_project/Player.java b/src/main/java/course_project/Player.java new file mode 100644 index 00000000..06e8bfed --- /dev/null +++ b/src/main/java/course_project/Player.java @@ -0,0 +1,117 @@ +package course_project; + +public class Player { + + private GameField field; + private int numHitCells; + private int numOfLastShots; + + public Player() { + this.field = new GameField(true); + this.numHitCells = 0; + this.numOfLastShots = 0; + } + + public GameField getField() { + return field; + } + + public int getNumOfLastShots() { + return numOfLastShots; + } + + public void setNumOfLastShots(int numOfLastShots) { + this.numOfLastShots = numOfLastShots; + } + + public int getNumHitCells() { + return numHitCells; + } + + public void increaseNumHitCells() { + numHitCells++; + } + + public void printField(Player comp) { + System.out.println(" Your field: Field of opponent: "); + StringBuilder letters = new StringBuilder("A B C D E F G H I J"); + System.out.print(" "); + printWithUnderline(letters); + System.out.print(" "); + printWithUnderline(letters); + System.out.println(); + + for (int i = 1; i < 11; i++) { + StringBuilder s = new StringBuilder(); + if (i != 10) s.append(" "); + s.append(i); + + s.append("|"); + if (i == 10) { + System.out.print(s); + s = s.delete(0,s.length()); + } + for (int j = 1; j < 11; j++) { + s.append(humanSymbolToPrint(field.cells[j][i])); + + if (j != 10) s.append(" "); + } + if (i == 10) { + printWithUnderline(s); + s = s.delete(0,s.length()); + } + + s.append("| "); + if (i != 10) s.append(" "); + s.append(i); + s.append("|"); + if (i == 10) { + System.out.print(s); + s = s.delete(0,s.length()); + } + + for (int j = 1; j < 11; j++) { + s.append(compSymbolToPrint(comp.field.cells[j][i])); + + if (j != 10) s.append(" "); + } + if (i == 10) { + printWithUnderline(s); + System.out.println("|"); + } else { + System.out.println(s + "|"); + } + + } + System.out.println(); + } + + private String humanSymbolToPrint(GameField.CellStatus cellStatus) { + String s; + if (cellStatus == GameField.CellStatus.FAULT) + s = "-"; + else if (cellStatus == GameField.CellStatus.HIT) + s = "X"; + else if (cellStatus == GameField.CellStatus.SHIP) + s = "#"; + else s = " "; + + return s; + } + + private String compSymbolToPrint(GameField.CellStatus cellStatus) { + String s; + if (cellStatus == GameField.CellStatus.FAULT) + s = "-"; + else if (cellStatus == GameField.CellStatus.HIT) + s = "X"; + else s = " "; + + return s; + } + + private void printWithUnderline(StringBuilder s) { + System.out.print("\033[0;4m" + s + "\033[0;0m"); + } + +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..3875963d 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,9 +1,17 @@ package homework_1; public class Main { + static final String RED = "\u001b[31m"; + static final String RESET = "\u001b[0m"; - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - + public static void main(String[] args) { + for (int i = 0; i < args.length; i++) { + if (args[i].equals("error")) { + System.out.println(RED + "Alarm!"+ RESET); + break; + } else { + System.out.println(args[i] + ": " + args[i].length() + " letters"); + } + } + } } 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..ff4c1bab --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,46 @@ +package homework_2.pyramid_printer; + +import java.util.Scanner; + +public class PyramidPrinter { + private static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run(){ + Scanner sc = new Scanner(System.in); + int numb; + String str; + System.out.println("Please enter the number:"); + if (!sc.hasNextInt()) { + System.out.println(ERROR_MESSAGE); + return; + } else { + str = sc.nextLine(); + str = str.trim(); + if (!str.matches("[-+]?\\d+")) { + System.out.println(ERROR_MESSAGE); + return; + } + numb = Integer.parseInt(str); + if (numb < 0) { + System.out.println(ERROR_MESSAGE); + return; + } else { + printPyramid(numb); + } + } + sc.close(); + } + + public void printPyramid(int numb){ + if (numb == 0) { + return; + } + for (int i = 1; i <= numb; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("x"); + } + System.out.print("\n"); + } + } +} + 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..ac8b35ac --- /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..af246ba4 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,84 @@ +package homework_2.random_chars_table; + +import java.util.Random; +import java.util.Scanner; + +public class RandomCharsTable { + + private static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + public void run(){ + System.out.println("Please enter number of rows, columns and even|odd:"); + Scanner sc = new Scanner(System.in); + String str = sc.nextLine(); + String[] subStr= str.split(" "); + + if (subStr.length != 3) { + System.out.println(ERROR_MESSAGE); + return; + } + + int rows = 0; + int columns = 0; + + try { + rows = Integer.parseInt(subStr[0]); + columns = Integer.parseInt(subStr[1]); + } catch (NumberFormatException ex) { + System.out.println(ERROR_MESSAGE); + return; + } + + if ((!subStr[2].equals("even")) && (!subStr[2].equals("odd"))) { + System.out.println(ERROR_MESSAGE); + return; + } + + if (rows < 1 || columns < 1) { + System.out.println(ERROR_MESSAGE); + } + + String evenOrOdd = subStr[2]; + boolean isEven = false; + + if (evenOrOdd.equals("even")){ + isEven = true; + } + + printTable(rows, columns, isEven); + sc.close(); + } + + private void printTable(int rows, int columns, boolean isEven) { + String result = ""; + Random random = new Random(); + int [][] arr = new int[rows][columns]; + int a = 65; + int b = 90; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < columns; j++) { + arr[i][j] = a + (random.nextInt(b - a + 1)); + System.out.print("|"); + System.out.print((char)arr[i][j]); + if (!(arr[i][j] % 2 == 0) ^ (isEven)) { + result = result.concat(Character.toString((char)arr[i][j])); + result = result.concat(","); + } + } + System.out.print("|\n"); + } + + if (result.length() == 0) { + result = ""; + } else { + result = result.substring(0, result.length() - 1); + } + + if (isEven){ + System.out.print("Even letters - " + result); + } else { + System.out.print("Odd letters - " + result); + } + } +} 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..2184caef --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,7 @@ +package homework_2.traffic_light; + +public class Main { + public static void main(String[] args){ + new TrafficLight().run(); + } +} diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..1bd3324b --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,51 @@ +package homework_2.traffic_light; + +import java.util.Scanner; + +public class TrafficLight { + private static final String RED = "\u001b[31m"; + private static final String YELLOW = "\u001B[33m"; + private static final String GREEN = "\u001B[32m"; + private static final String RESET = "\u001b[0m"; + private static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + + public void run(){ + Scanner sc = new Scanner(System.in); + int numb; + String str; + System.out.println("Please enter time in seconds:"); + if (!sc.hasNextInt()) { + System.out.println(ERROR_MESSAGE); + return; + } else { + str = sc.nextLine(); + str = str.trim(); + if (!str.matches("[-+]?\\d+")) { + System.out.println(ERROR_MESSAGE); + return; + } + numb = Integer.parseInt(str); + if (numb < 0) { + System.out.println(ERROR_MESSAGE); + return; + } else if (numb > 86399) { + System.out.println("The day is over"); + return; + } else { + printTrafficLight(numb); + } + } + sc.close(); + } + + public void printTrafficLight(int sec){ + int light = sec % 60; + if ((light >=0) && (light < 35)) { + System.out.println(GREEN + "GREEN" + RESET); + } else if (((light >=35) && (light < 40)) || ((light >=55) && (light < 60))) { + System.out.println(YELLOW + "YELLOW" + RESET); + } else { + System.out.println(RED + "RED" + RESET); + } + } +} diff --git a/src/main/java/homework_3/immutable_class/MyImmutableBag.java b/src/main/java/homework_3/immutable_class/MyImmutableBag.java new file mode 100644 index 00000000..082e05c3 --- /dev/null +++ b/src/main/java/homework_3/immutable_class/MyImmutableBag.java @@ -0,0 +1,75 @@ +package homework_3.immutable_class; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * Immutable class requirements: + * - class must be declared final, + * - fields in class must be private and final, + * - getters must return a copy of the object, + * - method for changing field of object should return a copy of the object with changed field, and not directly change the field, + * - constructor should copy passed reference objects into new one, not insert direct references. + */ + +public final class MyImmutableBag { + + private final int cash; + private final ArrayList documents; + private final Map pills; + + public MyImmutableBag(){ + documents = new ArrayList<>(); + documents.add("Passport"); + documents.add("INN"); + documents.add("Medical policy"); + cash = 1000; + pills = new HashMap<>(); + pills.put("Allergy pills", "Loratadine"); + pills.put("Headache tablets", "Citramone"); + pills.put("Tablets from temperature", "Paracetamol"); + } + + public MyImmutableBag(int cash){ + this.cash = cash; + documents = new ArrayList<>(); + documents.add("Passport"); + documents.add("INN"); + documents.add("Medical policy"); + pills = new HashMap<>(); + pills.put("Allergy pills", "Loratadine"); + pills.put("Headache tablets", "Citramone"); + pills.put("Tablets from temperature", "Paracetamol"); + } + + public MyImmutableBag(int cash, ArrayList documents, Map pills){ + this.cash = cash; + this.documents = new ArrayList<>(documents); + this.pills = new HashMap<>(pills); + } + + public int getCash() { + return this.cash; + } + + public ArrayList getDocuments() { + return new ArrayList<>(documents); + } + + public Map getPills() { + return new HashMap<>(pills); + } + + public MyImmutableBag changeCash(int newCash) { + return new MyImmutableBag(newCash, getDocuments(), getPills()); + } + + public MyImmutableBag changeDocuments(ArrayList newDocuments) { + return new MyImmutableBag(cash, new ArrayList<>(newDocuments), getPills()); + } + + public MyImmutableBag changePills(Map newPills) { + return new MyImmutableBag(cash, getDocuments(), new HashMap<>(newPills)); + } +} diff --git a/src/main/java/homework_4/custom_annotation/Student.java b/src/main/java/homework_4/custom_annotation/Student.java new file mode 100644 index 00000000..f81ac4d0 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Student.java @@ -0,0 +1,46 @@ +package homework_4.custom_annotation; + +@StudentInformation(city = "Saint-Petersburg", language = "Java") +public class Student { + private String name; + private String email; + private String city; + private String language; + + public Student(String name, String email) { + this.name = name; + this.email = email; + city = Student.class.getAnnotation(StudentInformation.class).city(); + language = Student.class.getAnnotation(StudentInformation.class).language(); + } + + public Student(String name, String email, String city) { + this.name = name; + this.email = email; + this.city = city; + language = Student.class.getAnnotation(StudentInformation.class).language(); + } + + public Student(String name, String email, String city, String language) { + this.name = name; + this.email = email; + this.city = city; + this.language = language; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } + + public String getLanguage() { + return language; + } + + public String getCity() { + return city; + } +} diff --git a/src/main/java/homework_4/custom_annotation/StudentInformation.java b/src/main/java/homework_4/custom_annotation/StudentInformation.java new file mode 100644 index 00000000..e74a6a42 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/StudentInformation.java @@ -0,0 +1,13 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface StudentInformation { + String city(); + String language(); +} 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..e092c39a --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,52 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +public class CustomFileReader { + //reading file with BufferedReader + public void run1() { + try (BufferedReader in = new BufferedReader(new FileReader(new File("src/main/resources/custom_file_reader/input.txt")))) { + String str; + while ((str = in.readLine()) != null) { + System.out.println(str.replaceAll("[,.]", "")); + } + } + catch (IOException e) { + e.printStackTrace(); + } + } + + //reading file with nio Files.readAllLines + public void run2() { + Path path = Paths.get("src/main/resources/custom_file_reader/input.txt"); + List list = null; + try { + list = Files.readAllLines(path); + + for (String str : list) + System.out.println(str.replaceAll("[,.]", "")); + } + catch (IOException | NullPointerException e) { + e.printStackTrace(); + } + } + + //reading a file with BufferedInputStream and FileInputStream + public void run3() { + try (BufferedInputStream in = new BufferedInputStream(new FileInputStream("src/main/resources/custom_file_reader/input.txt"))) { + int i; + + while ((i = in.read()) != -1) { + if ((char)i != ',' && (char)i != '.') + System.out.print((char)i); + } + } + catch (IOException e) { + e.printStackTrace(); + } + } +} 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..3cd5f930 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,7 @@ +package homework_4.custom_file_reader; + +public class Main { + public static void main(String[] args) { + new CustomFileReader().run1(); + } +} 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..930dcf6b --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,14 @@ +package homework_4.singleton; + +public class Singleton { + private static Singleton instance; + + private Singleton() {} + + public static Singleton getInstance() { + if (instance == null) { + instance = new Singleton(); + } + return instance; + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..1eb3f562 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,54 @@ +package homework_5.custom_regex_matcher; + +import java.util.Scanner; + +public class CustomRegexMatcher { + + public void run() { + Scanner sc = new Scanner(System.in); + System.out.println("Enter your password: "); + + String str = sc.nextLine(); + if (str.isEmpty()) System.out.println("The entered string is empty, password must be at least 8 characters long."); + boolean perfectPassword = str.matches("^(?=.*[0-9].*)(?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[!$%#^].*)[0-9a-zA-Z!$%#^]{8,}$"); + + if (perfectPassword) + System.out.println("Password security: " + true); + else + printReasonOfFail(str); + } + + public void printReasonOfFail(String str) { + if (str.matches("^(?=.*[0-9].*)(?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[!$%#^].*)[0-9a-zA-Z!$%#^]")) { + System.out.println("Password must be at least 8 characters long."); + return; + } + + if (str.matches("^(?=.*[0-9].*)(?=.*[a-z].*)(?=.*[A-Z].*)[0-9a-zA-Z]{8,}$")) { + System.out.println("Password must contain special characters: !, $, %, #, ^"); + return; + } + + if (str.matches("^(?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[!$%#^].*)[a-zA-Z!$%#^]{8,}$")) { + System.out.println("Password must contain digits: 0-9"); + return; + } + + if (str.matches("^(?=.*[0-9].*)(?=.*[!$%#^].*)[0-9!$%#^]{8,}$")) { + System.out.println("Password must contain lowercase and uppercase letters."); + return; + } + + if (str.matches("^(?=.*[0-9].*)(?=.*[a-z].*)(?=.*[!$%#^].*)[0-9a-z!$%#^]{8,}$")) { + System.out.println("Password must contain uppercase letters."); + return; + } + + if (str.contains(" ")) { + System.out.println("Password must not contain a space."); + return; + } + + System.out.println("Password at least 8 characters long must contain lowercase and uppercase letters, digits and special characters: !, $, %, #, ^."); + } +} 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..b154eb1b --- /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..e3944ec1 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,43 @@ +package homework_5.power_of_number; + +import java.util.Scanner; + +public class PowerOfNumber { + + private static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; + + public void run() { + System.out.println("Please enter 2 non-negative numbers:"); + Scanner sc = new Scanner(System.in); + String str = sc.nextLine(); + String[] subStr= str.split(" "); + + if (subStr.length != 2) { + System.out.println(ERROR_MESSAGE); + return; + } + + int num = 0; + int pow = 0; + + try { + num = Integer.parseInt(subStr[0]); + pow = Integer.parseInt(subStr[1]); + } catch (NumberFormatException ex) { + System.out.println(ERROR_MESSAGE); + return; + } + + System.out.println(raiseNumToPower(num, pow)); + } + + public int raiseNumToPower(int num, int pow) { + if (pow == 0) return 1; + + if (pow == 1) return num; + + if (num == 0) return 0; + + return num * raiseNumToPower(num, pow - 1); + } +} 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..9ca493ec --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,8 @@ +package homework_6.map_problems_generator; + +public class Main { + public static void main(String[] args) { + new MapProblemsGenerator().run1(); + new MapProblemsGenerator().run2(); + } +} 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..bb11007a --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java @@ -0,0 +1,34 @@ +package homework_6.map_problems_generator; + +public class MapProblemsCollisionGenerator { + + private final String value; + + public MapProblemsCollisionGenerator(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (obj == null || obj.getClass() != this.getClass()) { + return false; + } + + MapProblemsCollisionGenerator example = (MapProblemsCollisionGenerator) obj; + + return (value != null && value.equals(example.getValue())); + } + + @Override + public int hashCode() { + return 1; + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java new file mode 100644 index 00000000..8ab37a40 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,35 @@ +package homework_6.map_problems_generator; + +import java.util.HashMap; + +public class MapProblemsGenerator { + public void run1() { + HashMap mapWithCollision = new HashMap<>(); + + MapProblemsCollisionGenerator firstObject = new MapProblemsCollisionGenerator("First Object"); + MapProblemsCollisionGenerator secondObject = new MapProblemsCollisionGenerator("Second Object"); + + mapWithCollision.put(firstObject, 1); + mapWithCollision.put(secondObject, 2); + + System.out.println("Collision case in map: "); + mapWithCollision.keySet().forEach(key -> System.out.println(key.getValue() + " = " + mapWithCollision.get(key))); + System.out.println("Are the objects equivalent? " + firstObject.equals(secondObject)); + System.out.println("Does the object have the same hashcode? " + (firstObject.hashCode() == secondObject.hashCode())); + } + + public void run2() { + HashMap mapMutable = new HashMap<>(); + + MapProblemsMutableGenerator thirdObject = new MapProblemsMutableGenerator("Third Object"); + + mapMutable.put(thirdObject, 3); + + System.out.println("\nMutable key problem in map: "); + System.out.println("Trying to get object: " + mapMutable.get(thirdObject)); + + thirdObject.setValue("Modified third object"); + System.out.println("Trying to get modified object: " + mapMutable.get(thirdObject)); + + } +} 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..4759ab3d --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -0,0 +1,40 @@ +package homework_6.map_problems_generator; + +import java.util.Random; + +public class MapProblemsMutableGenerator { + + private String value; + + public MapProblemsMutableGenerator(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (obj == null || obj.getClass() != this.getClass()) { + return false; + } + + MapProblemsCollisionGenerator example = (MapProblemsCollisionGenerator) obj; + + return (value != null && value.equals(example.getValue())); + } + + @Override + public int hashCode() { + return value != null ? value.hashCode() : 0; + } +} diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..1c992837 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,18 @@ +package homework_7; + +public class Cat { + private String name; + private String breed; + private int age; + + public Cat(String name, String breed, int age){ + this.name = name; + this.breed = breed; + this.age = age; + } + + @Override + public String toString() { + return "Cat: " + name + ", " + breed + ", cat is " + age + " years old!"; + } +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..278ebe03 --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,30 @@ +package homework_7; + +public class Kitten { + private String name; + private String breed; + private String yearOfBirth; + + public Kitten(String name, String breed, String yearOfBirth) { + this.name = name; + this.breed = breed; + this.yearOfBirth = yearOfBirth; + } + + public String getName() { + return name; + } + + public String getBreed() { + return breed; + } + + public String getYearOfBirth() { + return yearOfBirth; + } + + @Override + public String toString() { + return "Kitten: " + name + ", " + breed + ", was born in " + yearOfBirth; + } +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..6f42db2a --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7; + +@FunctionalInterface +public interface KittenToCatFunction { + N grow(T t); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..62a7b59e --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,24 @@ +package homework_7; + +public class Main { + public static void main(String[] args) { + Kitten kitten = new Kitten("Murzik", "simple kitten", "2020"); + KittenToCatFunction kittenToCatFunction = (k) -> { + int yearOfBirth = 0; + try + { + yearOfBirth = Integer.parseInt(k.getYearOfBirth()); + } + catch (NumberFormatException nfe) + { + System.out.println("NumberFormatException: " + nfe.getMessage()); + } + + return new Cat(k.getName(), k.getBreed(), 2021-yearOfBirth); + }; + Cat cat = kittenToCatFunction.grow(kitten); + + System.out.println(kitten); + System.out.println(cat); + } +} diff --git a/src/main/resources/custom_file_reader/input.txt b/src/main/resources/custom_file_reader/input.txt new file mode 100644 index 00000000..cde8a42f --- /dev/null +++ b/src/main/resources/custom_file_reader/input.txt @@ -0,0 +1,5 @@ +I'm sure you've been asked many times whether you're an introvert or an extrovert. For some people, it's an easy choice, but for most of us, it's difficult to choose one way or the other. + +It's hard to choose because the introvert/extrovert dichotomy reflects a tired and outdated view of personality. Personality traits exist along a continuum, and the vast majority of us aren't introverts or extroverts - we fall somewhere in the middle. + +Personality consists of a stable set of preferences and tendencies through which we approach the world. Personality traits form at an early age and are fixed by early adulthood. Many important things about you change over the course of your lifetime, but your personality isn't one of them. diff --git a/src/main/resources/custom_file_reader/output.txt b/src/main/resources/custom_file_reader/output.txt new file mode 100644 index 00000000..2ef5dc7b --- /dev/null +++ b/src/main/resources/custom_file_reader/output.txt @@ -0,0 +1,5 @@ +I'm sure you've been asked many times whether you're an introvert or an extrovert For some people it's an easy choice but for most of us it's difficult to choose one way or the other + +It's hard to choose because the introvert/extrovert dichotomy reflects a tired and outdated view of personality Personality traits exist along a continuum and the vast majority of us aren't introverts or extroverts - we fall somewhere in the middle + +Personality consists of a stable set of preferences and tendencies through which we approach the world Personality traits form at an early age and are fixed by early adulthood Many important things about you change over the course of your lifetime but your personality isn't one of them diff --git a/src/test/java/course_project_test/CourseProjectTest.java b/src/test/java/course_project_test/CourseProjectTest.java new file mode 100644 index 00000000..069dfce0 --- /dev/null +++ b/src/test/java/course_project_test/CourseProjectTest.java @@ -0,0 +1,99 @@ +package course_project_test; + +import base.UnitBase; +import course_project.Game; +import course_project.GameField; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CourseProjectTest extends UnitBase { + + @Test + void givenCorrectInput_whenCheckingIncorrectInput_thenTrue() { + assertTrue(Game.checkingCorrectInput("A10")); + assertTrue(Game.checkingCorrectInput("B1")); + assertTrue(Game.checkingCorrectInput("I7")); + assertTrue(Game.checkingCorrectInput("C8")); + assertTrue(Game.checkingCorrectInput("J10")); + } + + @Test + void givenIncorrectInput_whenCheckingIncorrectInput_thenFalse() { + assertFalse(Game.checkingCorrectInput("A11")); + assertFalse(Game.checkingCorrectInput("A 1")); + assertFalse(Game.checkingCorrectInput("A90")); + assertFalse(Game.checkingCorrectInput(" ")); + assertFalse(Game.checkingCorrectInput("")); + assertFalse(Game.checkingCorrectInput("J")); + assertFalse(Game.checkingCorrectInput("a1")); + assertFalse(Game.checkingCorrectInput("two")); + assertFalse(Game.checkingCorrectInput("B100")); + } + + @Test + void givenFieldWithShips_whenCheckSpaceAround() { + GameField field = new GameField(false); + field.setStatusShipInCell(4, true, new int[]{6,9}); + field.setStatusShipInCell(3, true, new int[]{4,1}); + field.setStatusShipInCell(3, false, new int[]{7,5}); + field.setStatusShipInCell(2, false, new int[]{9,1}); + field.setStatusShipInCell(2, false, new int[]{9,6}); + field.setStatusShipInCell(2, true, new int[]{3,8}); + field.setStatusShipInCell(1, true, new int[]{7,3}); + field.setStatusShipInCell(1, true, new int[]{3,6}); + field.setStatusShipInCell(1, true, new int[]{1,4}); + field.setStatusShipInCell(1, true, new int[]{1,9}); + + assertFalse(field.checkSpaceAround(2, 5, 3, false)); + assertFalse(field.checkSpaceAround(4, 4, 3, false)); + assertFalse(field.checkSpaceAround(4, 9, 3, true)); + assertFalse(field.checkSpaceAround(10, 5, 1, true)); + assertTrue(field.checkSpaceAround(2, 1, 2, false)); + assertTrue(field.checkSpaceAround(5, 3, 3, false)); + assertTrue(field.checkSpaceAround(10, 4, 1, true)); + assertTrue(field.checkSpaceAround(3, 3, 3, true)); + } + + @Test + void testConstructorGameField() { + GameField field = new GameField(true); + int countShipCells = countingShipCells(field); + + assertEquals(20, countShipCells); + } + + @Test + void testCreateShip() { + GameField field = new GameField(false); + field.createShip(4); + assertEquals(4, countingShipCells(field)); + + field = new GameField(false); + field.createShip(3); + assertEquals(3, countingShipCells(field)); + + field = new GameField(false); + field.createShip(2); + assertEquals(2, countingShipCells(field)); + + field = new GameField(false); + field.createShip(1); + assertEquals(1, countingShipCells(field)); + } + + private int countingShipCells(GameField field) { + int countShipCells = 0; + + for (int i = 1; i < 11; i++) { + for (int j = 1; j < 11; j++) { + if (field.cells[i][j] == GameField.CellStatus.SHIP) { + countShipCells++; + } + } + } + + return countShipCells; + } +} diff --git a/src/test/java/homework_2_tests/PyramidPrinterTest.java b/src/test/java/homework_2_tests/PyramidPrinterTest.java new file mode 100644 index 00000000..7b42ee4d --- /dev/null +++ b/src/test/java/homework_2_tests/PyramidPrinterTest.java @@ -0,0 +1,101 @@ +package homework_2_tests; + +import homework_2.pyramid_printer.PyramidPrinter; +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PyramidPrinterTest extends UnitBase{ + + private final String errorMassage = "Only 1 non-negative integer is allowed as passed parameter"; + + private void run(){ + new PyramidPrinter().run(); + removeFromOutput("Please enter the number:"); + printOut(); + } + + @Test + void given0_whenRun_thenEmptyPyramid() { + setInput("0"); + + run(); + + assertEquals("", getOutput()); + } + + @Test + void given1_whenRun_thenPrintPyramid() { + setInput("1"); + + run(); + + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given2_whenRun_thenPrintPyramid() { + setInput("2"); + + run(); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + } + + @Test + void givenMinus1_whenRun_thenErrorMassage() { + setInput("-1"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenLetter_whenRun_thenErrorMassage() { + setInput("A"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenWord_whenRun_thenErrorMassage() { + setInput("three"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenDigitWithSpace_whenRun_thenPyramidPrinter() { + setInput(" 2 "); + + run(); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + } + + @Test + void givenTwoDigits_whenRun_thenErrorMassage() { + setInput("1 2"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenDouble_whenRun_thenErrorMassage() { + setInput("5.0"); + + run(); + + assertEquals(errorMassage, getOutput()); + } +} diff --git a/src/test/java/homework_2_tests/RandomCharsTableTest.java b/src/test/java/homework_2_tests/RandomCharsTableTest.java new file mode 100644 index 00000000..17a6cfc1 --- /dev/null +++ b/src/test/java/homework_2_tests/RandomCharsTableTest.java @@ -0,0 +1,121 @@ +package homework_2_tests; + +import homework_2.random_chars_table.RandomCharsTable; +import base.UnitBase; +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 UnitBase{ + + private final String errorMassage = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + private void run(){ + new RandomCharsTable().run(); + removeFromOutput("Please enter number of rows, columns and even|odd:"); + printOut(); + } + + @Test + void given3_3_even_whenRun_thenValidCase() { + setInput("3 3 even"); + + run(); + + assertTrue(getOutput().matches("\\|[A-Z]\\|[A-Z]\\|[A-Z]\\|\\n\\|[A-Z]\\|[A-Z]\\|[A-Z]\\|\\n\\|[A-Z]\\|[A-Z]\\|[A-Z]\\|\\nEven letters - ([BDFHJLNPRTVXZ],)*[BDFHJLNPRTVXZ]*")); + + String endOfLastString = getOutputLines()[3].substring(15); + for (int i = 0; i < 3; i++) { + for (int j = 1; j < 7; j = j + 2) { + String letter = getOutputLines()[i].substring(j,j+1); + if (letter.matches("[BDFHJLNPRTVXZ]")) { + assertTrue(endOfLastString.contains(letter)); + } + } + } + } + + @Test + void given2_2_odd_whenRun_thenValidCase() { + setInput("2 2 odd"); + + run(); + + assertTrue(getOutput().matches("\\|[A-Z]\\|[A-Z]\\|\\n\\|[A-Z]\\|[A-Z]\\|\\nOdd letters - ([ACEGIKMOQSUWY],)*[ACEGIKMOQSUWY]*")); + + String endOfLastString = getOutputLines()[2].substring(14); + for (int i = 0; i < 2; i++) { + for (int j = 1; j < 5; j = j + 2) { + String letter = getOutputLines()[i].substring(j,j+1); + if (letter.matches("[ACEGIKMOQSUWY]")) { + assertTrue(endOfLastString.contains(letter)); + } + } + } + } + + @Test + void givenDigitEven_whenRun_thenErrorMassage() { + setInput("5 even"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenDigitsIncorrectWord_whenRun_thenErrorMassage() { + setInput("5 5 one"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenDigitsEvenIncorrectWord_whenRun_thenErrorMassage() { + setInput("5 5 even one"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenDigitsOnly_whenRun_thenErrorMassage() { + setInput("5 5 "); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenThreeDigits_whenRun_thenErrorMassage() { + setInput("5 5 5"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenOddOnly_whenRun_thenErrorMassage() { + setInput("Odd"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenIncorrectWordOnly_whenRun_thenErrorMassage() { + setInput("Five"); + + run(); + + assertEquals(errorMassage, getOutput()); + } +} diff --git a/src/test/java/homework_2_tests/TrafficLightTest.java b/src/test/java/homework_2_tests/TrafficLightTest.java new file mode 100644 index 00000000..241e0d29 --- /dev/null +++ b/src/test/java/homework_2_tests/TrafficLightTest.java @@ -0,0 +1,99 @@ +package homework_2_tests; + +import homework_2.traffic_light.TrafficLight; +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightTest extends UnitBase{ + + private final String errorMassage = "Only 1 non-negative integer is allowed as passed parameter"; + + private void run(){ + new TrafficLight().run(); + removeFromOutput("Please enter time in seconds:"); + printOut(); + } + + @Test + void given0_whenRun_thenGreen() { + setInput("0"); + + run(); + + assertEquals("[32mGREEN\u001B[0m", getOutput()); + } + + @Test + void given34_whenRun_thenGreen() { + setInput("34"); + + run(); + + assertEquals("[32mGREEN\u001B[0m", getOutput()); + } + + @Test + void given35_whenRun_thenYellow() { + setInput("35"); + + run(); + + assertEquals("[33mYELLOW\u001B[0m", getOutput()); + } + + @Test + void given54_whenRun_thenRed() { + setInput("54"); + + run(); + + assertEquals("[31mRED\u001B[0m", getOutput()); + } + + @Test + void given86401_whenRun_thenTheDayIsOver() { + setInput("86401"); + + run(); + + assertEquals("The day is over", getOutput()); + } + + @Test + void givenLetter_whenRun_thenErrorMassage() { + setInput("A"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenWord_whenRun_thenErrorMassage() { + setInput("one"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenTwoDigits_whenRun_thenErrorMassage() { + setInput("8 9"); + + run(); + + assertEquals(errorMassage, getOutput()); + } + + @Test + void givenDouble_whenRun_thenErrorMassage() { + setInput("5.0"); + + run(); + + assertEquals(errorMassage, getOutput()); + } +} diff --git a/src/test/java/homework_3_tests/ImmutableClassTest.java b/src/test/java/homework_3_tests/ImmutableClassTest.java new file mode 100644 index 00000000..7a06c0f0 --- /dev/null +++ b/src/test/java/homework_3_tests/ImmutableClassTest.java @@ -0,0 +1,32 @@ +package homework_3_tests; + +import homework_3.immutable_class.MyImmutableBag; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +public class ImmutableClassTest { + + @Test + void immutableTest() { + int cash = 2000; + ArrayList documents = new ArrayList<>(Arrays.asList("Passport", "Student ID", "Metro card")); + HashMap pills = new HashMap<>(); + pills.put("Vitamins", "Supradyn"); + pills.put("Medicine for cold", "Coldrex"); + MyImmutableBag myFirstBag = new MyImmutableBag(cash, documents, pills); + pills.remove("Vitamins"); + MyImmutableBag mySecondBag = new MyImmutableBag(cash, documents, pills); + assertNotEquals(myFirstBag, mySecondBag); + assertNotEquals(myFirstBag.getPills(), mySecondBag.getPills()); + + documents.add("Doctor's prescription"); + MyImmutableBag myThirdBag = new MyImmutableBag().changeDocuments(documents); + assertNotEquals(myFirstBag, myThirdBag); + assertNotEquals(myFirstBag.getDocuments(), myThirdBag.getDocuments()); + } +} diff --git a/src/test/java/homework_4_tests/CustomAnnotationTest.java b/src/test/java/homework_4_tests/CustomAnnotationTest.java new file mode 100644 index 00000000..3a95bdeb --- /dev/null +++ b/src/test/java/homework_4_tests/CustomAnnotationTest.java @@ -0,0 +1,46 @@ +package homework_4_tests; + +import homework_4.custom_annotation.Student; +import homework_4.custom_annotation.StudentInformation; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class CustomAnnotationTest { + + @Test + void givenMinimumParametersInput_whenConstructor_thenAllParametersFilled() { + Student student = new Student("Oleg", "Oleg@gmail.com"); + + assertEquals("Oleg", student.getName()); + assertEquals("Oleg@gmail.com", student.getEmail()); + assertEquals("Saint-Petersburg", student.getCity()); + assertEquals("Java", student.getLanguage()); + } + + @Test + void givenParametersInput_whenConstructor_thenCorrectParameters() { + Student student = new Student("Olga", "Olga@gmail.com", "Moscow", "Python"); + + assertEquals("Olga", student.getName()); + assertEquals("Olga@gmail.com", student.getEmail()); + assertEquals("Moscow", student.getCity()); + assertEquals("Python", student.getLanguage()); + } + + @Test + void givenNotAllParametersInput_whenConstructor_thenAllParametersFilled() { + Student student = new Student("Pasha", "Pasha@gmail.com", "Samara"); + + assertEquals("Pasha", student.getName()); + assertEquals("Pasha@gmail.com", student.getEmail()); + assertEquals("Samara", student.getCity()); + assertEquals("Java", student.getLanguage()); + } + + @Test + void givenImplementedAnnotation_whenGetDeclaredAnnotation_thenNotNull() { + assertNotNull(Student.class.getDeclaredAnnotation(StudentInformation.class)); + } +} diff --git a/src/test/java/homework_4_tests/CustomFileReaderTest.java b/src/test/java/homework_4_tests/CustomFileReaderTest.java new file mode 100644 index 00000000..fe14349a --- /dev/null +++ b/src/test/java/homework_4_tests/CustomFileReaderTest.java @@ -0,0 +1,68 @@ +package homework_4_tests; + +import base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.Test; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomFileReaderTest extends UnitBase { + + private static final String INPUT_FILE = "src/main/resources/custom_file_reader/output.txt"; + + @Test + void run1Test() { + new CustomFileReader().run1(); + + try (BufferedReader buffer = new BufferedReader(new FileReader(INPUT_FILE))) { + String expect = buffer.lines().collect(Collectors.joining("\r\n")); + assertEquals(expect, getOutput()); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + void run1TestByNio() { + new CustomFileReader().run1(); + + checkOutput(); + } + + @Test + void run2TestByNio() { + new CustomFileReader().run2(); + + checkOutput(); + } + + @Test + void run3TestByNio() { + new CustomFileReader().run3(); + + checkOutput(); + } + + private void checkOutput() { + Path path = Paths.get(INPUT_FILE); + List list; + try { + list = Files.readAllLines(path); + String expect = list.stream() + .map(s -> s.replaceAll("[,.]", "")) + .collect(Collectors.joining("\r\n")); + + assertEquals(expect, getOutput()); + } catch (IOException | NullPointerException e) { + e.printStackTrace(); + } + } +} diff --git a/src/test/java/homework_4_tests/SingletonTest.java b/src/test/java/homework_4_tests/SingletonTest.java new file mode 100644 index 00000000..bbc19ee3 --- /dev/null +++ b/src/test/java/homework_4_tests/SingletonTest.java @@ -0,0 +1,17 @@ +package homework_4_tests; + +import homework_4.singleton.Singleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SingletonTest { + + @Test + void getInstanceTest() { + Singleton firstSingleton = Singleton.getInstance(); + Singleton secondSingleton = Singleton.getInstance(); + + assertEquals(firstSingleton, secondSingleton); + } +} diff --git a/src/test/java/homework_5_tests/CustomRegexMatcherTest.java b/src/test/java/homework_5_tests/CustomRegexMatcherTest.java new file mode 100644 index 00000000..75ee54a7 --- /dev/null +++ b/src/test/java/homework_5_tests/CustomRegexMatcherTest.java @@ -0,0 +1,61 @@ +package homework_5_tests; + +import base.UnitBase; +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; + +public class CustomRegexMatcherTest extends UnitBase { + + private void run() { + new CustomRegexMatcher().run(); + removeFromOutput("Enter your password: "); + printOut(); + } + + @ParameterizedTest + @MethodSource("testTrueCases") + void givenCorrectPassword_whenRun_thenTrue(String input, String expected) { + setInput(input); + + run(); + + assertEquals(expected, getOutput()); + } + + private static Stream testTrueCases() { + return Stream.of( + Arguments.of("Cheeseburger1!", "Password security: true"), + Arguments.of("21$cheeseburgeR", "Password security: true"), + Arguments.of("2cheese!Burger", "Password security: true") + ); + } + + @ParameterizedTest + @MethodSource("testFalseCases") + void givenIncorrectPassword_whenRun_thenFalse(String input, String expected) { + setInput(input); + + run(); + + assertEquals(expected, getOutput()); + } + + private static Stream testFalseCases() { + return Stream.of( + Arguments.of("cheeseburger1!", "Password must contain uppercase letters."), + Arguments.of("21& cheeseburgeR", "Password must not contain a space."), + Arguments.of("cheeseBurger1", "Password must contain special characters: !, $, %, #, ^"), + Arguments.of(" cheeseBurger21! ", "Password must not contain a space."), + Arguments.of("2!", "Password at least 8 characters long must contain lowercase and uppercase letters, digits and special characters: !, $, %, #, ^.") + ); + } + + + +} diff --git a/src/test/java/homework_5_tests/PowerOfNumberTest.java b/src/test/java/homework_5_tests/PowerOfNumberTest.java new file mode 100644 index 00000000..04d43b91 --- /dev/null +++ b/src/test/java/homework_5_tests/PowerOfNumberTest.java @@ -0,0 +1,58 @@ +package homework_5_tests; + +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 PowerOfNumberTest extends UnitBase { + + private static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; + + private void run() { + new PowerOfNumber().run(); + removeFromOutput("Please enter 2 non-negative numbers:"); + printOut(); + } + + @ParameterizedTest + @MethodSource("testTrueCases") + void givenCorrectPassword_whenRun_thenPrintPower(String input, String expected) { + setInput(input); + + run(); + + assertEquals(expected, getOutput()); + } + + private static Stream testTrueCases() { + return Stream.of( + Arguments.of("2 2", "4"), + Arguments.of("0 2", "0"), + Arguments.of("2 0", "1") + ); + } + + @ParameterizedTest + @MethodSource("testBadInputCases") + void givenIncorrectInput_whenRun_thenErrorMassage(String input, String expected) { + setInput(input); + + run(); + + assertEquals(expected, getOutput()); + } + + private static Stream testBadInputCases() { + return Stream.of( + Arguments.of("1", ERROR_MESSAGE), + Arguments.of("1 2 3", ERROR_MESSAGE), + Arguments.of("one 3", ERROR_MESSAGE) + ); + } +}