diff --git a/README.md b/README.md index 5d686e9f..9b581bcb 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,21 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Konstantin Ivanov* | 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/blob/feature/konstantinIvanov/src/main/java/homework_1/Main.java) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [TrafficLight homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_2/traffic_light/Main.java) | App reads current time in seconds from the console and prints the traffic light | +| HW2 | [Pyramid homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_2/pyramid_printer/Main.java) | The app that reads input argument and builds pyramid base on input value | +| HW2 | [RandomCharsTable homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_2/random_chars_table/Main.java) | App reads from the console width and length of the chart, strategy keyword (even or odd). Prints to the console the chart of random chars from A to Z | +| HW3 | [ImmutableClass homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_3/ImmutableClass.java) | Immutable class | +| HW4 | [Singleton homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_4/Singleton/MySingleton.java) | Singleton | +| HW4 | [CustomFileReader homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_4/custom_file_reader/CustomFileReader.java) | The app that reads from a file using nio io | +| HW4 | [CustomAnnotation homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_4/custom_annotation/test_annotation/Main.java) | The app has three annotation, BeforeSuite, which runs once at the beginning, AfterSuite, which runs once at the end, and Test which runs methods by priority | +| HW5 | [CustomRegexMatcher homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_5/customRegexMatcher/CustomRegexMatcher.java) | The app with customRegexMatcher | +| HW5 | [PowerOfNumber homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_5/powerOfNumber/PowerOfNumber.java) | The app realizes PowerOfNumber method which using recursion | +| HW6 | [MapProblemsGenerator homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_6/MapProblemsCollisionGenerator.java) | The app has two classes, MapProblemsCollisionGenerator which creates 100% collision and MapProblemsMutableGenerator with hashcoreEquals | +| HW7 | [KittenToCatFunction homework](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/konstantinIvanov/src/main/java/homework_7/KittenToCat.java) | This app transform Kitten to Cat | -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) + +[Link to CodingBat](https://codingbat.com/done?user=kostya-ivanov9623@mail.ru&tag=8599662828) diff --git a/src/main/java/course_project/seaBattle/Computer.java b/src/main/java/course_project/seaBattle/Computer.java new file mode 100644 index 00000000..d0b28a2d --- /dev/null +++ b/src/main/java/course_project/seaBattle/Computer.java @@ -0,0 +1,22 @@ +package course_project.seaBattle; + + +import java.util.Arrays; + +import static course_project.seaBattle.Field.*; + +public class Computer { + private String name; + + public String getName() { + return name; + } + + public Computer(String name) { + this.name = name; + for (int i = 0; i < computer_field.length; i++) { + Arrays.fill(computer_field[i], '*'); + Arrays.fill(fake_field[i], '*'); + } + } +} \ No newline at end of file diff --git a/src/main/java/course_project/seaBattle/Field.java b/src/main/java/course_project/seaBattle/Field.java new file mode 100644 index 00000000..d7c8af6c --- /dev/null +++ b/src/main/java/course_project/seaBattle/Field.java @@ -0,0 +1,110 @@ +package course_project.seaBattle; + +import java.util.Random; +import java.util.Scanner; + +public class Field { + public static final int SIZE = 10; + public static char[][] player_field = new char[SIZE][SIZE]; + public static char[][] computer_field = new char[SIZE][SIZE]; + public static char[][] fake_field = new char[SIZE][SIZE]; + public static int playerShip = 20; + public static int computerShip = 20; + + public static void printBattleField(char[][] field) { + for (int i = 0; i < SIZE; i++) { + if (i == 0) { + for (int k = 0; k < SIZE; k++) { + System.out.print("\t" + k); + } + System.out.println(); + } + System.out.print(i); + for (int j = 0; j < SIZE; j++) { + System.out.print("\t" + field[i][j]); + } + System.out.println(); + } + } + + public static void printAllMaps(Player user, course_project.seaBattle.Computer computer) { + System.out.print("\t=========" + user.getName() + "========"); + System.out.println("\t\t\t\t \t=======" + computer.getName() + "======="); + System.out.print(" "); + for (int i = 0; i < SIZE; i++) { + System.out.print(i + " "); + } + System.out.print("\t\t "); + for (int i = 0; i < SIZE; i++) { + System.out.print(i + " "); + } + + System.out.print("\n"); + for (int i = 0; i < 10; i++) { + System.out.print(i + " "); + for (int j = 0; j < 10; j++) { + System.out.print(player_field[i][j] + " "); + } + System.out.print("\t\t"); + System.out.print(i + " "); + for (int k = 0; k < 10; k++) { + System.out.print(computer_field[i][k] + " "); + } + System.out.print("\n"); + } + } + public static void playerShoot(Scanner scanner, char[][] field) { + while (true) { + try { + System.out.println("Print the coordinate x"); + int x = scanner.nextInt(); + System.out.println("Print the coordinate y"); + int y = scanner.nextInt(); + if (field[x][y] == 'X') { + System.out.println("GOAL"); + System.out.println("Nice shot"); + field[x][y] = '@'; + fake_field[x][y] = '@'; + computerShip--; + printBattleField(fake_field); + if (computerShip == 0) { + return; + } + } else { + System.out.println("You missed"); + field[x][y] = '-'; + fake_field[x][y] = '-'; + printBattleField(fake_field); + return; + } + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("You can use number from 0 to 9"); + break; + } catch (Exception e) { + throw new RuntimeException("Error, you must use only number"); + } + } + } + public static void computerShoot(char[][] field, Random random) { + while (true) { + int x = random.nextInt(10); + int y = random.nextInt(10); + if (field[x][y] == 'X') { + System.out.println("Computer shot your ship"); + field[x][y] = '@'; + playerShip--; + printBattleField(player_field); + if (playerShip == 0) { + return; + } + } else if (field[x][y] == '@' || field[x][y] == '-') { + + } else { + System.out.println("Computer missed"); + field[x][y] = '-'; + printBattleField(player_field); + return; + } + } + } +} diff --git a/src/main/java/course_project/seaBattle/Game.java b/src/main/java/course_project/seaBattle/Game.java new file mode 100644 index 00000000..8b2fd33f --- /dev/null +++ b/src/main/java/course_project/seaBattle/Game.java @@ -0,0 +1,43 @@ +package course_project.seaBattle; + + +import java.util.Random; +import java.util.Scanner; + +import static course_project.seaBattle.Field.*; +import static course_project.seaBattle.Field.computerShip; +import static course_project.seaBattle.Ship.*; + +public class Game { + Scanner scanner = new Scanner(System.in); + Random rand = new Random(); + + public static boolean checkWin(int playerShip, int computerShip) { + if (playerShip == 0) { + System.out.println("Computer win -_-"); + return false; + } else if (computerShip == 0) { + System.out.println("You win!!"); + return false; + } else { + return true; + } + } + + public void run() { + System.out.println("Print your name"); + Player User = new Player(scanner.nextLine()); + course_project.seaBattle.Computer computer = new course_project.seaBattle.Computer("Computer"); + randomGenerateShip(player_field, rand); + printAllMaps(User, computer); + randomGenerateShip(computer_field, rand); + System.out.println("Start game"); + do { + playerShoot(scanner, computer_field); + computerShoot(player_field, rand); + } + while (checkWin(playerShip, computerShip)); + System.out.println(" End "); + System.out.println("if you like this game you can buy it for three hundred bucks"); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/seaBattle/Main.java b/src/main/java/course_project/seaBattle/Main.java new file mode 100644 index 00000000..7921918a --- /dev/null +++ b/src/main/java/course_project/seaBattle/Main.java @@ -0,0 +1,8 @@ +package course_project.seaBattle; + +public class Main { + + public static void main(String[] args) { + new Game().run(); + } +} diff --git a/src/main/java/course_project/seaBattle/Player.java b/src/main/java/course_project/seaBattle/Player.java new file mode 100644 index 00000000..d3f66aa9 --- /dev/null +++ b/src/main/java/course_project/seaBattle/Player.java @@ -0,0 +1,20 @@ +package course_project.seaBattle; + + +import java.util.Arrays; + +import static course_project.seaBattle.Field.*; + +public class Player { + private String name; + public String getName() { + return name; + } + + public Player(String name) { + this.name = name; + for (int i = 0; i < player_field.length; i++) { + Arrays.fill(player_field[i], '*'); + } + } +} \ No newline at end of file diff --git a/src/main/java/course_project/seaBattle/Ship.java b/src/main/java/course_project/seaBattle/Ship.java new file mode 100644 index 00000000..926e71a1 --- /dev/null +++ b/src/main/java/course_project/seaBattle/Ship.java @@ -0,0 +1,73 @@ +package course_project.seaBattle; + + +import java.util.Random; + +import static course_project.seaBattle.Field.SIZE; + +public class Ship { + int positionY; + int positionX; + int size; + boolean isVertical; + int health; + public static Ship[] ships = new Ship[10]; + + public Ship(int positionX, int positionY, int size, boolean isVertical) { + this.positionX = positionX; + this.positionY = positionY; + this.size = size; + this.isVertical = isVertical; + this.health = size; + } + + public static void randomGenerateShip(char[][] field, Random rand) { + for (int i = 0; i < 10; i++) { + boolean isShipPlaced = false; + do { + if (i == 0) ships[i] = new Ship(rand.nextInt(10), rand.nextInt(10), 4, rand.nextBoolean()); + if (i > 0 && i <= 2) + ships[i] = new Ship(rand.nextInt(10), rand.nextInt(10), 3, rand.nextBoolean()); + if (i > 2 && i <= 5) + ships[i] = new Ship(rand.nextInt(10), rand.nextInt(10), 2, rand.nextBoolean()); + if (i > 5) ships[i] = new Ship(rand.nextInt(10), rand.nextInt(10), 1, rand.nextBoolean()); + if (canSetShip(ships[i], field)) { + setShipOnField(ships[i], field); + isShipPlaced = true; + } + } while (!isShipPlaced); + } + } + private static void setShipOnField(Ship ship, char[][] field) { + if (ship.isVertical) { + for (int i = 0; i < ship.size; i++) { + field[ship.positionX][ship.positionY + i] = 'X'; + } + } else { + for (int i = 0; i < ship.size; i++) { + field[ship.positionX + i][ship.positionY] = 'X'; + } + } + } + + private static boolean canSetShip(Ship ship, char[][] field) { + if (ship.positionX < 0 || ship.positionY < 0 || SIZE <= ship.positionX || SIZE <= ship.positionY) + return false; + if (ship.isVertical && SIZE <= ship.positionY + ship.size) return false; + if (!ship.isVertical && SIZE <= ship.positionX + ship.size) return false; + int minX = Math.max(0, ship.positionX - 1); + int minY = Math.max(0, ship.positionY - 1); + int maxX = Math.min(SIZE - 1, ship.positionX + 1 + (ship.isVertical ? 0 : ship.size)); + int maxY = Math.min(SIZE - 1, ship.positionY + 1 + (ship.isVertical ? ship.size : 0)); + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + if (isShipPresent(x, y, field)) return false; + } + } + return true; + } + + private static boolean isShipPresent(int x, int y, char[][] field) { + return field[x][y] == 'X'; + } +} \ No newline at end of file diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..d59dd244 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -2,8 +2,18 @@ public class Main { - public static void main(String[] args) { - System.out.println("Hello homework!"); - } + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_RESET = "\u001B[0m"; + + public static void main(String[] args) { + for (String s : args) { + if (s.equals("error")) { + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); + break; + } else { + System.out.println(s + ": " + s.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..8c13fde3 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,10 @@ +package homework_2.pyramid_printer; + +import java.io.IOException; + +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..4a9ea67b --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,35 @@ +package homework_2.pyramid_printer; + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PyramidPrinter { + + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + int rows = Integer.parseInt(reader.readLine()); + if (rows<0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + return; + } + printPyramid(rows); + } catch (IOException e) { + e.printStackTrace(); + return; + } catch (NumberFormatException e){ + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + return; + } + } + + static void printPyramid(int rows){ + for (int i = 1; i <= rows; i++) { + for (int j = 0; 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..4e445173 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,10 @@ +package homework_2.random_chars_table; + +import java.io.IOException; + +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..ba898e3d --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,79 @@ +package homework_2.random_chars_table; + + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class RandomCharsTable { + private static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + + private static void printResult(int length, int width, char arr[][], String strategy, String res) { + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + System.out.print("|" + arr[i][j]); + } + System.out.print("|"); + System.out.println(); + } + if (strategy.equals("even")) { + System.out.println("Even letters -" + res.substring(0, res.length() - 1)); + } else System.out.println("Odd letters -" + res.substring(0, res.length() - 1)); + } + + public void run() { + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + + try { + String str = reader.readLine(); + String array[] = str.split(" "); + int length = Integer.parseInt(array[0]); + int width = Integer.parseInt(array[1]); + if (length<=0||width<=0) { + System.out.println(ERROR_MESSAGE); + return; + } + String strategy = array[2]; + if (strategy.equals("odd") || strategy.equals("even")) { + char[][] arr = new char[length][width]; + String res = ""; + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + double x = (Math.random() * ((90 - 65) + 1)) + 65; + int check = (int) x; + char result = (char) x; + arr[i][j] = result; + if (strategy.equals("even")) { + if (check % 2 == 0) { + res += " " + (char) check + ","; + } + } else { + if (check % 2 != 0) { + res += " " + (char) check + ","; + } + } + } + } + printResult(length, width, arr, strategy, res); + } else { + System.out.println(ERROR_MESSAGE); + return; + } + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println(ERROR_MESSAGE); + return; + } catch (IOException e) { + e.printStackTrace(); + }catch (Exception e) { + System.out.println(ERROR_MESSAGE); + return; + } finally { + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} 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..bbc08d3f --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,10 @@ +package homework_2.traffic_light; + +import java.io.IOException; + +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..e42ab50b --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,37 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + public void run() { + + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + String str; + try { + str = reader.readLine(); + int time = Integer.parseInt(str); + if (time < 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter "); + } else if (time > 86399) { + System.out.println("The day is over"); + } else { + int light = time % 60; + if (light < 35) { + System.out.println("GREEN"); + } else if (light < 40) { + System.out.println("YELLOW"); + } else if (light < 55) { + System.out.println("RED"); + } else { + System.out.println("YELLOW"); + } + } + } catch (NumberFormatException | IOException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + } +} + diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..1e2c40ac --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,56 @@ +package homework_3; + +import java.util.ArrayList; +import java.util.List; +/* +no setters methods +make variables private and final +make class final +A parameterized constructor should initialize all the fields performing a deep copy +Deep Copy of objects should be performed in the getter methods +*/public final class ImmutableClass { + + private final int someInt; + private final String someString; + private final Character someChar; + private final String[] names; + + public ImmutableClass(int someInt, String someString, Character someChar, String[] names) { + this.someInt = someInt; + this.someString = someString; + this.someChar = someChar; + this.names = names; + } + + public int getSomeInt() { + return someInt; + } + + public String getSomeString() { + return someString; + } + + public Character getSomeChar() { + return someChar; + } + + public String[] getNames() { + return names.clone(); + } + + public ImmutableClass getImmutableClass(int someInt) { + return new ImmutableClass(getSomeInt(),getSomeString(),getSomeChar(), getNames()); + } + + public ImmutableClass getImmutableClass(Character cshar) { + if (someChar != null) { + return new ImmutableClass(getSomeInt(),getSomeString(), cshar, getNames()); + } else return new ImmutableClass(getSomeInt(),getSomeString(),getSomeChar(), getNames()); + } + + public ImmutableClass getImmutableClass(String[] str) { + if (str != null) { + return new ImmutableClass(getSomeInt(),getSomeString(),getSomeChar(), str); + } else return new ImmutableClass(getSomeInt(),getSomeString(),getSomeChar(), getNames()); + } +} \ No newline at end of file diff --git a/src/main/java/homework_4/Singleton/MySingleton.java b/src/main/java/homework_4/Singleton/MySingleton.java new file mode 100644 index 00000000..835fa939 --- /dev/null +++ b/src/main/java/homework_4/Singleton/MySingleton.java @@ -0,0 +1,17 @@ +package homework_4.Singleton; + +public class MySingleton { + private static MySingleton singleton; + + private MySingleton() { + + } + + public synchronized static MySingleton getInstance() { + if (singleton == null) { + singleton = new MySingleton(); + } + return singleton; + } + +} diff --git a/src/main/java/homework_4/custom_annotation/db_annotation/Main.java b/src/main/java/homework_4/custom_annotation/db_annotation/Main.java new file mode 100644 index 00000000..ba777d9f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/db_annotation/Main.java @@ -0,0 +1,113 @@ +package homework_4.custom_annotation.db_annotation; + +import java.lang.reflect.Field; +import java.sql.*; +import java.util.HashMap; + +public class Main { + + public static String DB_URL = "jdbc:mysql://localhost:3306/DB_NAME"; + public static String User = ""; + public static String password = ""; + + private static Connection connection; + private static Statement statement; + + public static void main(String[] args) { + prepareTable(Student.class); + Student student = new Student(1, "kostya", 25, "kostya@gmail.com"); + saveObject(student); + } + + public static void prepareTable(Class myClass) { + if (!myClass.isAnnotationPresent(XTable.class)) throw new IllegalArgumentException(); + HashMap hashMap = new HashMap<>(); + hashMap.put(int.class, "INTEGER"); + hashMap.put(String.class, "VARCHAR(255)"); + try { + connection(); + String tableName = myClass.getAnnotation(XTable.class).name(); + statement.executeUpdate("DROP TABLE IF EXISTS " + tableName + ";"); + String createTable = "CREATE TABLE " + tableName + " ("; + Field[] fields = myClass.getDeclaredFields(); + for (Field field : fields) { + if (field.isAnnotationPresent(XField.class)) { + createTable += field.getName() + " " + hashMap.get(field.getType()) + ", "; + } + } + createTable = createTable.substring(0, createTable.length() - 2); + createTable += ");"; + statement.executeUpdate(createTable); + } catch (SQLException e) { + e.printStackTrace(); + } finally { + disconnect(); + } + } + + public static void saveObject(Object object) { + Class c = object.getClass(); + if (!c.isAnnotationPresent(XTable.class)) throw new IllegalArgumentException(); + try { + connection(); + String tableName = ((XTable) c.getAnnotation(XTable.class)).name(); + String insertQuery = "INSERT INTO " + tableName + " ("; + Field[] fields = c.getDeclaredFields(); + for (Field field : fields) { + if (field.isAnnotationPresent(XField.class)) { + insertQuery += field.getName() + ", "; + } + } + insertQuery = insertQuery.substring(0, insertQuery.length() - 2); + insertQuery += ") VALUES ("; + for (Field field : fields) { + if (field.isAnnotationPresent(XField.class)) { + insertQuery += "?, "; + } + } + insertQuery = insertQuery.substring(0, insertQuery.length() - 2); + insertQuery += ");"; + PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); + int counter = 1; + for (Field field : fields) { + if (field.isAnnotationPresent(XField.class)) { + preparedStatement.setObject(counter, field.get(object)); + counter++; + } + } + preparedStatement.executeUpdate(); + } catch (SQLException | IllegalAccessException e) { + e.printStackTrace(); + } finally { + disconnect(); + } + } + + public static void connection() throws SQLException { + connection = DriverManager.getConnection(DB_URL, User, password); + statement = connection.createStatement(); + } + + public static void disconnect() { + if (connection != null) { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } +} +/* +CREATE TABLE students { +id INTEGER, +name VARCHAR(255), +score INTEGER, +mail VARCHAR(255) +}; + */ +/* +INSERT INTO students( +id, name , score , mail) +VALUES (?, ?, ? , ?); + */ diff --git a/src/main/java/homework_4/custom_annotation/db_annotation/Student.java b/src/main/java/homework_4/custom_annotation/db_annotation/Student.java new file mode 100644 index 00000000..131b9aab --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/db_annotation/Student.java @@ -0,0 +1,21 @@ +package homework_4.custom_annotation.db_annotation; + +@XTable(name = "students") +public class Student { + @XField + public int id; + @XField + public String name; + @XField + public int score; + @XField + public String mail; + + public Student(int id, String name, int score, String mail) { + this.id = id; + this.name = name; + this.score = score; + this.mail = mail; + } +} + diff --git a/src/main/java/homework_4/custom_annotation/db_annotation/XField.java b/src/main/java/homework_4/custom_annotation/db_annotation/XField.java new file mode 100644 index 00000000..742b50f6 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/db_annotation/XField.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation.db_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface XField { + +} diff --git a/src/main/java/homework_4/custom_annotation/db_annotation/XTable.java b/src/main/java/homework_4/custom_annotation/db_annotation/XTable.java new file mode 100644 index 00000000..2e9eae2a --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/db_annotation/XTable.java @@ -0,0 +1,13 @@ +package homework_4.custom_annotation.db_annotation; + + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface XTable { + String name(); +} diff --git a/src/main/java/homework_4/custom_annotation/test_annotation/AfterSuite.java b/src/main/java/homework_4/custom_annotation/test_annotation/AfterSuite.java new file mode 100644 index 00000000..015dd8ce --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/test_annotation/AfterSuite.java @@ -0,0 +1,11 @@ +package homework_4.custom_annotation.test_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface AfterSuite { +} diff --git a/src/main/java/homework_4/custom_annotation/test_annotation/BeforeSuite.java b/src/main/java/homework_4/custom_annotation/test_annotation/BeforeSuite.java new file mode 100644 index 00000000..30a0e8f3 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/test_annotation/BeforeSuite.java @@ -0,0 +1,11 @@ +package homework_4.custom_annotation.test_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface BeforeSuite { +} diff --git a/src/main/java/homework_4/custom_annotation/test_annotation/Main.java b/src/main/java/homework_4/custom_annotation/test_annotation/Main.java new file mode 100644 index 00000000..ee1f1eec --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/test_annotation/Main.java @@ -0,0 +1,72 @@ +package homework_4.custom_annotation.test_annotation; + + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; + +public class Main { + public static void main(String[] args) { + // new Main().start(); + } + + public void start() { + Class c = TestClass.class; + Method method[] = c.getDeclaredMethods(); + ArrayList arrayList = new ArrayList<>(); + Object testObj = null; + try { + testObj = c.newInstance(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + Method beforeMethod = null; + Method afterMethod = null; + for (Method method1 : method) { + if (method1.isAnnotationPresent(TestAnnotation.class)) { + arrayList.add(method1); + } + if (method1.isAnnotationPresent(BeforeSuite.class)) { + if (beforeMethod == null) { + beforeMethod = method1; + } else throw new RuntimeException("Method beforeSuite can be only one"); + } + if (method1.isAnnotationPresent(AfterSuite.class)) { + if (afterMethod == null) { + afterMethod = method1; + } else throw new RuntimeException("Method afterSuite can be only one"); + } + } + arrayList.sort((o1, o2) -> o2.getAnnotation(TestAnnotation.class).priority() - o1.getAnnotation(TestAnnotation.class).priority()); + if (beforeMethod != null) { + try { + beforeMethod.invoke(testObj, null); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + for (Method o : arrayList) { + try { + o.invoke(testObj, null); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + if (afterMethod != null) { + try { + afterMethod.invoke(testObj, null); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + } +} + diff --git a/src/main/java/homework_4/custom_annotation/test_annotation/TestAnnotation.java b/src/main/java/homework_4/custom_annotation/test_annotation/TestAnnotation.java new file mode 100644 index 00000000..cf827892 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/test_annotation/TestAnnotation.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation.test_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface TestAnnotation { + int priority() default 3; +} diff --git a/src/main/java/homework_4/custom_annotation/test_annotation/TestClass.java b/src/main/java/homework_4/custom_annotation/test_annotation/TestClass.java new file mode 100644 index 00000000..656ef340 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/test_annotation/TestClass.java @@ -0,0 +1,33 @@ +package homework_4.custom_annotation.test_annotation; + +public class TestClass { + @BeforeSuite + public void init() { + System.out.println("@BeforeSuite"); + } + + @TestAnnotation(priority = 4) + public void test1() { + System.out.println("test with priority 4"); + } + + @TestAnnotation(priority = 1) + public void test2() { + System.out.println("test with priority 1"); + } + + @TestAnnotation(priority = 5) + public void test3() { + System.out.println("test with priority 5"); + } + + @TestAnnotation(priority = 2) + public void test4() { + System.out.println("test with priority 2"); + } + + @AfterSuite + public void end() { + System.out.println("@AfterSuite"); + } +} 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..665b3c99 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,85 @@ +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; +import java.util.Scanner; + +import static java.nio.charset.StandardCharsets.UTF_8; + +public class CustomFileReader { + + private String message; + private File file; + private String filePath = "src/main/resources/custom_file_reader/text.txt"; + + public void run1() { + if (isFilePathExist(filePath)) { + file = new File(filePath); + Scanner scanner = null; + try { + scanner = new Scanner(file); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + while (scanner.hasNextLine()) { + message = scanner.nextLine(); + printResult(); + } + } else { + printErrorMessage(); + } + } + public void run2() { + if (isFilePathExist(filePath)) { + file = new File(filePath); + BufferedReader reader = null; + try { + reader = new BufferedReader(new FileReader(file)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + while (true) { + try { + if (!reader.ready()) break; + } catch (IOException e) { + e.printStackTrace(); + } + try { + message = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + printResult(); + } + } + } + + public void run3() { + Path file = Paths.get(filePath); + List lines = null; + try { + lines = Files.readAllLines(Paths.get(filePath), UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + lines.stream().filter(s -> s.contains(",") || s.contains(".")) + .map(s -> s.replaceAll("(\\.)|(,)", "")) + .forEach(System.out::println); + } + + + private void printErrorMessage() { + System.out.println("Error"); + } + + private boolean isFilePathExist(String filePath) { + return new File(filePath).exists(); + } + + private void printResult() { + System.out.println(message.replaceAll("(\\.)|(,)", "")); + } +} 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..45b02f8d --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,15 @@ +package homework_4.custom_file_reader; + +import java.io.File; +import java.io.IOException; + +public class Main { + + public static void main(String[] args) throws IOException { + File file = new File("src/main/resources/custom_file_reader/text.txt"); + file.createNewFile(); + new CustomFileReader().run1(); + new CustomFileReader().run2(); + new CustomFileReader().run3(); + } +} diff --git a/src/main/java/homework_5/customRegexMatcher/CustomRegexMatcher.java b/src/main/java/homework_5/customRegexMatcher/CustomRegexMatcher.java new file mode 100644 index 00000000..89fb13c4 --- /dev/null +++ b/src/main/java/homework_5/customRegexMatcher/CustomRegexMatcher.java @@ -0,0 +1,19 @@ +package homework_5.customRegexMatcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CustomRegexMatcher { + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + String message = reader.readLine(); + System.out.println(checkMail(message)); + } catch (IOException e) { + e.printStackTrace(); + } + } + public static boolean checkMail(String str) { + return str.matches("[0-9a-zA-Z_-]{5,}\\d*@\\w{2,}\\.\\w{2,}"); + } +} diff --git a/src/main/java/homework_5/customRegexMatcher/Main.java b/src/main/java/homework_5/customRegexMatcher/Main.java new file mode 100644 index 00000000..6524c6ed --- /dev/null +++ b/src/main/java/homework_5/customRegexMatcher/Main.java @@ -0,0 +1,8 @@ +package homework_5.customRegexMatcher; + +public class Main { + + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} diff --git a/src/main/java/homework_5/powerOfNumber/Main.java b/src/main/java/homework_5/powerOfNumber/Main.java new file mode 100644 index 00000000..62aabd55 --- /dev/null +++ b/src/main/java/homework_5/powerOfNumber/Main.java @@ -0,0 +1,9 @@ +package homework_5.powerOfNumber; + +public class Main { + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} + + diff --git a/src/main/java/homework_5/powerOfNumber/PowerOfNumber.java b/src/main/java/homework_5/powerOfNumber/PowerOfNumber.java new file mode 100644 index 00000000..0d90b1f0 --- /dev/null +++ b/src/main/java/homework_5/powerOfNumber/PowerOfNumber.java @@ -0,0 +1,32 @@ +package homework_5.powerOfNumber; + +import java.util.Scanner; + +public class PowerOfNumber { + public void run() { + Scanner scanner = new Scanner(System.in); + try { + int fir = scanner.nextInt(); + int sec = scanner.nextInt(); + PowerOfNumber power = new PowerOfNumber(); + int result = power.rec(fir, sec); + System.out.println(result); + } catch (Exception e) { + System.out.println("Only 2 non-negative integers are allowed"); + } finally { + scanner.close(); + } + } + public int rec(int firstNumber, int secondNumber) { + if (firstNumber < 0 || secondNumber < 0) { + throw new RuntimeException("Only 2 non-negative integers are allowed"); + } + if (secondNumber == 0) { + return 1; + } + if (secondNumber > 0 ) { + return firstNumber * rec(firstNumber, secondNumber-1); + } + return rec(firstNumber, secondNumber) * secondNumber; + } +} \ No newline at end of file diff --git a/src/main/java/homework_6/Main.java b/src/main/java/homework_6/Main.java new file mode 100644 index 00000000..fef24520 --- /dev/null +++ b/src/main/java/homework_6/Main.java @@ -0,0 +1,17 @@ +package homework_6; + +import java.util.HashMap; + +public class Main { + + public static void main(String[] args) { + HashMap myMap = new HashMap<>(); + MapProblemsMutableGenerator mutab = new MapProblemsMutableGenerator(1); + + myMap.put(mutab, 100); + System.out.println(myMap.get(mutab)); + + mutab.setId(3); + System.out.println(myMap.get(mutab)); + } +} diff --git a/src/main/java/homework_6/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..3ebd0c86 --- /dev/null +++ b/src/main/java/homework_6/MapProblemsCollisionGenerator.java @@ -0,0 +1,31 @@ +package homework_6; + + +public class MapProblemsCollisionGenerator { + + private final int id; + private final String name; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsCollisionGenerator that = (MapProblemsCollisionGenerator) o; + return id == that.id; + } + + @Override + public int hashCode() { + return 1; + } + + + public String getName() { + return name; + } + + public MapProblemsCollisionGenerator(int id, String name) { + this.id = id; + this.name = name; + } +} diff --git a/src/main/java/homework_6/MapProblemsMutableGenerator.java b/src/main/java/homework_6/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..f5bcfbe9 --- /dev/null +++ b/src/main/java/homework_6/MapProblemsMutableGenerator.java @@ -0,0 +1,42 @@ +package homework_6; + +import java.util.Objects; + +public class MapProblemsMutableGenerator { + + private int id; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return id == that.id; + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + + + public MapProblemsMutableGenerator(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public String toString() { + return "MapProblemsMutableGenerator{" + + "id=" + id + + '}'; + } +} diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..8c9c8c51 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,34 @@ +package homework_7; + +public class Cat { + private String name; + private int age; + private double tail_length; + + public Cat(String name, int age, double tail_length) { + this.name = name; + this.age = age; + this.tail_length = tail_length; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + ", tail_length=" + tail_length + + '}'; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public double getTail_length() { + return tail_length; + } +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..9b3417ee --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,38 @@ +package homework_7; + +public class Kitten { + private String name; + private int age; + private double tail_length; + + public Kitten(String name, int age, double tail_length) { + this.name = name; + this.age = age; + this.tail_length = tail_length; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public double getTail_length() { + return tail_length; + } + + @Override + public String toString() { + return "Kitten{" + + "name='" + name + '\'' + + ", age=" + age + + ", tail_length=" + tail_length + + '}'; + } + + public Cat changeKittenToCat(KittenToCat kittenToCat) { + return kittenToCat.trasfom(this); + } +} diff --git a/src/main/java/homework_7/KittenToCat.java b/src/main/java/homework_7/KittenToCat.java new file mode 100644 index 00000000..645d0325 --- /dev/null +++ b/src/main/java/homework_7/KittenToCat.java @@ -0,0 +1,5 @@ +package homework_7; +@FunctionalInterface +public interface KittenToCat { + Cat trasfom(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..9ad8ca2b --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,12 @@ +package homework_7; + +public class Main { + + public static void main(String[] args) { + Kitten kitten = new Kitten("murzik", 1, 1.0 ); + Kitten kitten1 = new Kitten("sadCat", 12, 2.3); + Cat cat = kitten.changeKittenToCat(kit -> new Cat (kitten.getName(), kitten.getAge()*5, kitten.getTail_length()*2)); + Cat cat2 = kitten.changeKittenToCat(kit -> new Cat (kitten1.getName(), kitten1.getAge()*5, kitten1.getTail_length()*2)); + System.out.println(cat); + } +} diff --git a/src/main/resources/custom_file_reader/text.txt b/src/main/resources/custom_file_reader/text.txt new file mode 100644 index 00000000..f8369461 --- /dev/null +++ b/src/main/resources/custom_file_reader/text.txt @@ -0,0 +1,3 @@ +This, text. should be, output. to the console. +without, commas. and, +without, dots. \ No newline at end of file diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 97e2685b..3df30c70 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -1,73 +1,74 @@ package base; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; +import homework_2.pyramid_printer.PyramidPrinter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; public abstract class UnitBase { - protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - protected final PrintStream originalOut = System.out; - protected final InputStream originalIn = System.in; + protected final PrintStream originalOut = System.out; + protected final InputStream originalIn = System.in; + protected ByteArrayOutputStream mockedOut = new ByteArrayOutputStream(); - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(mockedOut)); - } + @BeforeEach + void setUpStreams() { + System.setOut(new PrintStream(mockedOut)); + } - @AfterEach - void restoreStreams() { - System.setOut(originalOut); - System.setIn(originalIn); - } + @AfterEach + void restoreStreams() { + System.setOut(originalOut); + System.setIn(originalIn); + } - // mock input as if you wrote it to console by hand - protected void setInput(String input) { - System.setIn(new ByteArrayInputStream(input.getBytes())); - } + // mock input as if you wrote it to console by hand + protected void setInput(String input) { + System.setIn(new ByteArrayInputStream(input.getBytes())); + } - // returns whole output as string, will all line separators and etc - protected String getOutput() { - return mockedOut.toString().trim(); - } + // returns whole output as string, will all line separators and etc + protected String getOutput() { + return mockedOut.toString().trim(); + } + + // output as array, separated by lines. First line - getOutputLines()[0], and so on + protected String[] getOutputLines() { + return getOutput().split("\\r?\\n"); + } - // output as array, separated by lines. First line - getOutputLines()[0], and so on - protected String[] getOutputLines() { - return getOutput().split("\\r?\\n"); - } + // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() + protected void removeFromOutput(String s) { + try { + String output = mockedOut.toString(); + mockedOut.reset(); + mockedOut.write(output.replace(s, "").getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } - // can be used to remove some strings from output (ex. remove "Please input number"). Put after run() - protected void removeFromOutput(String s) { - try { - String output = mockedOut.toString(); - mockedOut.reset(); - mockedOut.write(output.replace(s, "").getBytes()); - } catch (IOException e) { - e.printStackTrace(); + // can be used to print output to testing console. Useful for debugging. Put after run(); + protected void printOut() { + System.setOut(originalOut); + System.out.println(mockedOut); + System.setOut(new PrintStream(mockedOut)); } - } +/* + @Test + void example() throws IOException { + setInput("2"); - // can be used to print output to testing console. Useful for debugging. Put after run(); - protected void printOut() { - System.setOut(originalOut); - System.out.println(mockedOut); - System.setOut(new PrintStream(mockedOut)); - } + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Please input number"); -// @Test -// void example() { -// setInput("2"); -// -// new PyramidPrinter().run(); -// printOut(); -// removeFromOutput("Please input number"): -// -// assertEquals("x", getOutputLines()[0]); -// assertEquals("xx", getOutputLines()[1]); -// } + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + }*/ } diff --git a/src/test/java/course_project/Main.java b/src/test/java/course_project/Main.java new file mode 100644 index 00000000..2a92e8d8 --- /dev/null +++ b/src/test/java/course_project/Main.java @@ -0,0 +1,32 @@ +package course_project; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + + +import static course_project.seaBattle.Game.checkWin; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class Main extends UnitBase { + + @Test + public void testChechWinMethod1() { + assertTrue(checkWin(20,20)); + } + @Test + public void testChechWinMethod2() { + assertFalse(checkWin(0,0)); + } + @Test + public void testChechWinMethod3() { + assertTrue(checkWin(10,3)); + } + + @Test + public void testChechWinMethod4() { + assertFalse(checkWin(0,3)); + } + +} diff --git a/src/test/java/homework_2/PyramidPrinterTest.java b/src/test/java/homework_2/PyramidPrinterTest.java new file mode 100644 index 00000000..1232072e --- /dev/null +++ b/src/test/java/homework_2/PyramidPrinterTest.java @@ -0,0 +1,70 @@ +package homework_2; + +import base.UnitBase; +import homework_2.pyramid_printer.PyramidPrinter; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + + +public class PyramidPrinterTest extends UnitBase { + + @Test + public void testPyramidWithOneArg() { + setInput("1"); + new PyramidPrinter().run(); + printOut(); + assertEquals("x", getOutputLines()[0]); + } + + @Test + void InputZeroAsArgument() { + setInput("0"); + new PyramidPrinter().run(); + printOut(); + assertEquals("", getOutputLines()[0]); + } + + @Test + public void testPyramidWithTwoArg() { + setInput("2"); + new PyramidPrinter().run(); + printOut(); + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + } + + @Test + public void testPyramidWithStringArg() { + setInput("String"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Введите данные:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + public void testPyramidWithNegativeNumberArg() { + setInput("-2"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Введите данные:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + @Test + public void testPyramidWithDoubleArg() { + setInput("2.0"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Введите данные:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + @Test + public void testPyramidWithoutArg() { + setInput(""); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Введите данные:"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + +} diff --git a/src/test/java/homework_2/RandomCharsTableTest.java b/src/test/java/homework_2/RandomCharsTableTest.java new file mode 100644 index 00000000..8968eaf6 --- /dev/null +++ b/src/test/java/homework_2/RandomCharsTableTest.java @@ -0,0 +1,39 @@ +package homework_2; + +import base.UnitBase; +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.assertThrows; + +public class RandomCharsTableTest extends UnitBase { + @Test + public void testOnZeroArg() { + setInput("0 0 even"); + new RandomCharsTable().run(); + printOut(); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutputLines()[0]); + } + @Test + public void testOnEvenOrOddArg() { + setInput("3 2 notEven"); + new RandomCharsTable().run(); + printOut(); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutputLines()[0]); + } + @Test + public void testOnEmptyArg() { + setInput(""); + new RandomCharsTable().run(); + + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutputLines()[0]); + } + @Test + public void testOnNegativeArg() { + setInput("-10 -6 even"); + new RandomCharsTable().run(); + printOut(); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutputLines()[0]); + } + +} diff --git a/src/test/java/homework_2/TrafficLightTest.java b/src/test/java/homework_2/TrafficLightTest.java new file mode 100644 index 00000000..3ea731a4 --- /dev/null +++ b/src/test/java/homework_2/TrafficLightTest.java @@ -0,0 +1,63 @@ +package homework_2; + +import base.UnitBase; +import homework_2.traffic_light.TrafficLight; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightTest extends UnitBase { + + @Test + public void trafficTestOnGreenColor() { + setInput("3"); + new TrafficLight().run(); + printOut(); + assertEquals("GREEN", getOutputLines()[0]); + } + + @Test + public void trafficTestOnYellowColor() { + setInput("36"); + new TrafficLight().run(); + printOut(); + assertEquals("YELLOW", getOutputLines()[0]); + } + + @Test + public void trafficTestOnRedColor() { + setInput("43"); + new TrafficLight().run(); + printOut(); + assertEquals("RED", getOutputLines()[0]); + } + + @Test + public void trafficTestOnString() { + setInput("Str"); + new TrafficLight().run(); + printOut(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + @Test + public void trafficTestOnNegativeNumber() { + setInput("-5"); + new TrafficLight().run(); + printOut(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + @Test + public void trafficTestOnBigNumber() { + setInput("86999"); + new TrafficLight().run(); + printOut(); + assertEquals("The day is over", getOutputLines()[0]); + } + @Test + public void trafficTestOnDouble() { + setInput("3.0"); + new TrafficLight().run(); + printOut(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } +} diff --git a/src/test/java/homework_4/CustomAnnotationTest.java b/src/test/java/homework_4/CustomAnnotationTest.java new file mode 100644 index 00000000..7a207a1d --- /dev/null +++ b/src/test/java/homework_4/CustomAnnotationTest.java @@ -0,0 +1,42 @@ +package homework_4; + +import base.UnitBase; +import homework_4.custom_annotation.test_annotation.Main; +import org.junit.jupiter.api.Test; + + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomAnnotationTest extends UnitBase { + @Test + public void beforeSuiteTest() { + new Main().start(); + assertEquals("@BeforeSuite", getOutputLines()[0]); + } + @Test + public void testPriority() { + new Main().start(); + assertEquals("test with priority 5", getOutputLines()[1]); + } + @Test + public void testPriority1() { + new Main().start(); + assertEquals("test with priority 4", getOutputLines()[2]); + } + @Test + public void testPriority2() { + new Main().start(); + assertEquals("test with priority 2", getOutputLines()[3]); + } + @Test + public void testPriority3() { + new Main().start(); + assertEquals("test with priority 1", getOutputLines()[4]); + } + @Test + public void testPriority4() { + new Main().start(); + assertEquals("@AfterSuite", getOutputLines()[5]); + } + +} diff --git a/src/test/java/homework_4/CustomFileReaderTest.java b/src/test/java/homework_4/CustomFileReaderTest.java new file mode 100644 index 00000000..01d3a11b --- /dev/null +++ b/src/test/java/homework_4/CustomFileReaderTest.java @@ -0,0 +1,34 @@ +package homework_4; + +import base.UnitBase; +import homework_4.custom_file_reader.CustomFileReader; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + + + +public class CustomFileReaderTest extends UnitBase { + + private boolean checkResult(String res) { + return !(res.contains(".") && res.contains(",")); + } + @Test + public void givenTextWhenRun1ThenExpected() { + new CustomFileReader().run1(); + String text = getOutput(); + assertTrue(checkResult(text)); + } + @Test + public void givenTextWhenRun2ThenExpected() { + new CustomFileReader().run2(); + String text = getOutput(); + assertTrue(checkResult(text)); + } + @Test + public void givenTextWhenRun3ThenExpected() { + new CustomFileReader().run3(); + String text = getOutput(); + assertTrue(checkResult(text)); + } + +} diff --git a/src/test/java/homework_4/SingletonTest.java b/src/test/java/homework_4/SingletonTest.java new file mode 100644 index 00000000..af5aca4d --- /dev/null +++ b/src/test/java/homework_4/SingletonTest.java @@ -0,0 +1,15 @@ +package homework_4; + +import homework_4.Singleton.MySingleton; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertSame; + +public class SingletonTest { + @Test + public void testSingleton() { + MySingleton expected = MySingleton.getInstance(); + MySingleton actual = MySingleton.getInstance(); + assertSame(expected, actual); + } +} diff --git a/src/test/java/homework_5/CustomRegexMatcherTest.java b/src/test/java/homework_5/CustomRegexMatcherTest.java new file mode 100644 index 00000000..f738d4d0 --- /dev/null +++ b/src/test/java/homework_5/CustomRegexMatcherTest.java @@ -0,0 +1,41 @@ +package homework_5; + +import base.UnitBase; +import homework_5.customRegexMatcher.CustomRegexMatcher; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CustomRegexMatcherTest extends UnitBase { + + @Test + public void regexMailTest() { + assertTrue(new CustomRegexMatcher().checkMail("kostya_asdsa@mail.ru")); + } + @Test + public void regexMailTest2() { + assertFalse(new CustomRegexMatcher().checkMail("kostya_asdsa@mail.r")); + } + @Test + public void regexMailTest3() { + assertFalse(new CustomRegexMatcher().checkMail("kos@gmail.com")); + } + @Test + public void regexMailTest4() { + assertTrue(new CustomRegexMatcher().checkMail("something23-as_sa@gmail.ru")); + } + @Test + public void regexMailTest5() { + assertFalse(new CustomRegexMatcher().checkMail("notvalidmail@a.com")); + } + @Test + public void regexMailTest6() { + assertTrue(new CustomRegexMatcher().checkMail("some_mail123@yandex.ru")); + } + @Test + public void regexMailTest7() { + assertFalse(new CustomRegexMatcher().checkMail("kosdf23adsamail.ru")); + } + +} diff --git a/src/test/java/homework_5/PowerOfNumberTest.java b/src/test/java/homework_5/PowerOfNumberTest.java new file mode 100644 index 00000000..d990bcc3 --- /dev/null +++ b/src/test/java/homework_5/PowerOfNumberTest.java @@ -0,0 +1,39 @@ +package homework_5; + + +import base.UnitBase; +import homework_5.powerOfNumber.PowerOfNumber; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PowerOfNumberTest extends UnitBase { + @Test + public void testRecMethodWithNegativeNumber() { + setInput("-2"); + new PowerOfNumber().run(); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + @Test + public void testRecMethondWithString() { + setInput("String"); + new PowerOfNumber().run(); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + @Test + public void powerOfNumberTest() { + assertEquals(4,new PowerOfNumber().rec(2,2)); + } + @Test + public void powerOfNumberTest2() { + assertEquals(2,new PowerOfNumber().rec(2,1)); + } + @Test + public void powerOfNumberTest3() { + assertEquals(1,new PowerOfNumber().rec(2,0)); + } + @Test + public void powerOfNumberTest4() { + assertEquals(0,new PowerOfNumber().rec(0,2)); + } +} \ No newline at end of file