diff --git a/.idea/artifacts/java1_jar2.xml b/.idea/artifacts/java1_jar2.xml new file mode 100644 index 0000000..b42aedc --- /dev/null +++ b/.idea/artifacts/java1_jar2.xml @@ -0,0 +1,11 @@ + + + $PROJECT_DIR$/out/artifacts/java1_jar2 + + + + + + + + \ No newline at end of file diff --git a/.idea/java1-1.iml b/.idea/java1-1.iml new file mode 100644 index 0000000..1e990d0 --- /dev/null +++ b/.idea/java1-1.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 3ccb27b..eae8511 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -11,7 +11,7 @@ - + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..0aa6085 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/input.txt b/input.txt new file mode 100644 index 0000000..9cb95f5 --- /dev/null +++ b/input.txt @@ -0,0 +1,6 @@ +{"apple", "orange", "lemon", "banana", "apricot", "avocado", "broccoli", "carrot", "cherry", "garlic", "grape", "melon", "leak", "kiwi", "mango", "mushroom", "nut", "olive", "pea", "peanut", "pear", "pepper", "pineapple", "pumpkin", "potato"}; + + +|_|X|_| +|_|_|_| +|_|_|O| \ No newline at end of file diff --git a/src/java/META-INF/MANIFEST.MF b/src/java/META-INF/MANIFEST.MF new file mode 100644 index 0000000..e566020 --- /dev/null +++ b/src/java/META-INF/MANIFEST.MF @@ -0,0 +1,4 @@ +Manifest-Version: 1.0 +Main-Class: lesson4.Main +Class-Path: sqlite-jdbc-3.28.0.jar + diff --git a/src/java/lesson2/Cycles.java b/src/java/lesson2/Cycles.java new file mode 100644 index 0000000..e78b58d --- /dev/null +++ b/src/java/lesson2/Cycles.java @@ -0,0 +1,151 @@ +package lesson2; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Random; +import java.util.Scanner; + +public class Cycles { + + static void printN(char c, int n) { + while (n-- > 0) System.out.print(c); + } + + static void whileCycle() { + //пока выполняется условие { делать это } + int n = 5; + while (n > 0) { + System.out.println("n = " + n); + n--; + } + n = 5; + //[][][][][] + while (n-- > 0) System.out.print("[]"); + System.out.println(); + n = 0; + //[][[]][[[]]][[[[]]]][[[[[]]]]] + while (n < 5) { + printN('[', n + 1); + printN(']', n + 1); + n++; + } + System.out.println(); + //multiply table 9 * 9 + int i = 1, j = 1; + while (i < 10) { + j = 1; + while (j < 10) { + System.out.printf("%3d |", i * j); + j++; + } + System.out.println(); + i++; + } + } + + static void forCycle() { + for (int i = 1; i < 6; i++) { + System.out.println("n = " + i); + } + for (int i = 1; i <= 5; i++) { + for (int j = 0; j < i; j++) { + System.out.print('['); + } + for (int j = 0; j < i; j++) { + System.out.print(']'); + } + } + System.out.println(); + for (int i = 1; i < 10; i++) { + for (int j = 1; j < 10; j++) { + System.out.printf("%3d ", i * j); + } + System.out.println(); + } + int a = 3, b = 7, c = 12; + //1 2 4 8 16 .... +// for (int i = 1, cnt = 0; cnt < 50; i <<= 1, cnt++) { +// System.out.print(i + " "); +// if (cnt % 10 == 0) System.out.println(); +// } + for (int i = 1; i < 10000; i <<= 1) { + System.out.print(i + " "); + } + System.out.println(); + for (int i = 1, cnt = 1; i < 100; i += cnt, cnt++) { + System.out.println(i); + } + } + + static void arrays() { + int[] a = new int[]{3, 4, 5, 6, 7}; + System.out.println(Arrays.toString(a)); + for (int i = 0; i < a.length; i++) { + System.out.print(a[i] + " "); + } + System.out.println(); + for (int i : a) { + System.out.print(i + " "); + } + //0,1,2,3,4,2,1,0 + //out: max array value, + //and index of this value + //impl1 O(N) depend by array length + int[] mou = new int[]{0, 12, 3, 2, 0}; + //int n = new Scanner(System.in).nextInt(); + //int [] ar = new int[n]; + //System.out.println(ar.length); + int peek = -1, index = -1; + int timeDifficult = 0; + for (int i = 0; i < mou.length; i++) { + timeDifficult++; + if (mou[i] > peek) { + peek = mou[i]; + index = i; + } + } + System.out.println(); + System.out.println("Processed by " + timeDifficult + " iteration"); + System.out.println("Peek height - " + peek + " at index = " + index); + //impl2 O(logN) + int l = 0, r = mou.length - 1; + timeDifficult = 0; + while (r - l != 3) { + timeDifficult++; + int m = (l + r) / 2; + if (mou[m] > mou[m - 1]) { + l = m - 1; + } else r = m + 1; + } + System.out.println("Processed by " + timeDifficult + " iteration"); + System.out.println("Peek height - " + mou[l + 1] + " at index = " + (l + 1)); + + } + + static void deepArrays() { + int [][] a = new int[3][4]; + System.out.println(a); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 4; j++) { + a[i][j] = i * j; + System.out.printf("%3d", a[i][j]); + } + System.out.println(); + } + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 3; j++) { + System.out.printf("%3d", a[j][i]); + } + System.out.println(); + } + int [][] ar = new int[3][]; + for (int i = 0; i < 3; i++) { + ar[i] = new int[new Random().nextInt(10)]; + } + System.out.println(Arrays.deepToString(ar)); + } + + public static void main(String[] args) { + deepArrays(); + } +} diff --git a/src/java/lesson2/IfCase.java b/src/java/lesson2/IfCase.java new file mode 100644 index 0000000..07c6b51 --- /dev/null +++ b/src/java/lesson2/IfCase.java @@ -0,0 +1,47 @@ +package lesson2; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Scanner; + +public class IfCase { + public static void main(String[] args) throws IOException { + int a = 4, b = 4; + if (a > 3 || ++b < 10) {} + //System.out.println(a + " " + b); + //input data case 0 + //a = System.in.read(); + //System.out.println((char) a); + //input data case 1 +// Scanner in = new Scanner(System.in); +// String s1 = in.nextLine(); +// String [] words = s1.split(" "); +// System.out.println(Arrays.toString(words)); +// while (in.hasNext()) { +// System.out.println(in.next()); +// } + //input case 2 +// BufferedReader br = new BufferedReader( +// new InputStreamReader(System.in) +// ); +// int val = Integer.parseInt(br.readLine()); +// System.out.println(val); + String name = "Иван"; + int age = 30; + //%s - str, %d - int, long, %f - double, %c - char + System.out.printf("%sу %d лет\n", name, age); + int value = 0; + switch (value) { + case 0: + System.out.println("ZERO"); + break; + case 1: + System.out.println("ONE"); + break; + default: + System.out.println("other"); + } + } +} diff --git a/src/java/lesson2/homework/HomeWork.java b/src/java/lesson2/homework/HomeWork.java new file mode 100644 index 0000000..6579120 --- /dev/null +++ b/src/java/lesson2/homework/HomeWork.java @@ -0,0 +1,65 @@ +package lesson2.homework; + +import java.util.Arrays; + + + +public class HomeWork { + public static void main(String[] args) { + + +//** Задать одномерный массив и найти в нем минимальный и максимальный элементы (без помощи интернета); + + int[] maxMinArray = {5, 44, -34, 22, 44, -4, 5, 6, 4, 5, -56, 34, 67, 8}; + Arrays.sort(maxMinArray); + int max = maxMinArray[maxMinArray.length - 1], min = maxMinArray[0]; + System.out.println(max); + System.out.println(min); + +// Проверка методов + System.out.println(checkBalance(new int[]{2, 2, 2, 1, 2, 2, 10, 1})); + int[] array = new int[]{1, 2, 3, 4, 5, 6, 7}; + shift(array, -1); + System.out.println(Arrays.toString(array)); + } + + +//** Написать метод, в который передается не пустой одномерный целочисленный массив, +// метод должен вернуть true, если в массиве есть место, в котором сумма левой и правой части массива равны. +// Примеры: checkBalance([2, 2, 2, 1, 2, 2, || 10, 1]) → true, checkBalance([1, 1, 1, || 2, 1]) → true, +// граница показана символами ||, эти символы в массив не входят. + + public static boolean checkBalance(int[] array) { + int sum = 0, leftSum = 0; + for (int i : array) { + sum += i; + } + for (int i : array) { + leftSum += i; + if (2 * leftSum == sum) { + return true; + } + } + return false; + } + +//**** Написать метод, которому на вход подается одномерный массив и число n (может быть положительным, или отрицательным), +// при этом метод должен сместить все элементы массива на n позиций. +// Для усложнения задачи нельзя пользоваться вспомогательными массивами. + + public static void shift(int[] array, int n) { + if (n < 0) { + n = -n; + n = n % array.length; + n = array.length - n; + } else { + n = n % array.length; + } + while (n > 0){ + int temp = array[array.length - 1]; + System.arraycopy(array, 0, array, 1, array.length - 1); + array[0] = temp; + n--; + } + } +} diff --git a/src/java/lesson3/classwork/Recursion.java b/src/java/lesson3/classwork/Recursion.java new file mode 100644 index 0000000..0710e32 --- /dev/null +++ b/src/java/lesson3/classwork/Recursion.java @@ -0,0 +1,47 @@ +package lesson3.classwork; + +import java.util.Scanner; + +public class Recursion { + //f(x) = 1 + f(x-1) + public static int f(int x) { + if (x <= 1) return 1; + return x * f(x - 1); + } + + public static void print(Scanner in) { + int n = in.nextInt(); + if (n == 0) return; + print(in); + System.out.print(n + " "); + } + + //aaaabbbccc = 4(a)3(b)3(c) -> 4(a)3(b)ccc -> 4(a)bbbccc -> aaaabbbccc + public static String decompress(String s) { + int lastBracket = s.lastIndexOf('('); + if (lastBracket == -1) { + return s; + } else { + int endBracket = lastBracket + s.substring(lastBracket).indexOf(')'); + int value = 0, pos = lastBracket - 1; + while (pos >= 0 && s.charAt(pos) >= '0' && s.charAt(pos) <= '9') { + value = value * 10 + (s.charAt(pos) - '0'); + pos--; + } + StringBuilder decomp = new StringBuilder(); + String part = s.substring(lastBracket + 1, endBracket); + System.out.println(part + " " + value); + while (value > 0) { + decomp.append(part); + value--; + } + System.out.println("d:" + decomp + " s:" + s); + return decompress(s.substring(0, pos+1) + + decomp + s.substring(endBracket+1)); + } + } + + public static void main(String[] args) { + System.out.println(decompress("2(def2(c2(ab2(cd)12(x))))")); + } +} diff --git a/src/java/lesson3/classwork/Strings.java b/src/java/lesson3/classwork/Strings.java new file mode 100644 index 0000000..cc3288c --- /dev/null +++ b/src/java/lesson3/classwork/Strings.java @@ -0,0 +1,43 @@ +package lesson3.classwork; + +import java.util.ArrayList; +import java.util.Arrays; + +public class Strings { + public static void main(String[] args) { + // str -> value final + String str = "abbabbaba"; + System.out.println((int)str.charAt(1)); +// for (int i = 49; i < 59; i++) { +// System.out.println(i + " : " + (char) i); +// } + System.out.println(); + System.out.println((char)('A' + 3)); + System.out.println(str.contains("abbc")); + System.out.println(str.indexOf("abb")); + System.out.println(str.lastIndexOf("abb")); + //String line = " word1\nword 2 word3"; + //String [] words = line.trim().split("( +|\\n)"); + String line = "word1 word2 word3"; + System.out.println(Arrays.toString(line.split(" "))); + //Integer i = 5; // boxing + //int value = new Integer(12); // unboxing + String a = "aaa", b = "aac", c = new String("aaa"); + System.out.println(a == b); + System.out.println(a.equals(c)); + //a > b -> > 0, a < b -> < 0, a == b -> 0 + System.out.println(a.compareTo(b)); + System.out.println(b.compareTo(a)); + //aabbccc + //aabbccca + //aaa + //Aaa + //matches replace + String s = "111222"; + System.out.println(s.matches("[0-9]+.[0-9]+")); + s = s.replaceAll("1", "5"); + System.out.println(s); + //boxing unboxing + //boxed types Type {int val} + } +} diff --git a/src/java/lesson3/classwork/Window.java b/src/java/lesson3/classwork/Window.java new file mode 100644 index 0000000..b1c0c6e --- /dev/null +++ b/src/java/lesson3/classwork/Window.java @@ -0,0 +1,5 @@ +package lesson3.classwork; + +public class Window { + +} diff --git a/src/java/lesson3/homework/HomeWork.java b/src/java/lesson3/homework/HomeWork.java new file mode 100644 index 0000000..03a6154 --- /dev/null +++ b/src/java/lesson3/homework/HomeWork.java @@ -0,0 +1,97 @@ +package lesson3.homework; +import java.util.Random; +import java.util.Scanner; +public class HomeWork { + /* Написать программу, которая загадывает случайное число от 0 до 9 и пользователю дается 3 попытки угадать это число. + При каждой попытке компьютер должен сообщить, больше ли указанное пользователем число, чем загаданное, или меньше. + После победы или проигрыша выводится запрос – «Повторить игру еще раз? 1 – да / 0 – нет»(1 – повторить, 0 – нет). + */ + public static String[] words; + public static void main(String[] args) { + int game = getNumberFromScanner("Какую игру Вы хотите запустить? 0 – Угадай число / 1 – Угадай слово", 0, 1); + if (game == 0) { + System.out.println("Вас приветсвует игра УГАДАЙ ЧИСЛО. Вам даеться три попытки."); + guessNumber(); + } + else { + words = new String[]{"apple", "orange", "lemon", "banana", "apricot", "avocado", "broccoli", "carrot", "cherry", "garlic", "grape", "melon", "leak", "kiwi", "mango", "mushroom", "nut", "olive", "pea", "peanut", "pear", "pepper", "pineapple", "pumpkin", "potato"}; + System.out.println("Вас приветсвует игра УГАДАЙ СЛОВО. Компьютер загадал одно из следующих слов: "); + for (int i = 0; i < 25; i++) System.out.println(words[i]); + guessWord(); + } + + } + + + public static int getNumberFromScanner(String message, int min, int max) { + int numberFromScaner; + do { + System.out.println(message); + Scanner sc = new Scanner(System.in); + numberFromScaner = sc.nextInt(); + } while (numberFromScaner < min || numberFromScaner > max); + return numberFromScaner; + } + public static void guessNumber() { + Random rand = new Random(); + int x = rand.nextInt(10); + for (int count = 1; count <= 3; count++) { + int number = getNumberFromScanner("Введите число в пределах от 0 до 9", 0, 9); + String alert = number > x ? "Загаданное число меньше." : (number < x ? "Загаданное число больше." : "Поздравляю!!! Вы угадали!"); + if (number == x) { + System.out.println(alert); + break; + } + String attempt = count == 3 ? " попыток" : (count == 2 ? " попытка" : " попытки"); + if (count == 3) System.out.println("Попытки закончились. Вы проиграли. Загаданое число " + x); + else System.out.println(alert + " У Вас осталось " + (3 - count) + attempt); + } + int q = getNumberFromScanner("Повторить игру еще раз? 1 – да / 0 – нет", 0, 1); + if (q == 1) guessNumber(); + else return; + + } + + /* + * Создать массив из словString[] words = {"apple", "orange", "lemon", "banana", "apricot", "avocado", "broccoli", "carrot", "cherry", "garlic", "grape", "melon", "leak", "kiwi", "mango", "mushroom", "nut", "olive", "pea", "peanut", "pear", "pepper", "pineapple", "pumpkin", "potato"}. + При запуске программы компьютер загадывает слово, запрашивает ответ у пользователя, сравнивает его с загаданным словом и сообщает, правильно ли ответил пользователь. Если слово не угадано, компьютер показывает буквы, которые стоят на своих местах. + apple – загаданное + apricot - ответ игрока + ap############# (15 символов, чтобы пользователь не мог узнать длину слова) + Для сравнения двух слов посимвольно можно пользоваться: + String str = "apple"; + char a = str.charAt(0); - метод, вернет char, который стоит в слове str на первой позиции + Играем до тех пор, пока игрок не отгадает слово. + Используем только маленькие буквы. + */ + + + public static void guessWord() { + Random rand = new Random(); + int x = rand.nextInt(25); + String word = words[x]; + for( ; ;) { + System.out.println(" Введите слово:"); + Scanner sc = new Scanner(System.in); + String wordFromScaner = sc.next(); + wordFromScaner = wordFromScaner.toLowerCase(); + if (wordFromScaner.equals(word)) { + System.out.println("Поздравляю Вы угадали слово!!!!"); + return; + } else { + System.out.println("Вы не угадали(. Попробуйте еще раз. Воспользуйтесь подсказкой - "); + int minWordLenght = Math.min(wordFromScaner.length(), word.length()); + for (int i = 0; i < minWordLenght; i++) { + char character = wordFromScaner.charAt(i) == word.charAt(i) ? wordFromScaner.charAt(i) : '#'; + System.out.print(character); + } + for (int y = 1; y < 15 - minWordLenght; y++) { + System.out.print("#"); + } + + } + } + + + } +} \ No newline at end of file diff --git a/src/java/lesson4/Main.java b/src/java/lesson4/Main.java new file mode 100644 index 0000000..d6d70de --- /dev/null +++ b/src/java/lesson4/Main.java @@ -0,0 +1,98 @@ +package lesson4; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Random; +import java.util.Scanner; + +public class Main { + + static void showTable(char [][] t) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + System.out.print("|" + t[i][j]); + } + System.out.println("|"); + } + } + + static void checkVictory(int [][] X, boolean user) { + for (int i = 0; i < 3; i++) { + int sX = 0, sY = 0, dS1 = 0, dS2 = 0; + for (int j = 0; j < 3; j++) { + sX += X[i][j]; + sY += X[j][i]; + dS1 += X[j][j]; + dS2 += X[j][2 - j]; + if (sX == 3 || sY == 3 || dS1 == 3 || dS2 == 3) { + System.out.println(user ? "Вы победили!" : "Вы проиграли"); + //System.out.println(sX + " " + sY + " " + dS1 + " " + dS2); + System.exit(0); + } + } + } + } + + public static void main(String[] args) throws InterruptedException { + Scanner in = new Scanner(System.in); + char def = '_'; + char [][] t = new char[3][3]; + int [][] X = new int[3][3]; + int [][] o = new int[3][3]; + for (int i = 0; i < 3; i++) { + Arrays.fill(t[i], def); + } + showTable(t); + System.out.println("Вы играете крестиками!" + + " Выберете номер строки и столбца"); + char user = 'X'; + int limit = 9; + while (true) { + System.out.println("Ваш ход:"); + int x = in.nextInt(), y = in.nextInt(); + x--; y--; + while (t[x][y] != def) { + System.out.println("Выберите пустую клетку! Ваш ход:"); + x = in.nextInt(); x--; + y = in.nextInt(); y--; + } + t[x][y] = user; + X[x][y] = 1; + showTable(t); + checkVictory(X, true); + System.out.println("Компьютер думает как походить"); + for (int i = 0; i < 7; i++) { + System.out.print("*"); + Thread.sleep(250); + } + System.out.println(); + moveAI(t, o); + showTable(t); + checkVictory(o, false); + System.out.println("******"); + limit--; + if (limit == 0) { + System.out.println("Ничья"); + System.exit(0); + } + } + } + + private static void moveAI(char[][] t, int [][] X) { + ArrayList pairs = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + if (t[i][j] == '_') { + pairs.add(new int[]{i, j}); + } + } + } + if (pairs.size() == 0) { + return; + } + int [] rnd = pairs.get(new Random().nextInt(pairs.size())); + t[rnd[0]][rnd[1]] = 'O'; + X[rnd[0]][rnd[1]] = 1; + } + +} diff --git a/src/java/lesson5/classwork/A.java b/src/java/lesson5/classwork/A.java new file mode 100644 index 0000000..8e1208f --- /dev/null +++ b/src/java/lesson5/classwork/A.java @@ -0,0 +1,20 @@ +package lesson5.classwork; + +public class A { + + public static int counter; + private int number; + + static { + counter = 0; + } + + public A() { + counter++; + number = counter; + } + + public void printNumber() { + System.out.println(number); + } +} diff --git a/src/java/lesson5/classwork/Array.java b/src/java/lesson5/classwork/Array.java new file mode 100644 index 0000000..b6fad3d --- /dev/null +++ b/src/java/lesson5/classwork/Array.java @@ -0,0 +1,34 @@ +package lesson5.classwork; + +public class Array { + + private int [] data; + private int len; + + public Array() { + data = new int[100]; + len = 0; + } + + public void addToEnd(int value) { + data[len] = value; + len++; + } + public void removeFromEnd() { + len--; + } + + public int get(int index) { + return data[index]; + } + public void set(int index, int value) { + data[index] = value; + } + + public void printArray() { + for (int i = 0; i < len; i++) { + System.out.print(data[i] + " "); + } + System.out.println(); + } +} diff --git a/src/java/lesson5/classwork/Cat.java b/src/java/lesson5/classwork/Cat.java new file mode 100644 index 0000000..eb9696f --- /dev/null +++ b/src/java/lesson5/classwork/Cat.java @@ -0,0 +1,57 @@ +package lesson5.classwork; + +import java.util.ArrayList; + +public class Cat { + + String name; + int age; + + public Cat(){} + + public Cat(String name, int age) { + this.name = name; + this.age = age; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } + + public void setName(String name) { + this.name = name; + } + + public static void main(String[] args) { + Cat cat = new Cat("Vaska",12); + cat.setName("asfasf"); + System.out.println(cat); + //cat = null; + Cat ca1 = cat; + String s = "aaa" + "bbb", s1 = "cccc"; + s = s + 5; + //System.out.println(ca1.age); + Triangle t = new Triangle(3, 4); + //t.setA(4); + t.printInfo(); + System.out.println(t.angleAC()); + System.out.println(t.angleBC()); + System.out.println(t.angleAB()); +// Array ar = new Array(); +// for (int i = 0; i < 15; i++) { +// ar.addToEnd(i+1); +// } +// ar.printArray(); +// ar.removeFromEnd(); +// ar.set(3, 700); +// ar.printArray(); + ArrayList list = new ArrayList<>(); + for (int i = 0; i < 15; i++) { + list.add(i+1); + } + } +} diff --git a/src/java/lesson5/classwork/Test.java b/src/java/lesson5/classwork/Test.java new file mode 100644 index 0000000..8143f19 --- /dev/null +++ b/src/java/lesson5/classwork/Test.java @@ -0,0 +1,20 @@ +package lesson5.classwork; + +import java.util.ArrayList; +import java.util.Random; + +public class Test { + public static void main(String[] args) { + ArrayList list = new ArrayList<>(); + for (int i = 0; i < 20; i++) { + list.add(new A()); + } + for (int i = 0; i < 5; i++) { + list.remove(new Random().nextInt(list.size())); + } + for (A a : list) { + a.printNumber(); + } + new A().printNumber(); + } +} diff --git a/src/java/lesson5/classwork/Triangle.java b/src/java/lesson5/classwork/Triangle.java new file mode 100644 index 0000000..05cbdef --- /dev/null +++ b/src/java/lesson5/classwork/Triangle.java @@ -0,0 +1,58 @@ +package lesson5.classwork; + +public class Triangle { + // + private double a, b, c; + + public Triangle(double a, double b) { + this.a = a; + this.b = b; + c = Math.sqrt(a * a + b * b); + } + //alt + insert + + public boolean checkInPoint(double x, double y) { + // TODO: 28.01.2020 + return false; + } + + public void setA(double length) { + this.a = length; + c = Math.sqrt(a * a + b * b); + } + + public void setB(double length) { + this.b = length; + c = Math.sqrt(a * a + b * b); + } + + public double angleAC() { + return Math.asin(b / c) * 180 / Math.PI; + } + + public double angleBC() { + return Math.acos(b / c) * 180 / Math.PI; + } + + public double angleAB() { + return 180 - angleAC() - angleBC(); + } + + public double getA() { + return a; + } + + public double getB() { + return b; + } + + public double getC() { + return c; + } + + public void printInfo() { + System.out.printf("a = %.2f, b = %.2f, c = %.2f\n", a, b, c); + } + +// +} diff --git a/src/java/lesson5/homework/HomeWork.java b/src/java/lesson5/homework/HomeWork.java new file mode 100644 index 0000000..0573212 --- /dev/null +++ b/src/java/lesson5/homework/HomeWork.java @@ -0,0 +1,38 @@ +package lesson5.homework; + +import lesson5.classwork.Array; + +import java.util.ArrayList; + +public class HomeWork { + + class Person { + + String name; + int age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + } + + public Person [] createFivePerson() { + Person [] people = new Person[50]; + for (int i = 0; i < 50; i++) { + people[i] = new Person("Ivan", i + 20); + } + return people; + } + + public ArrayList filterBiggerThan40(Person [] people) { + ArrayList list = new ArrayList<>(); + for(Person person : people) { + if (person.age >= 40) { + list.add(person); + } + } + return list; + } + +} diff --git a/src/java/lesson6/classwork/A.java b/src/java/lesson6/classwork/A.java new file mode 100644 index 0000000..fac0ebd --- /dev/null +++ b/src/java/lesson6/classwork/A.java @@ -0,0 +1,63 @@ +package lesson6.classwork; + +public class A { + + private int a, b; + private float c; + int d; + public int e; + + public A() { + System.out.println("1"); + } + + public A(int a, int b) { + //this(); + System.out.println("2"); + this.a = a; + this.b = b; + } + + public A(float a) { + System.out.println("3"); + this.c = a; + } + + public A(int a, int b, float c) { + this(a,b); + this.c = c; + System.out.println("4"); + } + + //1. overloading static in class + //fooii + int foo(int a, int b){ + return 1; + } + //fooif + int foo(int a, float c) { + return 2; + } + + int foo(int i) { + return 3; + } + + int foo(long l) { + return 4; + } + + int foo(double d) { + return 6; + } + + int foo(float f) { + return 5; + } + + + public static void main(String[] args) { + A a = new A(); + //System.out.println(a.foo(12)); + } +} diff --git a/src/java/lesson6/classwork/B.java b/src/java/lesson6/classwork/B.java new file mode 100644 index 0000000..2ee4851 --- /dev/null +++ b/src/java/lesson6/classwork/B.java @@ -0,0 +1,24 @@ +package lesson6.classwork; + +public class B extends A { + public B() { + } + + public B(int a, int b, int c) { + super(a, b); + c = 0; + } + + public B(float a) { + super(a); + } + + public B(int a, int b, float c) { + super(a, b, c); + } + + public static void main(String[] args) { + B b = new B(); + + } +} diff --git a/src/java/lesson6/classwork/C.java b/src/java/lesson6/classwork/C.java new file mode 100644 index 0000000..23856dd --- /dev/null +++ b/src/java/lesson6/classwork/C.java @@ -0,0 +1,4 @@ +package lesson6.classwork; + +public class C { +} diff --git a/src/java/lesson6/classwork/constructors/A.java b/src/java/lesson6/classwork/constructors/A.java new file mode 100644 index 0000000..774738b --- /dev/null +++ b/src/java/lesson6/classwork/constructors/A.java @@ -0,0 +1,17 @@ +package lesson6.classwork.constructors; + +public class A { + + private int a; + public int aI; + + public A(int a, int aI) { + System.out.println("A was invoked"); + this.a = a; + this.aI = aI; + } + + public void printParam() { + System.out.print(a + " " + aI); + } +} diff --git a/src/java/lesson6/classwork/constructors/B.java b/src/java/lesson6/classwork/constructors/B.java new file mode 100644 index 0000000..a597a18 --- /dev/null +++ b/src/java/lesson6/classwork/constructors/B.java @@ -0,0 +1,18 @@ +package lesson6.classwork.constructors; + +public class B extends A { + + public int c; + + public B(int a, int aI, int c) { + super(a, aI); + this.c = c; + System.out.println("B was invoked"); + } + + @Override + public void printParam() { + super.printParam(); + System.out.print(" " + c); + } +} diff --git a/src/java/lesson6/classwork/constructors/C.java b/src/java/lesson6/classwork/constructors/C.java new file mode 100644 index 0000000..9fceb8a --- /dev/null +++ b/src/java/lesson6/classwork/constructors/C.java @@ -0,0 +1,33 @@ +package lesson6.classwork.constructors; + +import java.util.ArrayList; +import java.util.List; + +public class C extends B { + + public int d; + + public C(int a, int aI, int c, int d) { + super(a, aI, c); + this.d = d; + } + + @Override + public void printParam() { + super.printParam(); + System.out.println(" " + d); + } + + public void foo(A a) { + a.printParam(); + } + + public static void main(String[] args) { + C c = new C(1,2,3,4); + c.foo(new A(1,2)); + c.foo(new B(1,2,3)); + c.foo(new C(1,2,3,4)); + List list = new ArrayList<>(); + //System.out.println(c.getClass()); + } +} diff --git a/src/java/lesson6/classwork/expressions/BinaryExpression.java b/src/java/lesson6/classwork/expressions/BinaryExpression.java new file mode 100644 index 0000000..268d1b8 --- /dev/null +++ b/src/java/lesson6/classwork/expressions/BinaryExpression.java @@ -0,0 +1,11 @@ +package lesson6.classwork.expressions; + +public abstract class BinaryExpression implements Expression { + + Expression left, right; + + public BinaryExpression(Expression left, Expression right) { + this.left = left; + this.right = right; + } +} diff --git a/src/java/lesson6/classwork/expressions/Const.java b/src/java/lesson6/classwork/expressions/Const.java new file mode 100644 index 0000000..3139587 --- /dev/null +++ b/src/java/lesson6/classwork/expressions/Const.java @@ -0,0 +1,22 @@ +package lesson6.classwork.expressions; + +public class Const extends UnaryExpression { + + int value; + + public Const(int value) { + this.value = value; + } + + @Override + public String toString() { + + return String.valueOf(value); + } + + @Override + public int evalute() { + System.out.println("val"); + return value; + } +} diff --git a/src/java/lesson6/classwork/expressions/Expression.java b/src/java/lesson6/classwork/expressions/Expression.java new file mode 100644 index 0000000..fef22a9 --- /dev/null +++ b/src/java/lesson6/classwork/expressions/Expression.java @@ -0,0 +1,7 @@ +package lesson6.classwork.expressions; + +@FunctionalInterface +public interface Expression { + int evalute(); + String toString(); +} diff --git a/src/java/lesson6/classwork/expressions/Multiply.java b/src/java/lesson6/classwork/expressions/Multiply.java new file mode 100644 index 0000000..2d3b097 --- /dev/null +++ b/src/java/lesson6/classwork/expressions/Multiply.java @@ -0,0 +1,19 @@ +package lesson6.classwork.expressions; + +public class Multiply extends BinaryExpression { + + public Multiply(Expression left, Expression right) { + super(left, right); + } + + @Override + public String toString() { + return "(" + left.toString() + " * " + right.toString() + ")"; + } + + @Override + public int evalute() { + System.out.println("mult"); + return left.evalute() * right.evalute(); + } +} diff --git a/src/java/lesson6/classwork/expressions/Sum.java b/src/java/lesson6/classwork/expressions/Sum.java new file mode 100644 index 0000000..4ad589a --- /dev/null +++ b/src/java/lesson6/classwork/expressions/Sum.java @@ -0,0 +1,19 @@ +package lesson6.classwork.expressions; + +public class Sum extends BinaryExpression { + + public Sum(Expression left, Expression right) { + super(left, right); + } + + @Override + public String toString() { + return "(" + left.toString() + " + " + right.toString() + ")"; + } + + @Override + public int evalute() { + System.out.println("sum"); + return left.evalute() + right.evalute(); + } +} diff --git a/src/java/lesson6/classwork/expressions/Test.java b/src/java/lesson6/classwork/expressions/Test.java new file mode 100644 index 0000000..9201f73 --- /dev/null +++ b/src/java/lesson6/classwork/expressions/Test.java @@ -0,0 +1,18 @@ +package lesson6.classwork.expressions; + +public class Test { + public static void main(String[] args) { + Expression expression = new Sum(new Sum(new Const(1), + new Const(2)), new Multiply(new Const(3), + new Sum(new Const(5), + new Const(6)))); + System.out.println(expression + " = " + expression.evalute()); + Expression div = new BinaryExpression(new Const(6), new Const(2)) { + @Override + public int evalute() { + return left.evalute() / right.evalute(); + } + }; + System.out.println(div + " = " + div.evalute()); + } +} diff --git a/src/java/lesson6/classwork/expressions/UnaryExpression.java b/src/java/lesson6/classwork/expressions/UnaryExpression.java new file mode 100644 index 0000000..c96c091 --- /dev/null +++ b/src/java/lesson6/classwork/expressions/UnaryExpression.java @@ -0,0 +1,7 @@ +package lesson6.classwork.expressions; + +public abstract class UnaryExpression implements Expression { + + Expression operand; + +} diff --git a/src/java/lesson6/classwork/inter/Animal.java b/src/java/lesson6/classwork/inter/Animal.java new file mode 100644 index 0000000..5cc9d75 --- /dev/null +++ b/src/java/lesson6/classwork/inter/Animal.java @@ -0,0 +1,17 @@ +package lesson6.classwork.inter; + +public abstract class Animal { + + String type; + + public Animal(String type) { + this.type = type; + } + + public abstract void say(); + + public void getType() { + System.out.println(type); + } + +} diff --git a/src/java/lesson6/classwork/inter/Cat.java b/src/java/lesson6/classwork/inter/Cat.java new file mode 100644 index 0000000..0206397 --- /dev/null +++ b/src/java/lesson6/classwork/inter/Cat.java @@ -0,0 +1,13 @@ +package lesson6.classwork.inter; + +public class Cat extends Animal { + + public Cat(String type) { + super(type); + } + + @Override + public void say() { + System.out.println("MEOW"); + } +} diff --git a/src/java/lesson6/classwork/inter/ConsoleWriter.java b/src/java/lesson6/classwork/inter/ConsoleWriter.java new file mode 100644 index 0000000..00dd95b --- /dev/null +++ b/src/java/lesson6/classwork/inter/ConsoleWriter.java @@ -0,0 +1,9 @@ +package lesson6.classwork.inter; + +public class ConsoleWriter implements Writer { + + @Override + public void println(String message) { + System.out.println(message); + } +} diff --git a/src/java/lesson6/classwork/inter/Dog.java b/src/java/lesson6/classwork/inter/Dog.java new file mode 100644 index 0000000..216fed8 --- /dev/null +++ b/src/java/lesson6/classwork/inter/Dog.java @@ -0,0 +1,13 @@ +package lesson6.classwork.inter; + +public class Dog extends Animal { + + public Dog(String type) { + super(type); + } + + @Override + public void say() { + System.out.println("WOW"); + } +} diff --git a/src/java/lesson6/classwork/inter/FileWriter.java b/src/java/lesson6/classwork/inter/FileWriter.java new file mode 100644 index 0000000..09e064e --- /dev/null +++ b/src/java/lesson6/classwork/inter/FileWriter.java @@ -0,0 +1,49 @@ +package lesson6.classwork.inter; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; + +public class FileWriter implements Writer { + + private String pathToFile; + private PrintWriter writer; + private File file; + + public FileWriter(){ + pathToFile = null; + file = new File("output.txt"); + if (!file.exists()) { + try { + boolean flag = file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public FileWriter(String pathToFile) { + this.pathToFile = pathToFile; + file = new File(pathToFile); + if (!file.exists()) { + try { + boolean flag = file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @Override + public void println(String message) { + try { + writer = new PrintWriter(file); + writer.println(message); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } finally { + writer.close(); + } + } +} diff --git a/src/java/lesson6/classwork/inter/Test.java b/src/java/lesson6/classwork/inter/Test.java new file mode 100644 index 0000000..d83d3e2 --- /dev/null +++ b/src/java/lesson6/classwork/inter/Test.java @@ -0,0 +1,18 @@ +package lesson6.classwork.inter; + +public class Test { + + static void print(String msg) { + System.out.println(msg); + } + + public static void main(String[] args) { + //Animal an = new Cat("cat"); + //an.say(); + //new Dog("dog").say(); + Writer writer = new ConsoleWriter(); + writer.println("OK"); + Writer fw = new FileWriter("C:\\Users\\Mikhail\\IdeaProjects\\java1\\src\\java\\lesson6\\classwork\\inter\\output.txt"); + fw.println("OK"); + } +} diff --git a/src/java/lesson6/classwork/inter/Writer.java b/src/java/lesson6/classwork/inter/Writer.java new file mode 100644 index 0000000..6b02a38 --- /dev/null +++ b/src/java/lesson6/classwork/inter/Writer.java @@ -0,0 +1,6 @@ +package lesson6.classwork.inter; +@FunctionalInterface +public interface Writer { + //public abstract + void println(String message); +} diff --git a/src/java/lesson6/homework/Animal.java b/src/java/lesson6/homework/Animal.java new file mode 100644 index 0000000..d1783d1 --- /dev/null +++ b/src/java/lesson6/homework/Animal.java @@ -0,0 +1,19 @@ +package lesson6.homework.animals; + +import java.util.List; +import java.util.Random; + +interface Run { + void run(int length); +} +interface Swim { + void swim(int length); +} +interface Jump { + void jump(int height); +} + +public abstract class Animal implements Run, Jump, Swim { + protected int runLimit, swimLimit, jumpLimit; +} + diff --git a/src/java/lesson6/homework/Cat.java b/src/java/lesson6/homework/Cat.java new file mode 100644 index 0000000..ab20196 --- /dev/null +++ b/src/java/lesson6/homework/Cat.java @@ -0,0 +1,46 @@ +package lesson6.homework.animals; + +import java.util.Random; + +public class Cat extends Animal { + + private Random rnd = new Random(); + private static String defaultName = "cat"; + private static int increment = 0; + + @Override + public String toString() { + return defaultName; + } + + public Cat() { + increment++; + defaultName += increment; + swimLimit = 0; + runLimit = 100 + rnd.nextInt(200); + jumpLimit = 1 + rnd.nextInt(3); + } + + @Override + public void run(int length) { + if (length <= runLimit) { + System.out.println(this + " run " + length + " m."); + } else { + System.out.println(this + " cannot run so long"); + } + } + + @Override + public void swim(int length) { + System.out.println(this + " are not able to swim"); + } + + @Override + public void jump(int height) { + if (height <= jumpLimit) { + System.out.println(this + " jump to " + height + " m."); + } else { + System.out.println(this + " cannot jump so high"); + } + } +} diff --git a/src/java/lesson6/homework/Dog.java b/src/java/lesson6/homework/Dog.java new file mode 100644 index 0000000..a55fa25 --- /dev/null +++ b/src/java/lesson6/homework/Dog.java @@ -0,0 +1,49 @@ +package lesson6.homework.animals; + +import java.util.Random; + +public class Dog extends Animal{ + private Random rnd = new Random(); + private static String defaultName = "dog"; + private static int increment = 0; + + @Override + public String toString() { + return defaultName; + } + + public Dog() { + increment++; + defaultName += increment; + swimLimit = 0; + runLimit = 300 + rnd.nextInt(200); + jumpLimit = 1 + rnd.nextInt(3); + } + + @Override + public void run(int length) { + if (length <= runLimit) { + System.out.println(this + " run " + length + " m."); + } else { + System.out.println(this + " cannot run so long"); + } + } + + @Override + public void swim(int length) { + if (length <= runLimit) { + System.out.println(this + " swim " + length + " m."); + } else { + System.out.println(this + " cannot swim so long"); + } + } + + @Override + public void jump(int height) { + if (height <= jumpLimit) { + System.out.println(this + " jump to " + height + " m."); + } else { + System.out.println(this + " cannot jump so high"); + } + } +} diff --git a/src/java/lesson6/homework/Test.java b/src/java/lesson6/homework/Test.java new file mode 100644 index 0000000..4b48bc3 --- /dev/null +++ b/src/java/lesson6/homework/Test.java @@ -0,0 +1,12 @@ +package lesson6.homework.animals; + +public class Test { + public static void main(String[] args) { + Cat cat = new Cat(); + Dog dog = new Dog(); + cat.jump(1); + cat.jump(100); + cat.run(100); + dog.swim(50); + } +} diff --git a/src/java/lesson6/homework/rd b/src/java/lesson6/homework/rd new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/java/lesson6/homework/rd @@ -0,0 +1 @@ + diff --git a/src/java/lesson7/classwork/BufferedInput.java b/src/java/lesson7/classwork/BufferedInput.java new file mode 100644 index 0000000..20a95a7 --- /dev/null +++ b/src/java/lesson7/classwork/BufferedInput.java @@ -0,0 +1,24 @@ +package lesson7.classwork; + +import java.io.*; +import java.util.Arrays; + +public class BufferedInput { + public static void main(String[] args) throws IOException { + String path = "C:\\Users\\Mikhail\\IdeaProjects\\java1\\src\\java\\lesson7\\res\\out.txt"; + OutputStream out = new FileOutputStream(new File(path)); + long start = System.currentTimeMillis(); + //klsdjlksdjgsdjglsjdlkgjsldjglsjdgl + //buffer = klsdjlksdjgsdjglsjd + //in.read() = buffer[pos++] if pos > length then + //read(buffer) pos = 0; + for (int i = 0; i < 300000 / 1000; i++) { // 10 ** 6 + byte [] buffer = new byte[1000]; + Arrays.fill(buffer, (byte) 49); + out.write(buffer); + } + out.close(); + long end = System.currentTimeMillis(); + System.out.println(end - start + " ms."); + } +} diff --git a/src/java/lesson7/classwork/Ex1.java b/src/java/lesson7/classwork/Ex1.java new file mode 100644 index 0000000..7b0a48c --- /dev/null +++ b/src/java/lesson7/classwork/Ex1.java @@ -0,0 +1,17 @@ +package lesson7.classwork; + +public class Ex1 { + public static void main(String[] args) { + StringBuilder s = new StringBuilder("abcde"); + s.setCharAt(2, 'L'); + s.delete(1, 3); // [left; right) + s.insert(2, "MAMA"); + System.out.println(); +// long start = System.currentTimeMillis(); +// for (int i = 0; i < 100000; i++) { // 10 ** 6 +// s.append('a');//s = new String(copy of "aaaaaa")O(len) + new String("a") +// } +// long end = System.currentTimeMillis(); +// System.out.println(end - start + " ms."); + } +} diff --git a/src/java/lesson7/classwork/Input.java b/src/java/lesson7/classwork/Input.java new file mode 100644 index 0000000..00a0b76 --- /dev/null +++ b/src/java/lesson7/classwork/Input.java @@ -0,0 +1,34 @@ +package lesson7.classwork; + +import java.io.*; +import java.util.Scanner; + +public class Input { + public static void main(String[] args) throws IOException { + String path = "C:\\Users\\Mikhail\\IdeaProjects\\java1\\src\\java\\lesson7\\res\\out.txt"; + File f = new File(path); + OutputStream fout = new FileOutputStream(f, true); +// fout.write(49); +// fout.write(49); +// fout.write(49); +// fout.close(); + try(PrintWriter pr = new PrintWriter(fout)) { + pr.println("My text 2"); + } + InputStream in = System.in; + OutputStream out = System.out; + +// int x, val = 0; +// //new Scanner(in).nextInt(); +// while ((x = in.read()) != -1) { +// out.write(x); +// if (x == 10) break; +// if (x <= '0' || x >= '9') { +// System.err.println("Number format exception"); +// return; +// } +// val = (val * 10) + x - '0'; +// } +// System.out.println(val); + } +} diff --git a/src/test/TestHomeWork3.java b/src/test/TestHomeWork3.java new file mode 100644 index 0000000..96026d2 --- /dev/null +++ b/src/test/TestHomeWork3.java @@ -0,0 +1,69 @@ +import lesson3.homework.HomeWork; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; + +public class TestHomeWork3 { + + HomeWork work; + + @Before + public void init() { + work = new HomeWork(); + } + + @Test + public void testTranslate(){ + Assert.assertEquals("[x, y, c]", Arrays.toString( + work.translate(new String[]{"a", "b", "c"}, + new String[]{"a", "b", "d"}, + new String[]{"x", "y", "z"}))); + Assert.assertEquals("[x, b, c]", Arrays.toString( + work.translate(new String[]{"a", "b", "c"}, + new String[]{"a", "e", "f"}, + new String[]{"x", "y", "z"}))); + Assert.assertEquals("[x, y, z, f, lol]", Arrays.toString( + work.translate(new String[]{"a", "b", "c", "d", "e", "f", "lol"}, + new String[]{"a", "b", "e", "c", "d"}, + new String[]{"x", "y", "z"}))); + Assert.assertEquals("[x, y, default, default, default, default]", Arrays.toString( + work.translate(new String[]{"a", "b", "c", "x", "y", "z"}, + new String[]{"a", "b", "d"}, + new String[]{"x", "y", "z", "default", "123"}))); + } + + @Test + public void testEmail() { + Assert.assertTrue(work.isEmail("email@email.com")); + Assert.assertTrue(work.isEmail("m.k.pupkin@host.zone.com")); + Assert.assertTrue(work.isEmail("m.k.pupkin123@host.zone.com")); + Assert.assertTrue(work.isEmail("89232335647@host.ea")); + Assert.assertTrue(work.isEmail("123@127.0.0.1")); + Assert.assertFalse(work.isEmail("Hello world")); + Assert.assertFalse(work.isEmail("")); + Assert.assertFalse(work.isEmail("@@@")); + Assert.assertFalse(work.isEmail("@")); + Assert.assertFalse(work.isEmail("12124.124124.ru")); + } + + @Test + public void testKOrder() { + Assert.assertEquals(1, work.kOrderValue(new int[]{1, 0, 3}, 2)); + Assert.assertEquals(5, work.kOrderValue(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 5)); + Assert.assertEquals(2, work.kOrderValue(new int[]{-1, -5, 9, 8, 1, 2, 5}, 4)); + } + + @Test + public void testDict() { + Assert.assertEquals(1, + work.countOfWordsFromDictionaryInString("mama mila ramu", new String[]{"mama"})); + Assert.assertEquals(4, + work.countOfWordsFromDictionaryInString("mama mila ramu, mama, mama!, MAMA", new String[]{"mama"})); + Assert.assertEquals(4, + work.countOfWordsFromDictionaryInString("a, b, c, d, e, f AA BB , A, B! C", new String[]{"a", "B"})); + Assert.assertEquals(5, + work.countOfWordsFromDictionaryInString("a, b, c, d, e, f AA BB , A, B! C", new String[]{"a", "B", "aa"})); + } +}