Created
November 17, 2018 15:20
-
-
Save LeaKoroliuk/9937bd921bdfc308b3c95445f8732f58 to your computer and use it in GitHub Desktop.
ItCentreJavaCore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| import java.util.Arrays; | |
| public class HW01ShellSort { | |
| public static void main(String[] args) { | |
| int[] arr = new int[7]; | |
| fillArrRandom(arr); | |
| System.out.println(Arrays.toString(arr)); | |
| selectionSort(arr); | |
| System.out.println(Arrays.toString(arr)); | |
| } | |
| public static void selectionSort(int[] arr) { | |
| for (int i = 0; i < arr.length - 1; i++) { | |
| for (int j = i + 1; j < arr.length; j++) { | |
| if (arr[i] > arr[j]) { | |
| swap(arr, i, j); | |
| } | |
| } | |
| } | |
| } | |
| public static void swap(int[] arr, int i, int j) { | |
| int tmp = arr[i]; | |
| arr[i] = arr[j]; | |
| arr[j] = tmp; | |
| } | |
| public static void fillArrRandom(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| arr[i] = (int) (Math.random() * 100 - 50); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| public class Task01ArraySort { | |
| static int count = 0; | |
| public static void main(String[] args) { | |
| int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; | |
| // bubbleSort(arr); | |
| // arrToPrint(arr); | |
| // System.out.println(); | |
| // bubbleRevSort(arr); | |
| // arrToPrint(arr); | |
| // System.out.println(); | |
| // System.out.println(count); | |
| // vibSort(arr); | |
| // arrToPrint(arr); | |
| // System.out.println(); | |
| // System.out.println(count); | |
| insSort(arr); | |
| arrToPrint(arr); | |
| System.out.println(); | |
| System.out.println(count); | |
| // shellsort, quicksort , mergesort | |
| } | |
| // метод, который выводит элементы массива на экран | |
| public static void arrToPrint(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| System.out.print(arr[i] + ", "); | |
| } | |
| } | |
| // пузырьковая сортировка в порядке возрастания | |
| public static void bubbleSort(int[] arr) { | |
| for (int i = 0; i < arr.length - 1; i++) { | |
| for (int j = 0; j < arr.length - 1; j++) { | |
| if (arr[j] > arr[j + 1]) { | |
| swap(arr, i, j + 1); | |
| } | |
| } | |
| } | |
| } | |
| // пузырьковая сортировка в порядке убывания | |
| public static void bubbleRevSort(int[] arr) { | |
| for (int i = 0; i < arr.length - 1; i++) { | |
| for (int j = i + 1; j < arr.length; j++) { // for (int j = 0; j < arr.length - 1; j++) { | |
| if (arr[j] > arr[i]) { // if (arr[j] < arr[i]) { | |
| swap(arr, i, j); | |
| } | |
| } | |
| } | |
| } | |
| // сортировка выборкой в порядке возрастания | |
| public static void vibSort(int[] arr) { | |
| int min; | |
| for (int i = 0; i < arr.length - 1; i++) { | |
| min = i; | |
| for (int j = i + 1; j < arr.length; j++) { | |
| if (arr[j] < arr[min]) { | |
| min = j; | |
| } | |
| } | |
| swap(arr, i, min); | |
| } | |
| } | |
| // сортировка вставками в порядке возрастания | |
| public static void insSort(int[] arr) { | |
| for (int i = 1; i < arr.length; i++) { | |
| for (int j = i; j > 0 && (arr[j] < arr[j - 1]); j--) { | |
| swap(arr, j, j - 1); | |
| } | |
| } | |
| } | |
| // замена местами | |
| public static void swap(int[] arr, int i, int j) { | |
| int tmp = arr[i]; | |
| arr[i] = arr[j]; | |
| arr[j] = tmp; | |
| count++; | |
| } | |
| // метод, который заполняет массив случайными цифрами | |
| public static void fillArrRandom(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| arr[i] = (int) (Math.random() * 100 - 50); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| import java.util.Arrays; | |
| public class Task02BubbleSortGolovach { | |
| public static void main(String[] args) { | |
| int[] arr = new int[5]; | |
| fillArrRandom(arr); | |
| System.out.println(Arrays.toString(arr)); | |
| System.out.println(); | |
| bubbleSortLargeToEnd(arr); | |
| System.out.println(Arrays.toString(arr)); | |
| System.out.println(); | |
| System.out.println("----------------------------"); | |
| int[] array = new int[7]; | |
| fillArrRandom(array); | |
| System.out.println(Arrays.toString(array)); | |
| System.out.println(); | |
| bubbleSortSmallToBegin(array); | |
| System.out.println(Arrays.toString(array)); | |
| } | |
| public static void bubbleSortSmallToBegin(int[] arr) { | |
| for (int barrier = 0; barrier < arr.length; barrier++) { | |
| for (int index = arr.length - 1; index > barrier; index--) { | |
| if (arr[index] < arr[index - 1]) { | |
| swap(arr, index, index - 1); | |
| } | |
| System.out.print(barrier + "-" + index + " "); | |
| } | |
| System.out.println(); | |
| } | |
| } | |
| public static void bubbleSortLargeToEnd(int[] arr) { | |
| for (int barrier = arr.length - 1; barrier >= 0; barrier--) { | |
| for (int index = 0; index < barrier; index++) { | |
| if (arr[index] > arr[index + 1]) { | |
| swap(arr, barrier, index); | |
| } | |
| System.out.print(barrier + "-" + index + " "); | |
| } | |
| System.out.println(); | |
| } | |
| } | |
| public static void swap(int[] arr, int b, int i) { | |
| int tmp = arr[b]; | |
| arr[b] = arr[i]; | |
| arr[i] = tmp; | |
| } | |
| public static void fillArrRandom(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| arr[i] = (int) (Math.random() * 100); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| import java.util.Arrays; | |
| public class Task03ArrayMirrorGolovach { | |
| public static void main(String[] args) { | |
| int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; | |
| arrayMirrorVer2(arr); | |
| System.out.println(Arrays.toString(arr)); | |
| } | |
| // метод, когда внешний цикл "пробегает" от середины к началу | |
| public static void arrayMirrorVer2(int[] arr) { | |
| for (int index = arr.length / 2 - 1; index >= 0; index--) { | |
| swap(arr, index, arr.length - 1 - index); | |
| } | |
| } | |
| public static void arrayMirror(int[] arr) { | |
| for (int index = 0; index < arr.length / 2; index++) { | |
| swap(arr, index, arr.length - 1 - index); | |
| } | |
| } | |
| public static void swap(int[] arr, int b, int i) { | |
| int tmp = arr[b]; | |
| arr[b] = arr[i]; | |
| arr[i] = tmp; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| import java.util.Arrays; | |
| public class Task04SystemArrayCopyGolovach { | |
| public static void main(String[] args) { | |
| int[] arr = { 10, 20, 30, 40, 50 }; | |
| System.arraycopy(arr, 1, arr, 2, 2); | |
| System.out.println(Arrays.toString(arr)); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| public class Task05MergerGolovach { | |
| public static void main(String[] args) { | |
| int[] arrFirst = { 1, 1, 7, 9 }; | |
| int[] arrSecond = { 2, 3, 4, 4 }; | |
| System.out.println(merge(arrFirst, arrSecond)); | |
| } | |
| // переписать аглоритм так, чтоб метод заработал (с помощью условия if, можно использовать SystemArrayCopy) | |
| public static int[] merge(int[] a, int[] b) { | |
| int[] result = new int[a.length + b.length]; | |
| int aIndex = 0; | |
| int bIndex = 0; | |
| while (aIndex + bIndex != result.length) { | |
| if (a[aIndex] < b[bIndex]) { | |
| result[aIndex + bIndex] = a[aIndex++]; | |
| } else { | |
| result[aIndex + bIndex] = b[bIndex++]; | |
| } | |
| } | |
| return result; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| import java.util.Arrays; | |
| public class Task06InsertionSortGolovach { | |
| public static void main(String[] args) { | |
| int[] arr = new int[7]; | |
| fillArrRandom(arr); | |
| insertionSort(arr); | |
| System.out.println(Arrays.toString(arr)); | |
| } | |
| public static void insertionSort(int[] arr) { | |
| for (int i = 1; i < arr.length; i++) { | |
| int newElement = arr[i]; | |
| int location = i - 1; | |
| while (location >= 0 && arr[location] > newElement) { | |
| arr[location + 1] = arr[location]; | |
| location--; | |
| } | |
| arr[location + 1] = newElement; | |
| } | |
| } | |
| public static void fillArrRandom(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| arr[i] = (int) (Math.random() * 100); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson01; | |
| import java.util.Arrays; | |
| public class Task07SelectionSortGolovach { | |
| public static void main(String[] args) { | |
| int[] arr = new int[7]; | |
| fillArrRandom(arr); | |
| selectionSort(arr); | |
| System.out.println(Arrays.toString(arr)); | |
| } | |
| public static void selectionSort(int[] arr) { | |
| for (int barrier = 0; barrier < arr.length - 1; barrier++) { | |
| int elem = arr[barrier]; | |
| for (int index = barrier + 1; index < arr.length; index++) { | |
| if (elem > arr[index]) { | |
| int tmp = arr[index]; | |
| arr[index] = arr[barrier]; | |
| arr[barrier] = tmp; | |
| } | |
| } | |
| } | |
| } | |
| public static void fillArrRandom(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| arr[i] = (int) (Math.random() * 100); | |
| } | |
| } | |
| public static void swap(int[] arr, int b, int i) { | |
| int tmp = arr[b]; | |
| arr[b] = arr[i]; | |
| arr[i] = tmp; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| import java.util.Scanner; | |
| public class HW01FibonacciNumberLoop { | |
| public static void main(String[] args) { | |
| int inputNum = inputNum(); | |
| System.out.println(fib(inputNum)); | |
| } | |
| // метод, который читывает с консоли число | |
| private static int inputNum() { | |
| @SuppressWarnings("resource") | |
| Scanner scan = new Scanner(System.in); | |
| System.out.println("Введите целое число: "); | |
| int inputNum = scan.nextInt(); | |
| return inputNum; | |
| } | |
| private static int fib(int args) { | |
| int[] arr = new int[args + 1]; | |
| if (args == 0) { | |
| return 0; | |
| } | |
| arr[0] = 0; | |
| arr[1] = 1; | |
| for (int i = 2; i < arr.length; i++) { | |
| arr[i] = arr[i - 1] + arr[i - 2]; | |
| } | |
| return arr[args]; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class HW02Hanoi { | |
| public static void main(String[] args) { | |
| int n = 8; | |
| hanoi(n, 1, 2, 3); | |
| } | |
| static void hanoi(int n, int from, int to, int additional) { | |
| if (n == 0) return; | |
| hanoi(n - 1, from, additional, to); | |
| System.out.println(from + " " + to); | |
| hanoi(n - 1, additional, to, from); | |
| } | |
| } | |
| /* | |
| Даны три стержня. | |
| На первом стержне находится несколько дисков сверху вниз по возрастанию размера диска. | |
| Два другие пустые. Требуется перенести все диски с первого стержня на второй. | |
| Переносить диски разрешается только по одному. Не разрешается класть больший диск на меньший. | |
| Вход. Количество дисков n (1 ≤ n ≤ 19) на первом стержне. | |
| Выход. Выведите по два числа в строке – номера стержней, откуда и куда переносится диск. Решение должно быть кратчайшим. | |
| Пример входа Пример выхода | |
| 3 1 2 | |
| 1 3 | |
| 2 3 | |
| 1 2 | |
| 3 1 | |
| 3 2 | |
| 1 2 | |
| РЕШЕНИЕ (рекурсия) | |
| Анализ алгоритма | |
| Пусть требуется перенести n дисков со стержня А на стержень B при помощи стержня C. Воспользуемся следующей рекурсивной схемой: | |
| · перенесем n – 1 дисков со стержня А на стержень C, используя B; | |
| · перенесем диск со стержня А на стержень B; | |
| · перенесем n – 1 дисков со стержня C на стержень B, используя А; | |
| Реализация алгоритма | |
| Функция hanoi моделирует перенос дисков со стержня from на стержень to, используя дополнительный стержень additional. | |
| void hanoi(int n, int from, int to, int additional) | |
| { | |
| if (n == 0) return; | |
| hanoi(n-1,from,additional,to); | |
| printf("%d %d\n",from,to); | |
| hanoi(n-1,additional,to,from); | |
| } | |
| Читаем количество дисков n. Моделируем работу ханойских башен по переносу n дисков с первого стержня на второй, используя третий. | |
| scanf("%d",&n); | |
| hanoi(n,1,2,3); | |
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task01 { | |
| public static void main(String[] args) { | |
| System.out.println("main start"); | |
| hi(true); | |
| System.out.println("main end"); | |
| } | |
| public static void hi(boolean bb) { | |
| if (bb == false) { | |
| return; | |
| } else { | |
| System.out.println("Hello, World!"); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task02 { | |
| static int count = 0; | |
| public static void main(String[] args) { | |
| hi(10); | |
| } | |
| public static void hi(int i) { | |
| count++; | |
| System.out.println("Hello " + i); | |
| if (count == 10) { | |
| return; | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task03 { | |
| public static void main(String[] args) { | |
| hi(10); | |
| } | |
| public static void hi(int i) { | |
| System.out.println("Hello " + i); | |
| if (i == 0) { | |
| return; | |
| } | |
| System.out.println("Hello " + i); | |
| hi(--i); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task04 { | |
| public static void main(String[] args) { | |
| hi(0); | |
| } | |
| public static void hi(int i) { | |
| if (i > 3) { | |
| return; | |
| } | |
| System.out.println("Возвышение " + i); | |
| hi(i + 1); | |
| System.out.println("Убывание " + i); | |
| return; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task05 { | |
| static int count = 0; | |
| public static void main(String[] args) { | |
| System.out.println(fib(0)); | |
| System.out.println(count); | |
| } | |
| public static int fib(int i) { | |
| count++; | |
| if (i == 0) { | |
| return 0; | |
| } | |
| if (i == 1) { | |
| return 1; | |
| } | |
| return fib(i - 1) + fib(i - 2); | |
| // или все можно записать одной строкой | |
| // return (args < 2) & arg : fib(i - 2) + fib(i - 1); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task06 { | |
| public static void main(String[] args) { | |
| System.out.println(f(5)); | |
| } | |
| public static int f(int n) { | |
| return n == 1 ? 1 : n * f(n - 1); | |
| // int tmp = 1; | |
| // if (n == 1) { | |
| // return tmp; | |
| // } else { | |
| // tmp = n * f(n - 1); | |
| // return tmp; | |
| // } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task07 { | |
| public static void main(String[] args) { | |
| System.out.println(pow(2, 7)); | |
| } | |
| public static int pow(int a, int b) { | |
| return (b == 0) ? 1 : a * pow(a, b - 1); | |
| // if (b == 0) { | |
| // return 1; | |
| // } else { | |
| // return a * pow(a, b - 1); | |
| // } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task08 { | |
| public static void main(String[] args) { | |
| int[] arr = new int[10]; | |
| fill(arr, 0); | |
| printArr(arr,0); | |
| System.out.println(find(arr, 0, 7)); | |
| } | |
| public static int find(int[] arr, int pos, int el) { | |
| if (pos < arr.length) { | |
| if (arr[pos] == el) { | |
| return pos; | |
| } else { | |
| return find(arr, pos + 1, el); | |
| } | |
| } else { | |
| return -1; | |
| } | |
| } | |
| public static int findLoop(int[] arr, int el) { | |
| for (int i = 0; i < arr.length; i++) { | |
| if(arr[i] == el) { | |
| return i; | |
| } | |
| } | |
| return -1; | |
| } | |
| public static void fill(int[] arr, int i) { | |
| if (i < arr.length) { | |
| arr[i] = (int) (Math.random() * 10); | |
| fill(arr, i + 1); | |
| } | |
| return; | |
| } | |
| public static void fillLoop(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| arr[i] = (int) (Math.random() * 10); | |
| } | |
| } | |
| public static void printArr(int[] arr, int i) { | |
| if (i < arr.length) { | |
| System.out.print(arr[i] + " "); | |
| printArr(arr, i + 1); | |
| }else { | |
| System.out.println(); | |
| } | |
| } | |
| public static void printArrLoop(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| System.out.print(arr[i] + " "); | |
| } | |
| System.out.println(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson02; | |
| public class Task09RecursionGolovach { | |
| public static void main(String[] args) { | |
| f(1); | |
| } | |
| private static void f(int arg) { | |
| System.out.print(" " + arg); | |
| if (arg < 7) { | |
| f(arg + 1); | |
| } | |
| System.out.print(" " + arg); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson03; | |
| public class Task01 { | |
| public static void main(String[] args) { | |
| System.out.println("Start"); | |
| User u1 = new User("Alex", 18, 45, "1@1.com"); | |
| // System.out.println(u1); // выводит на экран lesson03.User@7852e922 | |
| u1.printAll(); | |
| System.out.println(); | |
| u1.change(); | |
| System.out.println(); | |
| User u2 = new User("Anna", 18); | |
| u2.printAll(); | |
| // System.out.println(u1.email.compareTo(u2.email)); | |
| System.out.println(); | |
| System.out.println("count " + User.count); | |
| Task01 aaa = new Task01(); | |
| aaa.foo(); | |
| } | |
| void foo () { // можно добавить static и для объекта ничего не изменится | |
| System.out.println("Hello world"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson03; | |
| public class User { | |
| String name; | |
| int age; | |
| double weight; | |
| String email; | |
| static int count = 66; // статическая переменная | |
| User(String name, int age) { | |
| this.name = name; | |
| this.age = age; | |
| count++; | |
| } | |
| // User(String one, int two) { //не будет работать, будут null и 0 | |
| // name = name; | |
| // age = name; | |
| // } | |
| User(String name, int age, double weight, String email) { // конструктор | |
| this(name, age); | |
| this.weight = weight; | |
| this.email = email; | |
| } | |
| static void printCount() { | |
| System.out.println(count); | |
| // System.out.println(name); // не работает | |
| // System.out.println(this.name);// не работает | |
| } | |
| void printAll() { | |
| System.out.println(name); | |
| System.out.println(weight); | |
| System.out.println(age); | |
| System.out.println(email); | |
| System.out.println(count); | |
| } | |
| void change() { | |
| count = 777; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04; | |
| public class Marker { | |
| private String color; | |
| private String tradeMark; | |
| private int length; | |
| public String getColor() { | |
| return color; | |
| } | |
| public void setColor(String color) { | |
| this.color = color; | |
| } | |
| public String getTradeMark() { | |
| return tradeMark; | |
| } | |
| public void setTradeMark(String tradeMark) { | |
| this.tradeMark = tradeMark; | |
| } | |
| public int getLength() { | |
| return length; | |
| } | |
| public void setLenght(String lenght) { | |
| this.color = lenght; | |
| } | |
| public Marker(String color, String tradeMark, int lenght) { | |
| this.color = color; | |
| this.tradeMark = tradeMark; | |
| this.length = lenght; | |
| } | |
| public String toString() { | |
| return "Marker{" + | |
| "color='" + color + '\'' + | |
| ", tradeMark='" + tradeMark + '\'' + | |
| ", length=" + length + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04; | |
| import java.util.ArrayList; | |
| public class Runner { | |
| public static void main(String[] args) { | |
| Marker m1 = new Marker("black", "buroMax", 16); | |
| Marker m2 = new Marker("red", "buroMax", 16); | |
| Marker m3 = new Marker("blue", "buroMax", 16); | |
| // Marker[] arr = new Marker[3]; | |
| // arr[0] = m1; | |
| // arr[1] = m2; | |
| // arr[2] = m3; | |
| // for (int i = 0; i < arr.length; i++) { | |
| // System.out.println(arr[i]); | |
| // } | |
| // for (Marker m : arr) { | |
| // System.out.println(m); | |
| // } | |
| ArrayList<Marker> arr = new ArrayList<>(); | |
| arr.add(m1); | |
| arr.add(m2); | |
| arr.add(m3); | |
| // System.out.println(arr); | |
| for (Marker m : arr) { | |
| System.out.println(m); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04; | |
| public class Task01 { | |
| int x = 7; | |
| static int y = 8; | |
| static { | |
| y = 66; | |
| // x = 77; // ошибка | |
| System.out.println(y); | |
| } | |
| { | |
| x = 66; | |
| System.out.println(x); | |
| } | |
| public Task01(int x) { // конструктор | |
| this.x = x; | |
| } | |
| void print() { | |
| System.out.println(x + " " + y); | |
| } | |
| public static void main(String[] args) { | |
| System.out.println("main"); | |
| Task01 tt = new Task01(77); // экземпляр класса | |
| tt.print(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04; | |
| public class Task02 { | |
| public static void main(String[] args) { | |
| System.out.println("Start"); | |
| User u1 = new User("Alex", 18, 45, "1@1.com"); | |
| u1.setAge(66); | |
| System.out.println(u1); | |
| u1.printAll(); | |
| // User u2 = new User("Anna", 18); | |
| // u2.printAll(); | |
| // foo(); | |
| // System.out.println("count " + User.count); | |
| } | |
| static void foo () { | |
| System.out.println("Hello world"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04; | |
| public class User { | |
| private String name; | |
| private int age; | |
| private double weight; | |
| private String email; | |
| public static int count = 66; | |
| public String toString() { // метод должен обязательно! называться toString | |
| return "User{" + | |
| "name='" + name + '\'' + | |
| ", age='" + age + '\'' + | |
| ", weight='" + weight + '\'' + | |
| ", email='" + email + '\'' + | |
| '}'; | |
| } | |
| public int getAge() { | |
| return age; | |
| } | |
| public void setAge(int age) { | |
| if (age <= 0) { | |
| System.out.println("Error"); | |
| } else { | |
| this.age = age; | |
| } | |
| } | |
| public double getWeight() { | |
| return weight; | |
| } | |
| public void setWeight(int weight) { | |
| this.weight = weight; | |
| } | |
| User(String name, int age) { | |
| this.name = name; | |
| this.age = age; | |
| count++; | |
| } | |
| // User(String one, int two) { //не будет работать, будут null и 0 | |
| // name = name; | |
| // age = name; | |
| // } | |
| User(String name, int age, double weight, String email) { // конструктор | |
| this(name, age); | |
| this.weight = weight; | |
| this.email = email; | |
| } | |
| static void printCount() { | |
| System.out.println(count); | |
| } | |
| void printAll() { | |
| System.out.println(name); | |
| System.out.println(weight); | |
| System.out.println(age); | |
| System.out.println(email); | |
| System.out.println(count); | |
| } | |
| void change() { | |
| count = 777; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| public class Book { | |
| private int id; | |
| private String title; | |
| private String author; | |
| private String publisher; | |
| private int year; | |
| private int pages; | |
| private int price; | |
| private String binding; | |
| public int getId() { | |
| return id; | |
| } | |
| public void setId(int id) { | |
| this.id = id; | |
| } | |
| public String getTitle() { | |
| return title; | |
| } | |
| public void setTitle(String title) { | |
| this.title = title; | |
| } | |
| public String getAuthor() { | |
| return author; | |
| } | |
| public void setAuthor(String author) { | |
| this.author = author; | |
| } | |
| public String getPublisher() { | |
| return publisher; | |
| } | |
| public void setPublisher(String publisher) { | |
| this.publisher = publisher; | |
| } | |
| public int getYear() { | |
| return year; | |
| } | |
| public void setYear(int year) { | |
| this.year = year; | |
| } | |
| public int getPages() { | |
| return pages; | |
| } | |
| public void setPages(int pages) { | |
| this.pages = pages; | |
| } | |
| public int getPrice() { | |
| return price; | |
| } | |
| public void setPrice(int price) { | |
| this.price = price; | |
| } | |
| public String getBinding() { | |
| return binding; | |
| } | |
| public void setBinding(String binding) { | |
| this.binding = binding; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Book{" + "id=" + | |
| id + ", title='" + title + '\'' + | |
| ", author='" + author + '\'' + | |
| ", publisher='" + publisher + '\'' + | |
| ", year=" + year + | |
| ", pages=" + pages + | |
| ", price=" + price + | |
| ", binding=" + binding + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| import java.util.ArrayList; | |
| public class Books { | |
| private ArrayList<Book> books = new ArrayList<Book>(); | |
| // конструктор | |
| public Books() { | |
| books = new ArrayList<Book>(); | |
| } | |
| // добавляем новую книгу | |
| public void add(Book book) { | |
| books.add(book); | |
| } | |
| public Books findAuthor(String author) { | |
| Books results = new Books(); | |
| for (Book book : books) { | |
| if (book.getAuthor().equals(author)) { | |
| results.add(book); | |
| } | |
| } | |
| return results; | |
| } | |
| public Books findPublisher(String publisher) { | |
| Books results = new Books(); | |
| for (Book book : books) { | |
| if (book.getPublisher().equals(publisher)) { | |
| results.add(book); | |
| } | |
| } | |
| return results; | |
| } | |
| public Books findBooksPublishedAfterSpecifiedYear(int year) { | |
| Books results = new Books(); | |
| for (Book book : books) { | |
| if (book.getYear() > year) { | |
| results.add(book); | |
| } | |
| } | |
| return results; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Book{" + | |
| "books=" + books + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| public class BooksRunner { | |
| public static void main(String[] args) { | |
| Books list = new Books(); | |
| Book b1 = new Book(); | |
| b1.setAuthor("Author01"); | |
| b1.setPublisher("KIO"); | |
| b1.setYear(1989); | |
| b1.setPrice(199); | |
| Book b2 = new Book(); | |
| b2.setAuthor("Author02"); | |
| b2.setPublisher("Kyiv"); | |
| b2.setYear(2013); | |
| b2.setPrice(299); | |
| Book b3 = new Book(); | |
| b3.setAuthor("Author03"); | |
| b3.setPublisher("Lviv"); | |
| b3.setYear(2015); | |
| b3.setPrice(399); | |
| list.add(b1); | |
| list.add(b2); | |
| list.add(b3); | |
| System.out.println(list.findAuthor("Author02")); | |
| System.out.println(list.findPublisher("Lviv")); | |
| System.out.println(list.findBooksPublishedAfterSpecifiedYear(1990)); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Создать классы: | |
| 1. Book: id, Название, Автор (ы), Издательство, Год издания, Количество страниц, Цена, Тип переплета. | |
| 2. Books: ArrayList<Book> books. Позволяет выполнить поиск: | |
| a) список книг заданного автора; | |
| b) список книг, выпущенных заданным издательством; | |
| c) список книг, выпущенных после заданного года. | |
| 3. Клиентский класс BooksRunner, демонстрирующий работу предыдущих классов. | |
| Подсказки: | |
| 1. Конструктор по-умолчанию. | |
| 2. Приватные поля. | |
| 3. Геттеры/сеттеры для всех полей Book(). | |
| ------------------------------------------------------------------------------------------- | |
| Создать классы: | |
| 1. Point (Immutable): double x, double y. Methods: getters . | |
| 2. Line (Immutable): Point start, Point end. Methods: double getLength( ). | |
| 3. Lines: ArrayList<Line> lines. Methods: void add(Line line), double sumLength( ), Line longestLine( ). | |
| 4. Клиентский класс LineRunner, демонстрирующий работу предыдущих классов. | |
| Точка и линия должны быть неизменяемыми объектами (Immutable) - все поля final, отсутствуют setters. | |
| ------------------------------------------------------------------------------------------- | |
| Создать классы: | |
| 1. Rectangle (Прямоугольник), содержащий размеры (высоту и ширину), и умеющий подсчитывать свои периметр и площадь. | |
| 2. Rectangles (Прямоугольники), содержащий список прямоугольников, умеющий добавлять новые прямоугольники и подсчитывать их суммарную площадь. | |
| Подсказка: реализовать на основании ArrayList. | |
| 3. Клиентский класс RectangleRunner, демонстрирующий работу предыдущих классов. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Рекурсия | |
| 1. Посчитать сумму цифр введённого числа | |
| 2. Через рекурсию вернуть число в обратном порядке */ | |
| package lesson04HomeWork; | |
| import java.util.Scanner; | |
| public class HW04Task04Recursion { | |
| public static void main(String[] args) { | |
| int inputNum = inputNum(); | |
| System.out.println(revNumRec(inputNum)); | |
| System.out.println(sumOfNum(inputNum)); | |
| System.out.println(sumOfNumRec(inputNum)); | |
| } | |
| // метод, который читывает с консоли число | |
| private static int inputNum() { | |
| @SuppressWarnings("resource") | |
| Scanner scan = new Scanner(System.in); | |
| System.out.println("Введите целое число: "); | |
| int inputNum = scan.nextInt(); | |
| return inputNum; | |
| } | |
| // метод, который рекурсивно переворачивает число | |
| private static int revNumRec(int inputNum) { | |
| if (inputNum < 10) { | |
| return inputNum; | |
| } else { | |
| System.out.print(inputNum % 10); | |
| return revNumRec(inputNum / 10); | |
| } | |
| } | |
| // метод, который считает сумму цифр введённого числа | |
| private static int sumOfNum(int inputNum) { | |
| if (inputNum < 10) { | |
| return inputNum; | |
| } | |
| int sum = 0; | |
| while (inputNum > 0) { | |
| sum = sum + inputNum % 10; | |
| inputNum /= 10; | |
| } | |
| return sum; | |
| } | |
| // метод, который рекурсивно считает сумму цифр введённого числа | |
| private static int sumOfNumRec(int inputNum) { | |
| if (inputNum < 10) { | |
| return inputNum; | |
| } | |
| int sum = 0; | |
| while (inputNum > 0) { | |
| sum = sum + inputNum % 10; | |
| inputNum /= 10; | |
| } | |
| return sum; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| public class Line { | |
| private final Point start; | |
| private final Point end; | |
| public Line(Point start, Point end) { | |
| this.start = start; | |
| this.end = end; | |
| } | |
| public double getLength() { | |
| double length = 0; | |
| length = Math.sqrt((Math.pow((start.getX() - end.getX()), 2) + Math.pow((start.getY() - end.getY()), 2))); | |
| return length; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Line {start=" + start + ", end=" + end + "}"; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| public class LineRunner { | |
| public static void main(String[] args) { | |
| Lines listLines = new Lines(); | |
| Line l1 = new Line(new Point(0, 0), new Point(1, 1)); | |
| Line l2 = new Line(new Point(0, 0), new Point(2, 2)); | |
| Line l3 = new Line(new Point(0, 0), new Point(3, 3)); | |
| Line l4 = new Line(new Point(0, 0), new Point(4, 4)); | |
| Line l5 = new Line(new Point(0, 0), new Point(7, 7)); | |
| listLines.add(l1); | |
| listLines.add(l2); | |
| listLines.add(l3); | |
| listLines.add(l4); | |
| listLines.add(l5); | |
| listLines.add(new Line(new Point(0, 0), new Point(5, 5))); | |
| listLines.add(new Line(new Point(0, 0), new Point(6, 6))); | |
| System.out.println("Добавлено " + listLines.lineSize() + " линий"); | |
| System.out.println("Длина всех линий: " + listLines.sumLength()); | |
| System.out.println("Самая длинная линия: " + listLines.longestLine() + "\n" + "Ее длина: " | |
| + listLines.longestLine().getLength()); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| import java.util.ArrayList; | |
| public class Lines { | |
| private final ArrayList<Line> lines; | |
| public Lines() { | |
| lines = new ArrayList<Line>(); | |
| } | |
| public void add(Line line) { | |
| lines.add(line); | |
| } | |
| public int lineSize() { | |
| return lines.size(); | |
| } | |
| public double sumLength() { | |
| double sum = 0; | |
| for (Line l : lines) { | |
| sum += l.getLength(); | |
| } | |
| return sum; | |
| } | |
| public Line longestLine() { | |
| if (lines.isEmpty()) { | |
| System.out.println("List is empty"); | |
| return new Line(new Point(0, 0), new Point(0, 0)); | |
| } else { | |
| Line longestLine = lines.get(0); | |
| for (Line l : lines) { | |
| if (l.getLength() > longestLine.getLength()) { | |
| longestLine = l; | |
| } | |
| } | |
| return longestLine; | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| public class Point { | |
| private final double x; | |
| private final double y; | |
| public Point(double x, double y){ | |
| this.x = x; | |
| this.y = y; | |
| } | |
| public double getX() { | |
| return x; | |
| } | |
| public double getY() { | |
| return y; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Point {x=" + x + ", y=" + y + "}"; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| public class Rectangle { | |
| private double height; | |
| private double width; | |
| public Rectangle(double height, double width) { | |
| this.height = height; | |
| this.width = width; | |
| } | |
| // public double getHeight() { | |
| // return height; | |
| // } | |
| // | |
| // public void setHeight(double height) { | |
| // this.height = height; | |
| // } | |
| // | |
| // public double getWidth() { | |
| // return width; | |
| // } | |
| // | |
| // public void setWeight(double widht) { | |
| // this.width = widht; | |
| // } | |
| public double perim() { | |
| return ((height + width) * 2); | |
| } | |
| public double area() { | |
| return height * width; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Rectangle{" + | |
| "height=" + height + | |
| ", width=" + width + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| public class RectangleRunner { | |
| public static void main(String[] args) { | |
| Rectangles list = new Rectangles(); | |
| Rectangle r1 = new Rectangle(2, 4); | |
| Rectangle r2 = new Rectangle(2, 5); | |
| Rectangle r3 = new Rectangle(2, 6); | |
| Rectangle r4 = new Rectangle(2, 7); | |
| Rectangle r5 = new Rectangle(2, 8); | |
| list.addR(r1); | |
| list.addR(r2); | |
| list.addR(r3); | |
| list.addR(r4); | |
| list.addR(r5); | |
| System.out.println("Периметр прямоугольника " + r1 + " равен: " + r1.perim()); | |
| System.out.println("Площадь прямоугольника " + r2 + " равна: " + r1.area()); | |
| System.out.println("Площадь всех прямоугольников равна: " + list.totalArea()); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson04HomeWork; | |
| import java.util.ArrayList; | |
| public class Rectangles { | |
| private ArrayList<Rectangle> rectangles; | |
| public Rectangles(){ | |
| rectangles = new ArrayList<Rectangle>(); | |
| } | |
| public void addR(Rectangle rectangle){ | |
| rectangles.add(rectangle); | |
| } | |
| public double totalArea(){ | |
| double res = 0; | |
| for(Rectangle r: rectangles ){ | |
| res += r.area(); | |
| } | |
| return res; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Rectangles{}"; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson05; | |
| public class Figure { | |
| protected int a; | |
| protected int b; | |
| private int z; | |
| public Figure() { | |
| this.a = 0; | |
| this.b = 0; | |
| z = 777; | |
| } | |
| public Figure(int a, int b) { | |
| this.a = a; | |
| this.b = b; | |
| } | |
| public int perim() { | |
| System.out.print("Figure perim "); | |
| return 0; | |
| } | |
| public int area() { | |
| System.out.print("Figure area "); | |
| return 0; | |
| } | |
| public String toString() { | |
| return "Figure{" + "a=" + a + ", b=" + b + "}"; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson05; | |
| public class FigureRunner { | |
| public static void main(String[] args) { | |
| Rectangle rec = new Rectangle(2, 3); | |
| System.out.println(rec); | |
| // System.out.println(rec.toString()); // тоже, что и System.out.println(rec); | |
| System.out.println(rec.area()); | |
| System.out.println(rec.perim()); | |
| System.out.println(); | |
| Triangle tr = new Triangle(2, 3, 7); | |
| System.out.println(tr); | |
| System.out.println(tr.area()); | |
| System.out.println(tr.perim()); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson05; | |
| public class Rectangle extends Figure { // extends Figure - расширяет класс Figure | |
| public Rectangle(int a, int b) { | |
| super(a, b); | |
| } | |
| @Override | |
| public int perim() { | |
| System.out.print("Rectangle perim "); | |
| return (a + b) * 2; | |
| } | |
| @Override | |
| public int area() { | |
| System.out.print("Rectangle area "); | |
| return a*b; | |
| } | |
| @Override // такой же метод есть у родителя. Сигнатура должна быть такой же | |
| public String toString() { | |
| return "Rectangle{" + "a=" + a + ", b=" + b + "}"; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson05; | |
| public class Test { | |
| public static void main(String[] args) { | |
| String s = "Hello"; | |
| s = ppp(s); | |
| System.out.println(s); | |
| s = s + " world!!!"; | |
| System.out.println(s); | |
| } | |
| public static String ppp(String s) { | |
| s = s + " world"; | |
| return s; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson05; | |
| public class Triangle extends Figure { | |
| private int c; // третья сторона | |
| public Triangle(int a, int b, int c) { | |
| super(a, b); // эта строка должна быть первая | |
| this.c = c; | |
| } | |
| @Override | |
| public int perim() { | |
| System.out.print("Triangle perim "); | |
| return a + b + c; | |
| } | |
| @Override | |
| public int area() { | |
| System.out.print("Triangle area "); | |
| return (int) Math.sqrt((a + b + c) * 2); | |
| } | |
| @Override | |
| public String toString() { | |
| return "Triangle{" + "a=" + a + ", b=" + b + ", c=" + c + "}"; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson06; | |
| class Cat { | |
| public void move() { | |
| System.out.println("Cat move"); | |
| } | |
| } | |
| class BritishCat extends Cat { | |
| @Override | |
| public void move() { | |
| System.out.println("British cat move"); | |
| } | |
| public void sound() { | |
| System.out.println("Mayw"); | |
| } | |
| } | |
| class PersianCat extends Cat { | |
| @Override | |
| public void move() { | |
| System.out.println("Persian cat move"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson06; | |
| public class User { | |
| String name; | |
| int age; | |
| double weight; | |
| User(String name, int age, double weight) { | |
| this.name = name; | |
| this.age = age; | |
| this.weight = weight; | |
| } | |
| public String toString() { | |
| return "User{" + "name=" + name + ", age=" + age + "}"; | |
| } | |
| @Override | |
| public boolean equals(Object obj) { | |
| if (this == obj) { | |
| return true; | |
| } | |
| if (obj == null || this.getClass() != obj.getClass()) { | |
| return false; | |
| } | |
| User other = (User) obj; | |
| if (age == other.age && weight == other.weight) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| @Override | |
| public int hashCode() { | |
| int result = 17; | |
| result = 31 * result + name.hashCode(); | |
| result = 31 * result + age; | |
| long l = Double.doubleToLongBits(weight); | |
| result = 31 * result + (int) (l ^ (l >>> 32)); | |
| return result; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson06; | |
| public class UserRunner { | |
| public static void main(String[] args) { | |
| Object obj = new Object(); | |
| User c1 = new User("Anna", 23, 60); | |
| User c2 = new User("Mark", 23, 60); | |
| System.out.println(c1.equals(c2)); | |
| System.out.println(c1.hashCode()); | |
| System.out.println(c2.hashCode()); | |
| System.out.println(); | |
| Cat[] myCats = { new Cat(), new BritishCat(), new PersianCat() }; | |
| for (Cat c : myCats) { | |
| c.move(); | |
| } | |
| for (int i = 0; i < myCats.length; i++) { | |
| Cat c = myCats[i]; | |
| c.move(); | |
| } | |
| Cat c = new BritishCat(); | |
| // c.sound(); // не может вызвать такой метод | |
| BritishCat cc = new BritishCat(); | |
| cc.sound(); | |
| Cat myCat1 = new BritishCat(); | |
| BritishCat myCat2 = (BritishCat) myCat1; | |
| System.out.println(myCat1 instanceof PersianCat); | |
| if (myCat1 instanceof PersianCat) { | |
| PersianCat myCat3 = (PersianCat) myCat1; | |
| } | |
| // PersianCat myCat3 = (PersianCat) myCat1; // ошибка превращения класса | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson06HomeWork; | |
| public class Car { | |
| protected String mark; // Название | |
| protected double fuelInTank; // Топливо, которое есть в баке | |
| protected double maxfuel; // Размер бака | |
| protected double averagefuel; // Средний расход | |
| protected double distance; // Дистанция | |
| protected boolean onOff; // Работает / Выключено | |
| public Car() { | |
| } | |
| public Car(String mark, double fuelInTank, double maxfuel, double averagefuel) { | |
| this.mark = mark; | |
| this.fuelInTank = fuelInTank; | |
| this.maxfuel = maxfuel; | |
| this.averagefuel = averagefuel; | |
| } | |
| // При добавлении топлива поверять поместится ли в бак | |
| public void addFuel(double fuel) { | |
| if (fuel <= maxfuel - fuelInTank) { | |
| fuelInTank += fuel; | |
| } else if (fuel > maxfuel - fuelInTank) { | |
| System.out.println("The tank fits " + maxfuel + " L. Now it has " + fuelInTank + " L. You can add 0.1 to " + (maxfuel - fuelInTank) + " L."); | |
| return; | |
| } | |
| } | |
| // Начать поездку | |
| // Проверить заведена ли | |
| // Проверить хватит ли топлива на поезку учитывая средний расход и остаток | |
| // топлива | |
| // Вывести сколько топлива потратится на поездку и сколько останется | |
| public void goCar(double howManyKm) { | |
| double spentFlue = 0; | |
| double leftFlue = 0; | |
| if (onOff == false) { | |
| onOffCar(); | |
| double var = (fuelInTank * 100) / averagefuel; | |
| if (howManyKm < var) { | |
| spentFlue = (howManyKm * averagefuel) / 100; | |
| leftFlue = fuelInTank - spentFlue; | |
| } | |
| } | |
| System.out.println("During the trip spent " + spentFlue + " L of fuel."); | |
| System.out.println("Left " + leftFlue + " L of fuel."); | |
| } | |
| // При запуска проверять есть ли топливо | |
| // Если не заведена, то включить | |
| public void onOffCar() { | |
| if (fuelInTank > 0) { | |
| if (onOff == false) { | |
| onOff = true; | |
| } | |
| } else { | |
| System.out.println("The tank is empty. Please, refuel the car!"); | |
| } | |
| } | |
| // Вывести состояние автомобиля // Для чего этот метод??? | |
| public void printInfo() { | |
| System.out.println("Car {'" + mark + "', 'tank size': " + maxfuel + ", 'fuel': " + fuelInTank + ", 'average fuel: '" | |
| + averagefuel); | |
| } | |
| @Override | |
| public String toString() { | |
| return "Car{" + | |
| "mark='" + mark + '\'' + | |
| ", fuel=" + fuelInTank + | |
| ", maxfuel=" + maxfuel + | |
| ", averagefuel=" + averagefuel + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson06HomeWork; | |
| public class CarTruckRunner { | |
| public static void main(String[] args) { | |
| Car car1 = new Car("Volkswagen golf 1999", 15, 55, 10); | |
| Car car2 = new Car("Toyota Сorolla 2008", 50, 60, 10.7); | |
| System.out.println("At the time of delivery to the warehouse in the tank " + car1 + " " + car1.fuelInTank + " L. of fuel."); | |
| car1.addFuel(20); | |
| System.out.println("After the first refueling in the tank " + car1 + " " + car1.fuelInTank + " L. of fuel."); | |
| System.out.println(); | |
| car2.goCar(50); | |
| System.out.println(); | |
| Truck truck1 = new Truck ("Nissan UD1452C", 70, 200, 21, 12400); | |
| Truck truck2 = new Truck ("Hyundai HD 120", 58, 230, 18, 10350); | |
| System.out.println("At the time of delivery to the warehouse in the tank " + truck2 + " " + truck2.fuelInTank + " L. of fuel."); | |
| truck2.addFuel(70); | |
| System.out.println("After the first refueling in the tank " + truck2 + " " + truck2.fuelInTank + " L. of fuel."); | |
| System.out.println(); | |
| truck1 .goCar(171); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Car { | |
| //Название | |
| private String mark; | |
| //Топливо | |
| private double fuel; | |
| //Размер бака | |
| private double maxfuel; | |
| //Средний расход | |
| private double averagefuel; | |
| //Дистанция | |
| private double distance; | |
| //Работает / Выключено | |
| private boolean onOff; | |
| public Car() { | |
| } | |
| public Car(String mark, double fuel, double maxfuel, double averagefuel) { | |
| } | |
| //При добавлении топлива поверять поместится ли в бак | |
| public void addFuel(double fuel) { | |
| } | |
| //Начать поездку | |
| //Проверить заведена ли | |
| //Проверить хватит ли топлива на поезку учитывая средний расход и остаток топлива | |
| //Вывести сколько топлива потратится на поездку и сколько останется | |
| public void goCar(double howManyKm) { | |
| } | |
| //При запуска проверять есть ли топливо | |
| //Если не заведена, то включить | |
| public void onOffCar() { | |
| } | |
| //Вывести состояние автомобиля | |
| public void printInfo() { | |
| } | |
| } | |
| ------------------------------------ | |
| public class Truck extends Car{ | |
| private int weight; | |
| public Truck(String mark, double fuel, double maxfuel, double averagefuel, int weight) { | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson06HomeWork; | |
| public class Truck extends Car { | |
| private int weight; | |
| public Truck(String mark, double fuel, double maxfuel, double averagefuel, int weight) { | |
| super(mark, fuel, maxfuel, averagefuel); | |
| this.weight = weight; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Truck{" + | |
| "mark='" + mark + '\'' + | |
| ", fuel=" + fuelInTank + | |
| ", maxfuel=" + maxfuel + | |
| ", averagefuel=" + averagefuel + | |
| ", weight=" + weight + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson07; | |
| public interface Animal { | |
| void move(); | |
| void sound(); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson07; | |
| public class AnimalRunner { | |
| public static void main(String[] args) { | |
| Animal dog = new Dog(); | |
| Animal cat = new Cat(); | |
| dog.move(); | |
| ((Dog)dog).sleep(); | |
| cat.sound(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson07; | |
| public class Cat implements Animal { | |
| @Override | |
| public void move() { | |
| System.out.println("Cat move"); | |
| } | |
| @Override | |
| public void sound() { | |
| System.out.println("Cat scream"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson07; | |
| public class Dog implements Potvora { | |
| @Override | |
| public void move() { | |
| System.out.println("Dog move"); | |
| } | |
| @Override | |
| public void sound() { | |
| System.out.println("Dog scream"); | |
| } | |
| @Override | |
| public void sleep() { | |
| System.out.println("Dog sleep"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson07; | |
| public interface Potvora extends Animal, Reptilia { | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson07; | |
| public interface Reptilia { | |
| void sleep(); | |
| void move(); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08; | |
| import java.util.Comparator; | |
| public class SecondSort implements Comparator <User> { | |
| // мы гарантируем, что сравниватьс будут именно объекты User | |
| // если будут <Object>, нужно приведение | |
| @Override | |
| public int compare(User u1, User u2){ | |
| if (u1.getName().compareTo(u2.getName()) < 0) { | |
| return 1; | |
| } else if (u1.getName().compareTo(u2.getName()) > 0) { | |
| return -1; | |
| } else { | |
| if (u1.getAge() < u2.getAge()) { | |
| return 1; | |
| } else if (u1.getAge() > u2.getAge()) { | |
| return -1; | |
| } else { | |
| return 0; | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08; | |
| public class Task01 { | |
| public static void main(String[] args) { | |
| Integer intObject1 = new Integer(100); | |
| Double doubleObject1 = new Double(0.01); | |
| Integer intObject2 = new Integer("100"); | |
| Double doubleObject2 = new Double("0.01"); | |
| Integer intObject3 = Integer.valueOf("11"); | |
| Double doubleObject3 = Double.valueOf("11.1"); | |
| int i = intObject1; | |
| i++; | |
| intObject1 = i; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08; | |
| public class Task02 { | |
| public static void main(String[] args) { | |
| String s1 = "Hello"; | |
| String s2 = new String(s1); | |
| String s3 = "Hello"; | |
| String s4 = new String("Hello"); | |
| System.out.println(s1 == s2); | |
| System.out.println(s1 == s3); | |
| System.out.println(s1 == s4); | |
| System.out.println(s1.equals(s2)); | |
| System.out.println(s1.equals(s3)); | |
| System.out.println(s1.equals(s4)); | |
| s4 = s4 + " world"; | |
| System.out.println(s4); | |
| s2 = foo(s2); | |
| System.out.println(s2); | |
| } | |
| public static String foo(String s2) { | |
| s2 = s2 + " world"; | |
| return s2; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08; | |
| import java.util.Objects; | |
| public class User implements Comparable { | |
| private String name; | |
| private int age; | |
| public User(String name, int age) { | |
| this.name = name; | |
| this.age = age; | |
| } | |
| public String getName() { | |
| return name; | |
| } | |
| public void setName(String name) { | |
| this.name = name; | |
| } | |
| public int getAge() { | |
| return age; | |
| } | |
| public void setAge(int age) { | |
| this.age = age; | |
| } | |
| @Override | |
| public boolean equals(Object obj) { // (User user) | |
| if (this == obj) { | |
| return true; | |
| } | |
| if (obj == null || getClass() != obj.getClass()) { | |
| return false; | |
| } | |
| User user = (User) obj; | |
| return age == user.age && Objects.equals(name, user.name); //и только эта строка | |
| // или | |
| // if (this.age == user.age) { // if (this.age == user.age && this.name.equals(user.name)) | |
| // if (this.name.equals(user.name)){ | |
| // return true; | |
| // } | |
| // return false; | |
| } | |
| // @Override | |
| //// public int compareTo(Object obj) { // сортирует только по возрасту | |
| //// if (this == obj) { | |
| //// return 0; | |
| //// } | |
| //// User user = (User) obj; | |
| //// if (this.age > user.getAge()) { // или if (this.age > ((User) obj).getAge()) { | |
| //// return 1; | |
| //// } else if (this.age < user.getAge()) { | |
| //// return -1; | |
| //// } else { | |
| //// return 0; | |
| //// } | |
| //// } | |
| @Override | |
| public int compareTo(Object obj) { //сортирует вначале по имени, а потом по возрасту | |
| if (this == obj) { | |
| return 0; | |
| } | |
| User user = (User) obj; | |
| if (this.name.compareTo(user.getName()) > 0) { | |
| return 1; | |
| } else if (this.name.compareTo(user.getName()) < 0) { | |
| return -1; | |
| } else { | |
| if (this.age > user.getAge()) { // или if (this.age > ((User) obj).getAge()) { | |
| return 1; | |
| } else if (this.age < user.getAge()) { | |
| return -1; | |
| } else { | |
| return 0; | |
| } | |
| } | |
| } | |
| @Override | |
| public String toString() { | |
| return "User{" + | |
| "name='" + name + '\'' + | |
| ", age=" + age + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08; | |
| import java.util.ArrayList; | |
| import java.util.Collections; | |
| import java.util.Comparator; | |
| public class UserRunner { | |
| public static void main(String[] args) { | |
| Users users = new Users(); | |
| users.add(new User("Anna", 18)); | |
| users.add(new User("Andrey", 16)); | |
| users.add(new User("Mark", 18)); | |
| users.add(new User("Marta", 94)); | |
| users.add(new User("Anna", 18)); | |
| System.out.println(users); | |
| System.out.println(users.getUser(0).equals(users.getUser(2))); | |
| System.out.println(users.getUser(0).equals(users.getUser(4))); | |
| System.out.println(users.getUser(0) == users.getUser(4)); | |
| System.out.println(); | |
| System.out.println(users.getUser(0).compareTo(users.getUser(4))); | |
| System.out.println(users.getUser(0).compareTo(users.getUser(1))); | |
| System.out.println(users.getUser(0).compareTo(users.getUser(2))); | |
| System.out.println(); | |
| ArrayList<User> newList = users.getList(); | |
| System.out.println("BEFORE" + newList); | |
| Collections.sort(newList); | |
| System.out.println("AFTER" + newList); | |
| newList.sort(new SecondSort()); | |
| System.out.println("SECOND" + newList); | |
| newList.sort(new Comparator<User>() { // от new до } - это анонимный класс | |
| @Override | |
| public int compare(User u1, User u2) { | |
| if (u1.getAge() < u2.getAge()) { | |
| return 1; | |
| } else if (u1.getAge() > u2.getAge()) { | |
| return -1; | |
| } else { | |
| return 0; | |
| } | |
| } | |
| }); | |
| System.out.println("Finally" + newList); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08; | |
| import java.util.ArrayList; | |
| public class Users { | |
| ArrayList <User> list = new ArrayList<>(); | |
| public ArrayList<User> getList(){ | |
| return list; | |
| } | |
| public void add(User user) { | |
| list.add(user); | |
| } | |
| public User getUser(int indx){ | |
| return list.get(indx); | |
| } | |
| @Override | |
| public String toString() { | |
| StringBuilder sb = new StringBuilder(); | |
| //String s = " "; | |
| for (User u: list){ | |
| sb.append(u.getName()).append(" ").append(u.getAge()).append("\n"); | |
| // s += + u.getName() + " " + u.getAge() + "\n"; | |
| } | |
| return sb.toString(); | |
| // return s; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08HomeWork.Customer; | |
| public class Customer implements Comparable<Customer> { | |
| private String lastName; | |
| private String firstName; | |
| private String middleName; | |
| private String address; | |
| private long cardNumber; | |
| private long accountNumber; | |
| public Customer(String lastName, String firstName, String middleName, String adress, long cardNumber) { | |
| this.lastName = lastName; | |
| this.firstName = firstName; | |
| this.middleName = middleName; | |
| this.address = adress; | |
| this.cardNumber = cardNumber; | |
| } | |
| public Customer(String lastName, String firstName, String middleName, String adress, long cardNumber, long accountNumber) { | |
| this(lastName, firstName, middleName, adress, cardNumber); | |
| this.accountNumber = accountNumber; | |
| } | |
| public String getLastName() { | |
| return lastName; | |
| } | |
| public void setLastName(String lastName) { | |
| this.lastName = lastName; | |
| } | |
| public String getFirstName() { | |
| return firstName; | |
| } | |
| public String getMiddleName() { | |
| return middleName; | |
| } | |
| public String getAddress() { | |
| return address; | |
| } | |
| public void setAddress(String address) { | |
| this.address = address; | |
| } | |
| public long getCardNumber() { | |
| return cardNumber; | |
| } | |
| public void setCardNumber(long cardNumber) { | |
| this.cardNumber = cardNumber; | |
| } | |
| public long getAccountNumber() { | |
| return accountNumber; | |
| } | |
| public void setAccountNumber(long accountNumber) { | |
| this.accountNumber = accountNumber; | |
| } | |
| @Override | |
| public int compareTo(Customer customer) { | |
| if (this == customer) { | |
| return 0; | |
| } | |
| if (this.address.compareTo(customer.getAddress()) > 0) { | |
| return 1; | |
| } else { | |
| return -1; | |
| } | |
| } | |
| @Override | |
| public String toString() { | |
| return "\n" + "Customer{" + | |
| "lastName='" + lastName + '\'' + | |
| ", firstName='" + firstName + '\'' + | |
| ", middleName='" + middleName + '\'' + | |
| ", address='" + address + '\'' + | |
| ", cardNumber=" + cardNumber + | |
| ", accountNumber=" + accountNumber + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08HomeWork.Customer; | |
| public class CustomerRunner { | |
| public static void main(String[] args) { | |
| Customers customersListFrom12Nov18 = new Customers(); | |
| Customer client1 = new Customer("Koroliuk", "Valerie", "Oleksiivna", "Dnipro, Vasylkivska 12/16, ap. 3", 4569_2568_5649_1548L, 2600_000_654_975L); | |
| Customer client2 = new Customer("Petrenko", "Oksana", "Andriivna", "Kyiv, Kreschatyk 25, ap. 17", 4586_2668_5482_1525L, 2600_0000_926_597L); | |
| Customer client3 = new Customer("Syhomlyn", "Ihor", "Petrovych", "Lviv, Vokzalna 1, ap. 14", 4569_2118_5649_3259L,2600_0000_123_597L); | |
| Customer client4 = new Customer("Sydorchuk", "Serhii", "Mykolayovych", "Kyiv, Antonova 56, ap. 265", 4569_2568_5649_1146L); | |
| Customer client5 = new Customer("Ivanov", "Iurii", "Vovodymyrovych", "Kharkiv, Uzhna 5", 4586_7289_5035_1548L); | |
| Customer client6 = new Customer("Koroliuk", "Serhii", "Vovodymyrovych", "Kyiv, Lygova 17, ap. 146", 4569_2568_5049_1525L); | |
| customersListFrom12Nov18.addCustomer(client1); | |
| customersListFrom12Nov18.addCustomer(client2); | |
| customersListFrom12Nov18.addCustomer(client3); | |
| customersListFrom12Nov18.addCustomer(client4); | |
| customersListFrom12Nov18.addCustomer(client5); | |
| customersListFrom12Nov18.addCustomer(client6); | |
| customersListFrom12Nov18.addCustomer(new Customer("Ivanova", "Kateryna", "Ihorivna", "Rivne", 4586_4589_2565_4269L, 2600_0000_598_255L)); | |
| System.out.println("List of customers whose last names begin with the letter 'K':" + "\n" + customersListFrom12Nov18.searchCustomersByFirstLetterOfLastName('K')); | |
| System.out.println("List of customers whose credit card number is in the specified range:" + "\n" + customersListFrom12Nov18.searchCreditCardNumberInTheSpecifiedRange(4568_0000_0000_0000L, 4570_0000_0000_0000L)); | |
| customersListFrom12Nov18.sortList(); | |
| System.out.println("List of buyers ordered by address:" + "\n" + customersListFrom12Nov18.printAddressFirst()); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 1. Получить список покупателей, чьи фамилии начинаются с буквы К; | |
| 2. Получить список покупателей, у которых номер кредитной карточки находится в | |
| указанном диапазоне; | |
| 3. Упорядочить покупателей согласно адресу проживания | |
| */ | |
| package lesson08HomeWork.Customer; | |
| import java.util.ArrayList; | |
| import java.util.Collections; | |
| public class Customers { | |
| private ArrayList<Customer> listOfCustomers; | |
| public Customers() { | |
| listOfCustomers = new ArrayList<>(); | |
| } | |
| public void addCustomer(Customer someCustomer) { | |
| listOfCustomers.add(someCustomer); | |
| } | |
| public void sortList(){ | |
| Collections.sort(listOfCustomers); | |
| } | |
| public String printAddressFirst() { | |
| StringBuilder sb = new StringBuilder(); | |
| for (Customer customer : listOfCustomers) { | |
| sb.append(customer.getAddress()).append(", ") | |
| .append(customer.getLastName()).append(" ") | |
| .append(customer.getFirstName()).append(" ") | |
| .append(customer.getMiddleName()).append(", ") | |
| .append(customer.getCardNumber()).append(", ") | |
| .append(customer.getAccountNumber()).append("\n"); | |
| } | |
| return sb.toString(); | |
| } | |
| public Customers searchCustomersByFirstLetterOfLastName(char inputChar) { | |
| Customers result = new Customers(); | |
| for (Customer customer : listOfCustomers) { | |
| if (customer.getLastName().charAt(0) == inputChar) { | |
| result.addCustomer(customer); | |
| } | |
| } | |
| return result; | |
| } | |
| public Customers searchCreditCardNumberInTheSpecifiedRange(long fromNum, long toNum) { | |
| Customers result = new Customers(); | |
| for (Customer customer : listOfCustomers) { | |
| if (customer.getCardNumber() >= fromNum && customer.getCardNumber() <= toNum) { | |
| result.addCustomer(customer); | |
| } | |
| } | |
| return result; | |
| } | |
| @Override | |
| public String toString() { | |
| StringBuilder sb = new StringBuilder(); | |
| for (Customer listOfCustomers : listOfCustomers) { | |
| sb.append(listOfCustomers.getLastName()).append(" ") | |
| .append(listOfCustomers.getFirstName()).append(" ") | |
| .append(listOfCustomers.getMiddleName()).append(", ") | |
| .append(listOfCustomers.getAddress()).append(", ") | |
| .append(listOfCustomers.getCardNumber()).append(", ") | |
| .append(listOfCustomers.getAccountNumber()).append("\n"); | |
| } | |
| return sb.toString(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Напишите консольное приложение, которое определяет целое | |
| положительное число в десятичной системе, затем преобразует и выводит его | |
| в двоичной/восьмиричной/шестнадцатиричной системах счисления. | |
| */ | |
| package lesson08HomeWork; | |
| import java.util.Scanner; | |
| public class Part01Task01 { | |
| public static void main(String[] args) { | |
| int inputNum = getInputNum(); | |
| System.out.println("Decimal (10): " + inputNum); | |
| System.out.println("Binary (2): " + getNumInBinarySystem(inputNum)); | |
| System.out.println("Octal (8): " + getNumInOctalSystem(inputNum)); | |
| System.out.println("Hex (16): " + getNumInHexadecimalSystem(inputNum)); | |
| } | |
| // в двоичной системе | |
| protected static String getNumInBinarySystem(int inputNum) { | |
| String numToString = ""; | |
| while (inputNum > 0) { | |
| int tmp = inputNum % 2; | |
| numToString += tmp; | |
| inputNum = inputNum / 2; | |
| } | |
| return getRevertString(numToString); | |
| } | |
| // в восьмеричной системе | |
| protected static String getNumInOctalSystem(int inputNum) { | |
| String numToString = ""; | |
| while (inputNum > 0) { | |
| int tmp = inputNum % 8; | |
| numToString += tmp; | |
| inputNum = inputNum / 8; | |
| } | |
| return getRevertString(numToString); | |
| } | |
| // в шестнадцатеричной системе | |
| protected static String getNumInHexadecimalSystem(int inputNum) { | |
| String numToString = ""; | |
| while (inputNum > 0) { | |
| int tmp = inputNum % 16; | |
| if (tmp == 10) { | |
| numToString += 'A'; | |
| } else if (tmp == 11) { | |
| numToString += 'B'; | |
| } else if (tmp == 12) { | |
| numToString += 'C'; | |
| } else if (tmp == 13) { | |
| numToString += 'D'; | |
| } else if (tmp == 14) { | |
| numToString += 'E'; | |
| } else if (tmp == 15) { | |
| numToString += 'F'; | |
| } else { | |
| numToString += tmp; | |
| } | |
| inputNum = inputNum / 16; | |
| } | |
| return getRevertString(numToString); | |
| } | |
| protected static String getRevertString(String s) { | |
| char[] charsArray = s.toCharArray(); | |
| String srtingRevert = ""; | |
| for (int i = s.length() - 1; i >= 0; i--) { | |
| srtingRevert += charsArray[i]; | |
| } | |
| return srtingRevert; | |
| } | |
| protected static int getInputNum() { // уточнить про return два раза и про ошибку, когда пользователь ввел строку | |
| Scanner sc = new Scanner(System.in); | |
| System.out.println("Input, please, the positive integer decimal number: "); | |
| if (sc.hasNextInt()) { | |
| return sc.nextInt(); | |
| } else { | |
| System.out.println("Wrong number! Please, try again."); | |
| } | |
| return sc.nextInt(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Напишите консольное приложение, которое находит все | |
| совершенные числа в диапазоне от 1 по некоторое заданное положительное | |
| число и выводит их (совершенное число – это число, которое равно сумме | |
| всех своих делителей, кроме самого себя. Например, 6 = 1+2+3). | |
| */ | |
| package lesson08HomeWork; | |
| public class Part01Task02 { | |
| public static void main(String[] args) { | |
| int n = 10_000; | |
| perfectNum(n); | |
| } | |
| protected static void perfectNum (int borderNum) { | |
| System.out.print("Perfect numbers from 1 to " + borderNum + " is : "); | |
| for (int i = 1; i <= borderNum; i++) { | |
| int sumOfDenominator = 0; | |
| for (int j = i - 1; j > 0; j--) { | |
| if (i % j == 0) { | |
| sumOfDenominator += j; | |
| } | |
| } | |
| if (sumOfDenominator == i) { | |
| System.out.print(i + ", "); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Напишите консольное приложение, которое вызывает метод для | |
| построения пирамиды высотой в диапазоне от 1 по 9. | |
| Например, для высоты = 4: | |
| 1 | |
| 121 | |
| 12321 | |
| 1234321 | |
| */ | |
| package lesson08HomeWork; | |
| import java.util.Scanner; | |
| public class Part01Task03 { | |
| public static void main(String[] args) { | |
| // int heightOfPyramid = getInputNum(); | |
| // int widthOfPyramid = heightOfPyramid * 2 - 1; | |
| int h = 4; | |
| int w = h * 2 - 1; | |
| // pyramidWithSymbol(h, w); | |
| // System.out.println(); | |
| pyramidWithNum(h, w); | |
| } | |
| protected static void pyramidWithNum(int h, int w) { | |
| for (int i = 1; i <= h; i++) { | |
| for (int j = 1; j <= w; j++) { | |
| if (j > h - i && j <= w - h + i) { | |
| if (j == h) { | |
| System.out.print(i); | |
| } else { | |
| int tmp = 1; | |
| System.out.print(i-tmp); | |
| tmp++; | |
| } | |
| } else { | |
| System.out.print(" "); | |
| } | |
| } | |
| System.out.println(); | |
| } | |
| } | |
| protected static void pyramidWithSymbol(int h, int w) { | |
| for (int i = 1; i <= h; i++) { | |
| for (int j = 1; j <= w; j++) { | |
| if (j > h - i && j <= w - h + i) { | |
| System.out.print("*"); | |
| } else { | |
| System.out.print(" "); | |
| } | |
| } | |
| System.out.println(); | |
| } | |
| } | |
| protected static int getInputNum() { | |
| Scanner sc = new Scanner(System.in); | |
| System.out.println("Input, please, the height (from 1 to 9) of pyramid: "); | |
| if (sc.hasNextInt()) { | |
| return sc.nextInt(); | |
| } else { | |
| System.out.println("Wrong number! Please, try again."); | |
| } | |
| return sc.nextInt(); | |
| } | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Напишите консольное приложение, которое обрабатывает | |
| квадратную матрицу согласно варианта (таблица 1). | |
| ТРЕБОВАНИЯ. | |
| 1. Приложение должно быть написано на языке Java. | |
| 2. Использовать только стандартные компиляторы и библиотеки. | |
| 3. При кодировании должны быть использованы соглашения об | |
| оформлении кода для языка Java. | |
| 4. Значения элементов матрицы задаются с помощью генератора | |
| случайных чисел. Матрица должна содержать как положительные, так | |
| и отрицательные значения. | |
| 5. Дополнительные данные (при необходимости) для обработки матрицы | |
| тоже задаются генератором случайных чисел. | |
| 6. Для проверки результата работы нужно вывести матрицу исходную и | |
| после обработки. | |
| */ | |
| package lesson08HomeWork; | |
| public class Part02 { | |
| public static void main(String[] args) { | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08HomeWork.Patient; | |
| import java.util.Objects; | |
| public class Patient implements Comparable<Patient> { | |
| private String lastName; | |
| private String firstName; | |
| private String middleName; | |
| private String address; | |
| private long phoneNumber; | |
| private int medicalCardNumber; | |
| private String diagnosis; | |
| public String getLastName() { | |
| return lastName; | |
| } | |
| public void setLastName(String lastName) { | |
| this.lastName = lastName; | |
| } | |
| public String getFirstName() { | |
| return firstName; | |
| } | |
| public String getMiddleName() { | |
| return middleName; | |
| } | |
| public String getAddress() { | |
| return address; | |
| } | |
| public void setAddress(String address) { | |
| this.address = address; | |
| } | |
| public long getPhoneNumber() { | |
| return phoneNumber; | |
| } | |
| public void setPhoneNumber(long phoneNumber) { | |
| this.phoneNumber = phoneNumber; | |
| } | |
| public int getMedicalCardNumber() { | |
| return medicalCardNumber; | |
| } | |
| public void setMedicalCardNumber(int medicalCardNumber) { | |
| this.medicalCardNumber = medicalCardNumber; | |
| } | |
| public String getDiagnosis() { | |
| return diagnosis; | |
| } | |
| public void setDiagnosis(String diagnosis) { | |
| this.diagnosis = diagnosis; | |
| } | |
| public Patient(String lastName, String firstName, String middleName, String address, long phoneNumber, int medicalCardNumber, String diagnosis) { | |
| this.lastName = lastName; | |
| this.firstName = firstName; | |
| this.middleName = middleName; | |
| this.address = address; | |
| this.phoneNumber = phoneNumber; | |
| this.medicalCardNumber = medicalCardNumber; | |
| this.diagnosis = diagnosis; | |
| } | |
| public boolean equals(Patient patient) { | |
| if (this == patient) { | |
| return true; | |
| } | |
| if (patient == null || getClass() != patient.getClass()) { | |
| return false; | |
| } | |
| return this.phoneNumber == patient.phoneNumber && | |
| this.medicalCardNumber == patient.medicalCardNumber && | |
| this.lastName == patient.lastName && | |
| this.firstName == patient.firstName && | |
| this.middleName == patient.middleName && | |
| this.address == patient.address && | |
| this.diagnosis == patient.diagnosis; | |
| } | |
| @Override | |
| public int hashCode() { | |
| return Objects.hash(lastName, firstName, middleName, address, phoneNumber, medicalCardNumber, diagnosis); | |
| } | |
| @Override | |
| public int compareTo(Patient patient) { | |
| if (this == patient) { | |
| return 0; | |
| } | |
| if (this.address.compareTo(patient.getLastName()) > 0) { | |
| return 1; | |
| } else { | |
| return -1; | |
| } | |
| } | |
| @Override | |
| public String toString() { | |
| return "Patient{" + | |
| "lastName='" + lastName + '\'' + | |
| ", firstName='" + firstName + '\'' + | |
| ", middleName='" + middleName + '\'' + | |
| ", address='" + address + '\'' + | |
| ", phoneNumber=" + phoneNumber + | |
| ", medicalCardNumber=" + medicalCardNumber + | |
| ", diagnosis='" + diagnosis + '\'' + | |
| '}'; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08HomeWork.Patient; | |
| import lesson08HomeWork.Customer.Customers; | |
| public class PatientRunner { | |
| public static void main(String[] args) { | |
| Patients patientsListFrom16Nov18 = new Patients(); | |
| patientsListFrom16Nov18.addPatient(new Patient("Koroliuk", "Valerie", "Oleksiivna", "Dnipro, Vasylkivska 12/16, ap. 3", 38_063_126_82_26L, 1257_6549, "A cold.")); | |
| patientsListFrom16Nov18.addPatient(new Patient("Petrenko", "Oksana", "Andriivna", "Kyiv, Kreschatyk 25, ap. 17", 38_097_148_82_54L, 1257_1546, "Pneumonia.")); | |
| patientsListFrom16Nov18.addPatient(new Patient("Syhomlyn", "Ihor", "Petrovych", "Lviv, Vokzalna 1, ap. 14", 38_093_256_12_57L, 1257_6592, "A broken arm.")); | |
| patientsListFrom16Nov18.addPatient(new Patient("Sydorchuk", "Serhii", "Mykolayovych", "Kyiv, Antonova 56, ap. 265", 38_066_569_12_85L, 1257_6691, "A cold.")); | |
| patientsListFrom16Nov18.addPatient(new Patient("Ivanov", "Iurii", "Vovodymyrovych", "Kharkiv, Uzhna 5", 38_063_259_78_36L, 1257_3659, "Cholecystitis.")); | |
| patientsListFrom16Nov18.addPatient(new Patient("Koroliuk", "Serhii", "Vovodymyrovych", "Kyiv, Lygova 17, ap. 146", 38_094_125_54_54L, 1257_1254, "A flu.")); | |
| System.out.println("The list of patients who have the specified diagnosis:" + "\n" + patientsListFrom16Nov18.listOfPatientsWhoHaveTheSpecifiedDiagnosis("A cold.")); | |
| System.out.println("List of customers whose credit card number is in the specified range:" + "\n" + patientsListFrom16Nov18.searchMedicalCardNumberInTheSpecifiedRange(1257_1000, 1257_2000)); | |
| patientsListFrom16Nov18.sortList(); | |
| System.out.println("Patient list in alphabetical order according to last name:" + "\n" + patientsListFrom16Nov18); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 1. Получить список пациентов, которые имеют указанный диагноз; | |
| 2. Получить список пациентов, у которых номер медицинской карточки находится в заданном диапазоне; | |
| 3. Упорядочить пациентов в алфавитном порядке согласно фамилии | |
| */ | |
| package lesson08HomeWork.Patient; | |
| import java.util.ArrayList; | |
| import java.util.Collections; | |
| public class Patients { | |
| private ArrayList<Patient> listOfPatients; | |
| public Patients() { | |
| listOfPatients = new ArrayList<>(); | |
| } | |
| public void addPatient(Patient somePatient) { | |
| listOfPatients.add(somePatient); | |
| } | |
| public void sortList() { | |
| Collections.sort(listOfPatients); | |
| } | |
| public Patients listOfPatientsWhoHaveTheSpecifiedDiagnosis(String someDiagnosis) { | |
| Patients result = new Patients(); | |
| for (Patient patient : listOfPatients) { | |
| if (patient.getDiagnosis().equals(someDiagnosis)) { | |
| result.addPatient(patient); | |
| } | |
| } | |
| return result; | |
| } | |
| public Patients searchMedicalCardNumberInTheSpecifiedRange(int fromNum, int toNum) { | |
| Patients result = new Patients(); | |
| for (Patient patient : listOfPatients) { | |
| if (patient.getMedicalCardNumber() >= fromNum && patient.getMedicalCardNumber() <= toNum) { | |
| result.addPatient(patient); | |
| } | |
| } | |
| return result; | |
| } | |
| @Override | |
| public String toString() { | |
| StringBuilder sb = new StringBuilder(); | |
| for (Patient patient : listOfPatients) { | |
| sb.append(patient.getLastName()).append(" ") | |
| .append(patient.getFirstName()).append(" ") | |
| .append(patient.getMiddleName()).append(", ") | |
| .append(patient.getAddress()).append(", ") | |
| .append(patient.getPhoneNumber()).append(", ") | |
| .append(patient.getMedicalCardNumber()).append(", ") | |
| .append(patient.getDiagnosis()).append("\n"); | |
| } | |
| return sb.toString(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package lesson08HomeWork; | |
| public class Test { | |
| public static void main(String[] args) { | |
| int rowCount = 1; | |
| for (int i = 6; i > 0; i--) { | |
| for (int j = 1; j <= i * 2; j++) { | |
| System.out.print(" "); | |
| } | |
| for (int j = 1; j <= rowCount; j++) { | |
| System.out.print(j + " "); | |
| } | |
| for (int j = rowCount - 1; j >= 1; j--) { | |
| System.out.print(j + " "); | |
| } | |
| System.out.println(); | |
| rowCount++; | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment