mirror of
https://github.com/ASDjonok/OOP_IO-2x_2023.git
synced 2026-04-21 21:34:35 +03:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a81f01103f | |||
| 154398a013 | |||
| 75217080cc | |||
| 90fcc14d7e | |||
| bb5b258ad3 | |||
| 40b2c64883 | |||
| 716b463e99 | |||
| 9112df275b | |||
| 81947f9b29 | |||
| f4fbabe6e5 |
@@ -0,0 +1,2 @@
|
||||
# Project exclude paths
|
||||
/out/
|
||||
Generated
-8
@@ -1,8 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_19" default="true" project-jdk-name="19" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-9
@@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/lab1.iml" filepath="$PROJECT_DIR$/lab1.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/laba3/laba3.iml" filepath="$PROJECT_DIR$/laba3/laba3.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
+10
-10
@@ -1,11 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
@@ -0,0 +1,21 @@
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
float s = 0.0f, a = 2.0f, b = 1.0f, m = 6.0f, n = 4.0f;
|
||||
int c = 1;
|
||||
|
||||
for (float i = a; i <= m; i++) {
|
||||
// Перевірка ділення на 0.
|
||||
if (i == -1) {
|
||||
System.out.println("Помилка: ділення на нуль не можливе.");
|
||||
return;
|
||||
}
|
||||
for (float j = b; j <= n; j++) {
|
||||
s += (i + j) / (i + c);
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("S = " + s);
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
@@ -1,11 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
@@ -0,0 +1,59 @@
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Створення матриць.
|
||||
char[][] a = {
|
||||
{12, 4, 8, 11},
|
||||
{16, 9, 3, 13},
|
||||
{7, 11, 16, 15}
|
||||
};
|
||||
char[][] b = {
|
||||
{15, 12, 4, 5},
|
||||
{19, 1, 3, 11},
|
||||
{2, 11, 6, 10}
|
||||
};
|
||||
|
||||
System.out.println("Матриця A: ");
|
||||
for (char[] i : a) {
|
||||
for (char j : i) {
|
||||
/* При виведенні елементів ми додаємо пробіли на кінці
|
||||
цілого числа (%-4d) задля легшого читання матриці.
|
||||
*/
|
||||
System.out.printf("%-4d", (int) j);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
System.out.println("\nМатриця B: ");
|
||||
for (char[] i : b) {
|
||||
for (char j : i) {
|
||||
System.out.printf("%-4d", (int) j);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
// Перевірка на те, чи є матриці однакових форм.
|
||||
if (a[0].length != b[0].length || a.length != b.length) {
|
||||
System.out.println("Матриці А і В мають різні форми.");
|
||||
} else {
|
||||
int[][] c = new int[a.length][a[0].length];
|
||||
float sum = 0;
|
||||
|
||||
System.out.println("\nМатриця С: ");
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
for (int j = 0; j < a[i].length; j++) {
|
||||
|
||||
c[i][j] = (byte) a[i][j] ^ (byte) b[i][j];
|
||||
sum += c[i][j];
|
||||
System.out.printf("%-4d", c[i][j]);
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
float average = sum / (c.length * c[0].length);
|
||||
System.out.printf("\nСереднє значення матриці С: %.3f", average);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
@@ -0,0 +1,54 @@
|
||||
import java.util.Arrays;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
StringBuffer text = new StringBuffer(scanner.nextLine());
|
||||
String str_text = text.toString();
|
||||
// Заміна ? й ! на .
|
||||
str_text = str_text.replaceAll("[?!]", ".");
|
||||
// Очищення від спеціальних символів.
|
||||
str_text = str_text.replaceAll("\"", "");
|
||||
str_text = str_text.replaceAll("-", "");
|
||||
str_text = str_text.replaceAll("[,':;^*&%$#@]", "");
|
||||
// Створення масиву з речень.
|
||||
String[] spl_text = str_text.split("\\.");
|
||||
|
||||
// Перевірка на кількість речень.
|
||||
if (spl_text.length == 0 || spl_text.length == 1) {
|
||||
System.out.println("Не вдалося виконати дію з рядками (було введено одне речення або взагалі нічого)");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("Слова першого речення, яких немає у жодному з наступних:");
|
||||
for (String st : spl_text[0].split(" ")) {
|
||||
int index = 0;
|
||||
for (int i = 1; i < spl_text.length; i++) {
|
||||
// Усунення кейсу з регістром, усунення пробілів.
|
||||
if (Arrays.asList(spl_text[i].toLowerCase().trim().split(" ")).contains(st.trim().toLowerCase())) {
|
||||
index = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Перевірка на те, чи було дане слово хоча б в одному реченні.
|
||||
if (index == 0) {
|
||||
System.out.println(st.trim().toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/* [Input]
|
||||
"У молодості я взяв собі за правило не пити ні краплі спиртного до обіду. Тепер, коли я вже немолодий, я тримаюся правила не пити ні краплі спиртного до сніданку". - Вінстон Черчилль
|
||||
[Output]
|
||||
у
|
||||
молодості
|
||||
взяв
|
||||
собі
|
||||
за
|
||||
правило
|
||||
обіду
|
||||
*/
|
||||
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,40 @@
|
||||
package lab4;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Створення об'єктів класу Student.
|
||||
Student First = new Student("Михайло", "Гордун", 21, "ІПСА", true);
|
||||
Student Second = new Student("Дмитро", "Шарій", 19, "ТЕФ", false);
|
||||
Student Third = new Student("Аліна", "Шарій", 18, "ЕФ", false);
|
||||
Student Fourth = new Student("Назар", "Лоленко", 17, "ФІОТ", true);
|
||||
Student Fifth = new Student("Олександра", "Зеленська", 18, "ФМВ", true);
|
||||
|
||||
// Створення масиву об'єктів класу Student.
|
||||
Student[] ObjArray = new Student[] {First, Second, Third, Fourth, Fifth};
|
||||
|
||||
// Сортування по алфавіту (прізвище ім'я).
|
||||
Arrays.sort(ObjArray, new Sorting.SortByAlphabet());
|
||||
System.out.println("\nСортування за алфавітом (зростання):");
|
||||
for (Student Student : ObjArray) {
|
||||
System.out.println(Student.lastName + " " + Student.firstName);
|
||||
}
|
||||
|
||||
/* Сортування по віці (спадання).
|
||||
Масив сортує масив по зростанню, але в циклі ітерація
|
||||
проходить навпаки, тим самим виводячи елементи з кінця
|
||||
до початку.
|
||||
*/
|
||||
Arrays.sort(ObjArray, new Sorting.SortByAge());
|
||||
System.out.println("\nСортування за віком (спадання):");
|
||||
for (int i = ObjArray.length-1; i >= 0; i--) {
|
||||
System.out.print(ObjArray[i].lastName + " ");
|
||||
System.out.print(ObjArray[i].firstName);
|
||||
System.out.println(", вік: " + ObjArray[i].age);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package lab4;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class Sorting {
|
||||
|
||||
// Непорушний клас, створений на основі абстратного класу Comparator.
|
||||
public static class SortByAlphabet implements Comparator<Student> {
|
||||
|
||||
/* Реалізація методу compare().
|
||||
Метод compare(Object o1, Object 02) є одним із абстрактних методів
|
||||
класу Comparator. Нам потрібно або зробити наш клас абстактним, або
|
||||
реалізувати даний метод. Якщо ж оголосити клас SortByAlphabet
|
||||
абстрактним, ми не зможемо створити на основі його об'єкт, тому
|
||||
вибір очевидний - реалізація методу.
|
||||
*/
|
||||
@Override
|
||||
public int compare(Student st1, Student st2) {
|
||||
/* Якщо в нас буде 2 однакових прізвища на порівняння, нам потрібно
|
||||
порівнювати імена аби сортування по алфавіту було правильним.
|
||||
*/
|
||||
if (st1.lastName.compareTo(st2.lastName) == 0) {
|
||||
return st1.firstName.compareTo(st2.firstName);
|
||||
} else {
|
||||
return st1.lastName.compareTo(st2.lastName);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Непорушний клас, створений на основі абстратного класу Comparator.
|
||||
public static class SortByAge implements Comparator<Student> {
|
||||
|
||||
// Аналогічно тут, реалізуємо метод compare().
|
||||
@Override
|
||||
public int compare(Student st1, Student st2) {
|
||||
/* Метод compareTo() приймає лише дані типу String, тому
|
||||
ми перетворюємо вік з int в String. Звісно ж це може привести
|
||||
до неточності. Числа будуть порівнюватись спочатку по перших
|
||||
цифрах, потім по других і тд. Якщо в нас буде, наприклад вік
|
||||
107 і 18 на порівнянні, прогрма порахує, що 18 > 107 по
|
||||
порядку. Тут цим знехтується, адже я сумніваюсь що існують
|
||||
студенти яким >100 років.
|
||||
*/
|
||||
String age1 = Integer.toString(st1.age);
|
||||
String age2 = Integer.toString(st2.age);
|
||||
return age1.compareTo(age2);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package lab4;
|
||||
|
||||
public class Student {
|
||||
|
||||
// Створення полів класу.
|
||||
public String firstName;
|
||||
public String lastName;
|
||||
public int age;
|
||||
private String faculty;
|
||||
private boolean hasStipend;
|
||||
|
||||
// Конструктор класу.
|
||||
public Student(String fn, String ln, int age, String fac, boolean wealth) {
|
||||
setValues(fn, ln, age, fac, wealth);
|
||||
getValues();
|
||||
}
|
||||
|
||||
/* Метод, який нічого не повертає.
|
||||
Визначає поля класу.
|
||||
*/
|
||||
private void setValues(String fn, String ln, int age, String fac, boolean wealth) {
|
||||
this.firstName = fn;
|
||||
this.lastName = ln;
|
||||
this.age = age;
|
||||
this.faculty = fac;
|
||||
this.hasStipend = wealth;
|
||||
}
|
||||
|
||||
/* Метод, який нічого не повертає.
|
||||
Виводить значення полів.
|
||||
*/
|
||||
private void getValues() {
|
||||
System.out.println("Прізвище та ім'я: " + this.lastName + " " + this.firstName);
|
||||
System.out.println("Вік: " + this.age);
|
||||
System.out.println("Факультет: " + this.faculty);
|
||||
System.out.print("Наявність стипендії: ");
|
||||
if (this.hasStipend)
|
||||
System.out.println("є");
|
||||
else
|
||||
System.out.println("немає");
|
||||
System.out.println("~".repeat(40));
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
@@ -1,38 +0,0 @@
|
||||
public class Letter {
|
||||
// Поле що містить літеру
|
||||
private char simbol;
|
||||
// Конструктор
|
||||
public Letter(char simbol) {
|
||||
this.simbol = simbol;
|
||||
}
|
||||
// Метод повернення літери
|
||||
public char getLetter(){
|
||||
return simbol;
|
||||
}
|
||||
// Метод перевірки на те, чи є буква пробілом
|
||||
public boolean isSpace(){
|
||||
if(this.simbol==' '){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Метод перевірки на те, чи є буква комою
|
||||
public boolean isKome(){
|
||||
if(this.simbol==','){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Метод перевірки на те, чи є буква тире
|
||||
public boolean isDash(){
|
||||
if(this.simbol=='-'){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Метод виводу літери
|
||||
public void printLetter(){
|
||||
System.out.print(simbol);
|
||||
}
|
||||
|
||||
}
|
||||
-188
@@ -1,188 +0,0 @@
|
||||
import java.util.*;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
// Ввід текста користувачем
|
||||
System.out.println("Введіть текст:");
|
||||
Scanner scan = new Scanner(System.in);
|
||||
String inputText1 = scan.nextLine();
|
||||
// Заміна табуляцій на пробіли
|
||||
String inputText = inputText1.replace("\n", " ");
|
||||
// Перехід від формату String до формату Text
|
||||
Text text = FromStringToText(inputText);
|
||||
// Зміна порядку слів в реченні
|
||||
text.changeOrder();
|
||||
// Вивід результату
|
||||
text.printText();
|
||||
}
|
||||
// Метод переходу від String до Text
|
||||
public static Text FromStringToText(String text) {
|
||||
// Створюємо массив char з двома пробілами в кінці
|
||||
char[] chars1 = text.toCharArray();
|
||||
char[] chars = Arrays.copyOf(chars1, chars1.length + 2);
|
||||
chars[chars.length-2]=' ';
|
||||
chars[chars.length-1]=' ';
|
||||
// Створюємо массив, який буде містити літери і знаки
|
||||
ArrayList<Object> modifiedText = new ArrayList<>();
|
||||
// Змінна, яка буде контролювати наявність знаків в тексті
|
||||
int k = 0;
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
if (chars[i] == '!' || chars[i] == '?' || chars[i] == '.') {
|
||||
if (chars[i + 1] == '!' || chars[i + 1] == '?' || chars[i + 1] == '.') {
|
||||
if (chars[i + 1 + 1] == '!' || chars[i + 1 + 1] == '?' || chars[i + 1 + 1] == '.') {
|
||||
// Якщо в тексті трапляється знак, який складається відразу з трьох знаків, то програма зараховує його як один і додає в массив з літерами і знаками
|
||||
ArrayList<Character> znaki = new ArrayList<>();
|
||||
znaki.add(chars[i]);
|
||||
znaki.add(chars[i + 1]);
|
||||
znaki.add(chars[i + 1 + 1]);
|
||||
Znak element = new Znak(znaki);
|
||||
// Додаємо до лічильника два, щоб цикл не обробляв знаки ще раз
|
||||
i = i + 1 + 1;
|
||||
modifiedText.add(element);
|
||||
k = k + 1;
|
||||
} else {
|
||||
// Якщо в тексті трапляється знак, який складається відразу з двох знаків, то програма зараховує його як один і додає в массив з літерами і знаками
|
||||
ArrayList<Character> znaki = new ArrayList<>();
|
||||
znaki.add(chars[i]);
|
||||
znaki.add(chars[i + 1]);
|
||||
Znak element = new Znak(znaki);
|
||||
// Додаємо до лічильника один, щоб цикл не обробляв знаки ще раз
|
||||
i = i + 1;
|
||||
modifiedText.add(element);
|
||||
k = k + 1;
|
||||
}
|
||||
|
||||
} else {
|
||||
// Якщо в тексті трапився один розділовий знак, то він додається до масиву з літер і знаків
|
||||
ArrayList<Character> znaki = new ArrayList<>();
|
||||
znaki.add(chars[i]);
|
||||
Znak element = new Znak(znaki);
|
||||
modifiedText.add(element);
|
||||
k = k + 1;
|
||||
}
|
||||
|
||||
} else {
|
||||
// Якщо елмент массиву chars не виявився знаком, то він додається як літера
|
||||
Letter element = new Letter(chars[i]);
|
||||
modifiedText.add(element);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
// Якщо знаків в тексті не було, програма закінчує роботу
|
||||
if (k == 0) {
|
||||
System.out.println("В вашому тексті нема жодного речення!");
|
||||
System.exit(0);
|
||||
}
|
||||
// Змінна яка буде нижнею межею для зрізання слова
|
||||
int l = 0;
|
||||
// Масиви для створення речень і тексту відповідно
|
||||
ArrayList<Word> sent = new ArrayList<Word>();
|
||||
ArrayList<Sentence> tex = new ArrayList<Sentence>();
|
||||
for (int i = 0; i < modifiedText.size(); i++) {
|
||||
// Створюємо змінні, які містять даний елемент масиву і минулий
|
||||
Object x = modifiedText.get(i);
|
||||
Object x1 = new Object();
|
||||
if (i > 0) {
|
||||
x1 = modifiedText.get(i - 1);
|
||||
}
|
||||
// Перевірка чи є елемент літерою
|
||||
if (x instanceof Letter) {
|
||||
// Переходимо до класу Letter
|
||||
Letter z = (Letter) x;
|
||||
Letter y = new Letter(' ');
|
||||
if (i > 0) {
|
||||
y = (Letter) x1;
|
||||
}
|
||||
// Перевірка чи є елемент комою
|
||||
if (z.isKome()) {
|
||||
// Створення слова з всіх елементів, що були до коми і додавання його до речення
|
||||
List<Object> wor1 = modifiedText.subList(l, i);
|
||||
ArrayList<Letter> word = new ArrayList<>();
|
||||
for (Object j : wor1) {
|
||||
Letter let = (Letter) j;
|
||||
word.add(let);
|
||||
}
|
||||
Word w = new Word(word);
|
||||
sent.add(w);
|
||||
// Зсув границі
|
||||
l = i + 1;
|
||||
// Додавання коми до речення
|
||||
ArrayList<Letter> kome = new ArrayList<>();
|
||||
kome.add(z);
|
||||
Word Kome = new Word(kome);
|
||||
sent.add(Kome);
|
||||
|
||||
|
||||
}
|
||||
// Перевірка чи є літера пробілом
|
||||
if (z.isSpace()) {
|
||||
// Перевірка чи є минулий символ комою
|
||||
if (y.isKome() || y.isDash()) {
|
||||
// Додавання пробілу до речення і зсув границі
|
||||
ArrayList<Letter> word1 = new ArrayList<>();
|
||||
word1.add(z);
|
||||
Word word = new Word(word1);
|
||||
sent.add(word);
|
||||
l = i + 1;
|
||||
} else {
|
||||
// Створення слова з всіх елементів, що були до пробіла і додавання його до речення
|
||||
List<Object> word1 = modifiedText.subList(l, i);
|
||||
ArrayList<Letter> word = new ArrayList<>();
|
||||
for (Object j : word1) {
|
||||
Letter let = (Letter) j;
|
||||
word.add(let);
|
||||
}
|
||||
Word w = new Word(word);
|
||||
sent.add(w);
|
||||
// Додавання пробілу до речення
|
||||
ArrayList<Letter> space = new ArrayList<>();
|
||||
space.add(z);
|
||||
Word Space = new Word(space);
|
||||
sent.add(Space);
|
||||
// Зсув границі
|
||||
l = i + 1;
|
||||
}
|
||||
}
|
||||
// Перевірка чи є елемент тире
|
||||
if (z.isDash()) {
|
||||
if (y.isSpace()) {
|
||||
// Якщо минулий елемент був пробілом, тире додається до речення
|
||||
ArrayList<Letter> word1 = new ArrayList<>();
|
||||
word1.add(z);
|
||||
Word word = new Word(word1);
|
||||
sent.add(word);
|
||||
l = i + 1;
|
||||
}
|
||||
}
|
||||
} else if (x instanceof Znak) {
|
||||
// Коли елемент є знаком, то створюється речення, яке додається до тексту
|
||||
List<Object> word1 = modifiedText.subList(l, i);
|
||||
ArrayList<Letter> word = new ArrayList<>();
|
||||
for (Object j : word1) {
|
||||
Letter let = (Letter) j;
|
||||
word.add(let);
|
||||
}
|
||||
Word w = new Word(word);
|
||||
sent.add(w);
|
||||
Znak z = (Znak) x;
|
||||
int jump = 2;
|
||||
// Зсув границі і лічильника
|
||||
l = i+jump;
|
||||
i = i + z.Lenght();
|
||||
|
||||
z.addSpace();
|
||||
|
||||
Sentence sentence = new Sentence(sent, z);
|
||||
tex.add(sentence);
|
||||
// Очищення речення
|
||||
sent= new ArrayList<>();
|
||||
}
|
||||
|
||||
}
|
||||
// Створення і повернення тексту
|
||||
Text text2 = new Text(tex);
|
||||
text2.printText();
|
||||
return text2;
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Sentence {
|
||||
// Поля, що містять речення
|
||||
private ArrayList<Word> words;
|
||||
private Znak znak;
|
||||
// Конструктор класу
|
||||
public Sentence(ArrayList<Word> words, Znak znak){
|
||||
this.words = words;
|
||||
this.znak = znak;
|
||||
|
||||
}
|
||||
// Метод заміни першого слова на останнє
|
||||
public void ChangeOrder(){
|
||||
//Отримуємо перше і останнє слово речення
|
||||
Word FirstWord = words.get(0);
|
||||
Word LastWord = words.get(words.size()-1);
|
||||
//Використовуємо метод ChangeRegistr класу word
|
||||
FirstWord.ChangeRegistr(false);
|
||||
LastWord.ChangeRegistr(true);
|
||||
//Вставляємо в речення
|
||||
words.set(0, LastWord);
|
||||
words.set(words.size()-1, FirstWord);
|
||||
}
|
||||
// Метод виводу речення
|
||||
public void printSentence(){
|
||||
for(Word i:words){
|
||||
i.printWord();
|
||||
}
|
||||
znak.printZnak();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Text {
|
||||
// Поле що містить текст
|
||||
private ArrayList<Sentence> sentences;
|
||||
// Конструктор класу
|
||||
public Text(ArrayList<Sentence> sentences){
|
||||
this.sentences = sentences;
|
||||
}
|
||||
// Метод виводу текста
|
||||
public void printText(){
|
||||
for(Sentence i:sentences){
|
||||
i.printSentence();
|
||||
}
|
||||
}
|
||||
// Метод повернення довжини тексту
|
||||
|
||||
public int Lenght(){
|
||||
return sentences.size();
|
||||
}
|
||||
// Метод зміни порядку слів у тексті
|
||||
public void changeOrder(){
|
||||
for(Sentence i: sentences){
|
||||
i.ChangeOrder();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Word {
|
||||
// Поле, що містить слово
|
||||
private ArrayList<Letter> letters;
|
||||
// Конструктор класу
|
||||
public Word(ArrayList<Letter> letters){
|
||||
this.letters = letters;
|
||||
}
|
||||
// Метод зміни регістру першої літери слова
|
||||
public void ChangeRegistr(boolean loh /*low or high?*/) {
|
||||
Letter FirstLetter = letters.get(0);
|
||||
char Let = FirstLetter.getLetter();
|
||||
// В залежності від значення змінної loh літера змінюється або в нижній або в верхній регістр
|
||||
if(loh==true){
|
||||
Let = Character.toUpperCase(Let);
|
||||
} else {
|
||||
Let = Character.toLowerCase(Let);
|
||||
}
|
||||
letters.set(0, new Letter(Let));
|
||||
}
|
||||
// Метод виводу слова
|
||||
public void printWord(){
|
||||
for(Letter i:letters){
|
||||
i.printLetter();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Znak {
|
||||
// Поле, що містить знак
|
||||
private ArrayList<Character> simbols;
|
||||
// Конструктор класу
|
||||
public Znak(ArrayList<Character> simbols) {
|
||||
this.simbols = simbols;
|
||||
}
|
||||
// Метод визначення довжини знаку
|
||||
public int Lenght(){
|
||||
int x = simbols.size();
|
||||
return x;
|
||||
}
|
||||
// Метод виводу знаку
|
||||
public void printZnak(){
|
||||
for(Character i:simbols){
|
||||
System.out.print(i);
|
||||
}
|
||||
}
|
||||
// Метод додавання пробілу в кінці знаку
|
||||
|
||||
public void addSpace(){
|
||||
simbols.add(' ');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
package lab5;
|
||||
|
||||
public record Letter(char value) {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package lab5;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String inputText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor dictum velit, vitae sollicitudin mauris facilisis et. Praesent mi odio, pretium eget sem ac, ultricies eleifend elit. Maecenas vulputate efficitur risus, a ornare lorem sollicitudin vitae. Pellentesque rhoncus posuere risus eu placerat. Maecenas luctus felis ac interdum sodales. Quisque nec est lectus.";
|
||||
|
||||
// Створений Text об'єкт
|
||||
Text text = new Text(inputText);
|
||||
|
||||
// Пошук у першому реченні слів, яких немає в наступних реченнях
|
||||
List<String> result = findUniqueWords(text);
|
||||
System.out.println("Unique words in the first sentence: " + result);
|
||||
}
|
||||
|
||||
public static List<String> findUniqueWords(Text text) {
|
||||
if (text.getSentences().isEmpty()) {
|
||||
throw new IllegalArgumentException("Text must contain at least one sentence.");
|
||||
}
|
||||
|
||||
Sentence firstSentence = text.getSentences().get(0);
|
||||
List<String> wordsInFirstSentence = firstSentence.getStringWords();
|
||||
|
||||
Set<String> uniqueWords = new HashSet<>(wordsInFirstSentence);
|
||||
|
||||
for (int i = 1; i < text.getSentences().size(); i++) {
|
||||
Sentence sentence = text.getSentences().get(i);
|
||||
List<String> wordsInCurrentSentence = sentence.getStringWords();
|
||||
|
||||
wordsInCurrentSentence.forEach(uniqueWords::remove);
|
||||
}
|
||||
|
||||
return new ArrayList<>(uniqueWords);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package lab5;
|
||||
|
||||
public record Punctuation(char value) {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package lab5;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Sentence {
|
||||
private final List<Object> wordsAndPunctuations;
|
||||
|
||||
public Sentence(String stringSentence) {
|
||||
List<Object> wordsAndPunctuations = new ArrayList<>();
|
||||
StringBuilder word = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < stringSentence.length(); i++) {
|
||||
char ch = stringSentence.charAt(i);
|
||||
|
||||
if (Character.isLetterOrDigit(ch)) {
|
||||
word.append(ch);
|
||||
} else if (Character.isWhitespace(ch)) {
|
||||
if (word.length() > 0) {
|
||||
wordsAndPunctuations.add(new Word(word.toString()));
|
||||
word.setLength(0);
|
||||
}
|
||||
} else if (String.valueOf(ch).matches(".*\\p{Punct}.*")) {
|
||||
if (word.length() > 0) {
|
||||
wordsAndPunctuations.add(new Word(word.toString()));
|
||||
word.setLength(0);
|
||||
}
|
||||
wordsAndPunctuations.add(new Punctuation(ch));
|
||||
}
|
||||
}
|
||||
|
||||
if (word.length() > 0) {
|
||||
wordsAndPunctuations.add(new Word(word.toString()));
|
||||
}
|
||||
|
||||
this.wordsAndPunctuations = wordsAndPunctuations;
|
||||
}
|
||||
|
||||
public List<Object> getWordsAndPunctuations() {
|
||||
return wordsAndPunctuations;
|
||||
}
|
||||
|
||||
|
||||
public List<Word> extractWords() {
|
||||
List<Word> words = new ArrayList<>();
|
||||
for (Object element : getWordsAndPunctuations()) {
|
||||
if (element instanceof Word) {
|
||||
words.add((Word) element);
|
||||
}
|
||||
}
|
||||
return words;
|
||||
}
|
||||
|
||||
public List<String> getStringWords() {
|
||||
List<String> wordStrings = new ArrayList<>();
|
||||
for (Word word : extractWords()) {
|
||||
wordStrings.add(word.getStringWord());
|
||||
}
|
||||
return wordStrings;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package lab5;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Text {
|
||||
private final List<Sentence> sentences;
|
||||
|
||||
public Text(String stringText) {
|
||||
this.sentences = new ArrayList<>();
|
||||
String[] splitText = stringText.split("(?<=[!.?])\\s*");
|
||||
for (String sentence : splitText) {
|
||||
getSentences().add(new Sentence(sentence));
|
||||
}
|
||||
}
|
||||
|
||||
public List<Sentence> getSentences() {
|
||||
return sentences;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package lab5;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Word {
|
||||
private final String stringWord;
|
||||
private final List<Letter> letters;
|
||||
|
||||
public Word(String stringWord) {
|
||||
List<Letter> letters = new ArrayList<>();
|
||||
char[] chars = stringWord.toCharArray();
|
||||
for (char c : chars) {
|
||||
letters.add(new Letter(c));
|
||||
}
|
||||
this.letters = letters;
|
||||
this.stringWord = stringWord;
|
||||
}
|
||||
|
||||
public List<Letter> getLetters() {
|
||||
return letters;
|
||||
}
|
||||
|
||||
public String getStringWord() {
|
||||
return stringWord;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,17 @@
|
||||
package lab6;
|
||||
|
||||
public class Bmw extends Car {
|
||||
|
||||
public String mark = "BMW";
|
||||
|
||||
public Bmw(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
super(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValues() {
|
||||
System.out.println("Марка: BMW");
|
||||
super.printValues();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package lab6;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public class Car {
|
||||
|
||||
protected String _model;
|
||||
protected float speed;
|
||||
protected int price;
|
||||
protected int year;
|
||||
protected float fuel;
|
||||
protected float engineCapacity;
|
||||
protected String country;
|
||||
|
||||
public Car(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
setValues(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
printValues();
|
||||
}
|
||||
|
||||
public void setValues(String _m, float s, int p, int y, float f, float e, String c) {
|
||||
this._model = _m;
|
||||
this.speed = s;
|
||||
this.price = p;
|
||||
this.year = y;
|
||||
this.fuel = f;
|
||||
this.engineCapacity = e;
|
||||
this.country = c;
|
||||
}
|
||||
|
||||
public void printValues() {
|
||||
System.out.println("Модель: " + _model + " " + year);
|
||||
System.out.println("Максимальна швидкість: " + speed + "км/год");
|
||||
System.out.println("Ціна: " + price + "$");
|
||||
System.out.println("Витрати палива: " + fuel + "л/100км");
|
||||
System.out.println("Об'єм двигуна: " + engineCapacity);
|
||||
System.out.println("Країна-виробник: " + country);
|
||||
System.out.println("~".repeat(40));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package lab6;
|
||||
|
||||
public class Ford extends Car {
|
||||
|
||||
public String mark = "Ford";
|
||||
|
||||
public Ford(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
super(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValues() {
|
||||
System.out.println("Марка: Ford");
|
||||
super.printValues();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package lab6;
|
||||
|
||||
public class Lexus extends Car {
|
||||
|
||||
public String mark = "Lexus";
|
||||
|
||||
public Lexus(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
super(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValues() {
|
||||
System.out.println("Марка: Lexus\nМатеринська компанія: Toyota");
|
||||
super.printValues();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package lab6;
|
||||
|
||||
/*
|
||||
Номер заліковї книжки - 2518.
|
||||
|
||||
Завдання:
|
||||
9)Визначити ієрархію легкових автомобілів. Створити таксопарк.
|
||||
Порахувати вартість автопарку. Провести сортування автомобілів
|
||||
парку за витратами палива. Знайти автомобіль у компанії, що
|
||||
відповідає заданому діапазону швидкості автомобіля.
|
||||
*/
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(" ".repeat(15) + "Таксопарк" + " ".repeat(15));
|
||||
System.out.println("~".repeat(40));
|
||||
|
||||
Volkswagen Car1 = new Volkswagen("Golf 4", 224, 5000, 2001, 6.8f, 1.6f, "Німеччина");
|
||||
Volkswagen Car2 = new Volkswagen("Passat", 240, 15000, 2007, 7.0f, 2.0f, "Німеччина");
|
||||
Toyota Car3 = new Toyota("Prius", 231, 12500, 2014, 4.3f, 1.8f, "Японія");
|
||||
Peguot Car4 = new Peguot("308", 220, 12000, 2007, 6.1f, 1.6f, "Франція");
|
||||
Lexus Car5 = new Lexus("LS", 250, 80000, 2022, 10.9f, 3.5f, "Японія");
|
||||
Skoda Car6 = new Skoda("Octavia", 220, 25000, 2022, 6.2f, 1.5f, "Чехія");
|
||||
Ford Car7 = new Ford("Focus", 242, 7800, 2014, 6.9f, 2.0f, "США");
|
||||
Bmw Car8 = new Bmw("5-Series", 250, 50000, 2018, 8.3f, 3.0f, "Німеччина");
|
||||
Car[] CarList = new Car[] {Car1, Car2, Car3, Car4, Car5, Car6, Car7, Car8};
|
||||
/*
|
||||
Використовується лямбда функція, щоб описати компаратор в Arrays.sort().
|
||||
*/
|
||||
java.util.Arrays.sort(CarList, (a, b) -> Float.compare(a.fuel, b.fuel));
|
||||
|
||||
System.out.println("Сортування автомобілів за витратами палива:");
|
||||
for (Car Car : CarList) {
|
||||
System.out.println(Car._model + ": " + Car.fuel + "л/100км");
|
||||
}
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("\nВведіть діапазон швидкості автомобіля:\nвід ");
|
||||
float speed_down = scanner.nextFloat();
|
||||
System.out.print("до ");
|
||||
float speed_up = scanner.nextFloat();
|
||||
System.out.println("Автомобілі із заданою швидкістю:");
|
||||
for (Car Car : CarList) {
|
||||
if ((Car.speed >= speed_down) && (Car.speed <= speed_up)) {
|
||||
|
||||
System.out.println(Car._model + ": " + Car.speed + " км/год");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package lab6;
|
||||
|
||||
public class Peguot extends Car {
|
||||
|
||||
public String mark = "Peguot";
|
||||
|
||||
public Peguot(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
super(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValues() {
|
||||
System.out.println("Марка: Peguot");
|
||||
super.printValues();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package lab6;
|
||||
|
||||
public class Skoda extends Car {
|
||||
|
||||
public String mark = "Skoda";
|
||||
|
||||
public Skoda(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
super(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValues() {
|
||||
System.out.println("Марка: Skoda\nМатеринська компанія: Volkswagen");
|
||||
super.printValues();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package lab6;
|
||||
|
||||
public class Toyota extends Car {
|
||||
|
||||
public String mark = "Toyota";
|
||||
|
||||
public Toyota(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
super(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValues() {
|
||||
System.out.println("Марка: Toyota");
|
||||
super.printValues();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package lab6;
|
||||
|
||||
public class Volkswagen extends Car {
|
||||
|
||||
public String mark = "Volkswagen";
|
||||
|
||||
public Volkswagen(String _model, float speed, int price, int year, float fuel, float engineCapacity, String country) {
|
||||
super(_model, speed, price, year, fuel, engineCapacity, country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValues() {
|
||||
System.out.println("Марка: Volkswagen");
|
||||
super.printValues();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,42 @@
|
||||
package lab7;
|
||||
|
||||
public class Car {
|
||||
|
||||
protected String mark;
|
||||
protected String model;
|
||||
protected int price;
|
||||
protected int year;
|
||||
protected float fuel;
|
||||
|
||||
public Car(String mark, String model, int price, int year, float fuel) {
|
||||
setValues(mark, model, price, year, fuel);
|
||||
}
|
||||
|
||||
// Цей конструктор був створений окремо для класу ElectricCar
|
||||
public Car(String mark, String model, int price, int year) {
|
||||
setValues(mark, model, price, year);
|
||||
}
|
||||
|
||||
public void setValues(String mark, String model, int price, int year, float fuel) {
|
||||
this.mark = mark;
|
||||
this.model = model;
|
||||
this.price = price;
|
||||
this.year = year;
|
||||
this.fuel = fuel;
|
||||
}
|
||||
|
||||
public void setValues(String mark, String model, int price, int year) {
|
||||
this.mark = mark;
|
||||
this.model = model;
|
||||
this.price = price;
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public void printValues() {
|
||||
System.out.println("Марка: " + mark);
|
||||
System.out.println("Модель: " + model + " " + year);
|
||||
System.out.println("Ціна: " + price + "$");
|
||||
System.out.println("Витрати палива: " + fuel + "л/100км");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package lab7;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class CarCollection<T extends Car> implements List<T> {
|
||||
private final LinkedList<T> carList;
|
||||
|
||||
public CarCollection() {
|
||||
carList = new LinkedList<>();
|
||||
}
|
||||
|
||||
public CarCollection(T car) {
|
||||
carList = new LinkedList<>();
|
||||
carList.add(car);
|
||||
}
|
||||
|
||||
public CarCollection(Collection<? extends T> c) {
|
||||
carList = new LinkedList<>(c);
|
||||
}
|
||||
|
||||
// Реалізація методів List
|
||||
@Override
|
||||
public int size() {
|
||||
return carList.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return carList.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
return carList.contains(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<T> iterator() {
|
||||
return carList.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
return carList.toArray();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T1> T1[] toArray(T1[] a) {
|
||||
return carList.toArray(a);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(T t) {
|
||||
return carList.add(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
return carList.remove(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsAll(Collection<?> c) {
|
||||
return carList.containsAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(Collection<? extends T> c) {
|
||||
return carList.addAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(int index, Collection<? extends T> c) {
|
||||
return carList.addAll(index, c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAll(Collection<?> c) {
|
||||
return carList.removeAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainAll(Collection<?> c) {
|
||||
return carList.retainAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
carList.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get(int index) {
|
||||
return carList.get(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T set(int index, T element) {
|
||||
return carList.set(index, element);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(int index, T element) {
|
||||
carList.add(index, element);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T remove(int index) {
|
||||
return carList.remove(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int indexOf(Object o) {
|
||||
return carList.indexOf(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int lastIndexOf(Object o) {
|
||||
return carList.lastIndexOf(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListIterator<T> listIterator() {
|
||||
return carList.listIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListIterator<T> listIterator(int index) {
|
||||
return carList.listIterator(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<T> subList(int fromIndex, int toIndex) {
|
||||
return carList.subList(fromIndex, toIndex);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package lab7;
|
||||
|
||||
public class CombatsCar extends Car {
|
||||
|
||||
private final int crew;
|
||||
private final float weight;
|
||||
private final String country;
|
||||
|
||||
public CombatsCar(String mark, String model, int price, int year, float fuel, int crew, float weight, String country) {
|
||||
super(mark, model, price, year, fuel);
|
||||
this.crew = crew;
|
||||
this.weight = weight;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void printValues() {
|
||||
super.printValues();
|
||||
System.out.println("--- Особливості бойової машини ---");
|
||||
System.out.println("Екіпаж: " + crew + " людей");
|
||||
System.out.println("Бойова маса: " + weight + "т");
|
||||
System.out.println("Країна-виробник: " + country);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package lab7;
|
||||
|
||||
public class ElectricCar extends Car {
|
||||
|
||||
private final float electricity;
|
||||
private final float chargingSpeed;
|
||||
|
||||
public ElectricCar(String mark, String model, int price, int year, float electricity, int chargingSpeed) {
|
||||
super(mark, model, price, year);
|
||||
this.electricity = electricity;
|
||||
this.chargingSpeed = chargingSpeed;
|
||||
}
|
||||
|
||||
public float getElectricity() {
|
||||
return electricity;
|
||||
}
|
||||
|
||||
public void printValues() {
|
||||
super.printValues();
|
||||
System.out.println("-Особливості електрокару-");
|
||||
System.out.println("Споживання електроенергії: " + electricity + " кВт·год/100км");
|
||||
System.out.println("Швидкість зарядки (з 0% до 100%): " + chargingSpeed + " хв");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package lab7;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Використання пустого конструктора CarCollection
|
||||
CarCollection<SportsCar> sportsCars = new CarCollection<>();
|
||||
sportsCars.add(new SportsCar("Ferrari", "458 Italia", 230000, 2015, 9.8f, 562, 202, 4.5f));
|
||||
sportsCars.add(new SportsCar("Lamborghini", "Huracan", 260000, 2020, 9.5f, 640, 211, 5.2f));
|
||||
sportsCars.add(new SportsCar("Porsche", "911", 150000, 2018, 14.3f, 450, 191, 3.0f));
|
||||
sportsCars.add(new SportsCar("McLaren", "570S", 200000, 2017, 11.2f, 562, 204, 3.8f));
|
||||
sportsCars.add(new SportsCar("Aston Martin", "Vantage", 150000, 2021, 12.3f, 503, 195, 4.0f));
|
||||
|
||||
// Сортування спорткарів за ціною
|
||||
System.out.println("~~~~~ Відсортовані спорткари за ціною ~~~~~");
|
||||
sportsCars.sort(Comparator.comparingInt(SportsCar::getPrice));
|
||||
|
||||
for (int i = sportsCars.size() - 1; i >= 0; i--) {
|
||||
sportsCars.get(i).printValues();
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
// Використання конструктора CarCollection з передаванням в його лише один об'єкт
|
||||
CarCollection<CombatsCar> combatsCars = new CarCollection<>(new CombatsCar("Humvee", "M1114", 220000, 1995, 6.5f, 4, 5.5f, "США"));
|
||||
combatsCars.add(new CombatsCar("Puma", "IFV", 3500000, 2010, 10.7f, 6, 31f, "Німеччина"));
|
||||
combatsCars.add(new CombatsCar("Warrior", "IFV", 4500000, 1988, 12.4f, 3, 29f, "Великобританія"));
|
||||
combatsCars.add(new CombatsCar("ZBD", "05", 1200000, 2011, 9.4f, 4, 25f, "Китай"));
|
||||
combatsCars.add(new CombatsCar("VBCI", "IFV", 5000000, 2008, 10.7f, 8, 32f, "Франція"));
|
||||
|
||||
// Пошук бойової машини за країною-виробником
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Введіть країну-виробницю бойової машини: ");
|
||||
String userCountry = scanner.nextLine();
|
||||
|
||||
System.out.println("Результати пошуку:\n");
|
||||
for (CombatsCar car : combatsCars) {
|
||||
if (car.getCountry().equals(userCountry)) {
|
||||
car.printValues();
|
||||
}
|
||||
}
|
||||
|
||||
ArrayList<ElectricCar> electricCarsList = new ArrayList<>();
|
||||
electricCarsList.add(new ElectricCar("Tesla", "Model S", 80000, 2022, 21.5f, 45));
|
||||
electricCarsList.add(new ElectricCar("Chevrolet", "Bolt", 35000, 2021, 28.0f, 60));
|
||||
electricCarsList.add(new ElectricCar("Nissan", "Leaf", 32000, 2021, 24.0f, 40));
|
||||
electricCarsList.add(new ElectricCar("BMW", "i3", 45000, 2021, 19.5f, 30));
|
||||
electricCarsList.add(new ElectricCar("Hyundai", "Kona", 42000, 2022, 22.0f, 50));
|
||||
|
||||
// Використання конструктора CarCollection з передаванням в його колекцію об'єктів
|
||||
CarCollection<ElectricCar> electricCars = new CarCollection<>(electricCarsList);
|
||||
|
||||
// Пошук автомобіля по діапазону споживання електроенергії
|
||||
System.out.println("\nВведіть діапазон споживання електроенергії (кВт·год/100км):");
|
||||
System.out.print("від ");
|
||||
float electricityLowerLimit = scanner.nextFloat();
|
||||
System.out.print("до ");
|
||||
float electricityUpperLimit = scanner.nextFloat();
|
||||
|
||||
System.out.println("Результати пошуку:\n");
|
||||
for (ElectricCar car : electricCars) {
|
||||
if (car.getElectricity() < electricityUpperLimit & car.getElectricity() > electricityLowerLimit) {
|
||||
car.printValues();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package lab7;
|
||||
|
||||
public class SportsCar extends Car {
|
||||
|
||||
private final int power;
|
||||
private final float speed;
|
||||
private final float engineCapacity;
|
||||
|
||||
public SportsCar(String mark, String model, int price, int year, float fuel, int power, float speed, float engineCapacity) {
|
||||
super(mark, model, price, year, fuel);
|
||||
this.power = power;
|
||||
this.speed = speed;
|
||||
this.engineCapacity = engineCapacity;
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void printValues() {
|
||||
super.printValues();
|
||||
System.out.println("-Особливості спорткару-");
|
||||
System.out.println("Потужість: " + power + " кінських сил");
|
||||
System.out.println("Максимальна швидкість: " + speed + " км/год");
|
||||
System.out.println("Об'єм двигуна: " + engineCapacity + "л");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Введіть текст:");
|
||||
Scanner scan = new Scanner(System.in);
|
||||
String inputText = scan.nextLine();
|
||||
StringBuilder text = new StringBuilder(inputText);
|
||||
StringBuilder suz = new StringBuilder();
|
||||
while (true){
|
||||
if(text.isEmpty()){
|
||||
break;
|
||||
}
|
||||
int index1 = text.indexOf(".");
|
||||
int index2 = text.indexOf("!");
|
||||
|
||||
int index3 = text.indexOf("?");
|
||||
|
||||
int index4 = text.indexOf("...");
|
||||
|
||||
int[] array1= {index1, index2, index3, index4};
|
||||
ArrayList<Integer> list = new ArrayList<Integer>();
|
||||
for (int i = 0; i < array1.length; i++) {
|
||||
if (array1[i] >= 0) {
|
||||
list.add(array1[i]);
|
||||
}
|
||||
}
|
||||
int min = Collections.min(list);
|
||||
String rechennya1 = text.substring(0, min);
|
||||
System.out.println(rechennya1);
|
||||
if (rechennya1.contains(" ")){
|
||||
StringBuilder rechennya = new StringBuilder(rechennya1);
|
||||
String firstword1;
|
||||
String secondword1 = text.substring(rechennya.lastIndexOf(" ")+1, rechennya.length());
|
||||
String secondword2;
|
||||
secondword2 = secondword1.substring(0, 1).toUpperCase()+secondword1.substring(1, secondword1.length());
|
||||
StringBuilder secondword = new StringBuilder(secondword2);
|
||||
if(rechennya.charAt(rechennya.indexOf(" ")-1)==','){
|
||||
firstword1 = text.substring(0, rechennya.indexOf(" ")-1);
|
||||
secondword.append(",");
|
||||
}
|
||||
else {
|
||||
firstword1 = text.substring(0, rechennya.indexOf(" "));
|
||||
}
|
||||
|
||||
String firstword2 = firstword1.substring(0, 1).toLowerCase()+firstword1.substring(1, firstword1.length());
|
||||
StringBuilder firstword = new StringBuilder(firstword2);
|
||||
|
||||
|
||||
firstword.insert(0, " ");
|
||||
rechennya.delete(0, rechennya.indexOf(" "));
|
||||
rechennya.insert(0, secondword);
|
||||
rechennya.delete(rechennya.lastIndexOf(" "), rechennya.length());
|
||||
rechennya.append(firstword);
|
||||
if ((index1==index4)&&(index1==min)){
|
||||
rechennya.append(text.substring(min, min+3));
|
||||
rechennya.append(" ");
|
||||
text.delete(0, min+4);
|
||||
}
|
||||
else {
|
||||
rechennya.append(text.substring(min, min+1));
|
||||
rechennya.append(" ");
|
||||
text.delete(0, min+2);
|
||||
}
|
||||
suz.append(rechennya);
|
||||
}
|
||||
else {
|
||||
StringBuilder rechennya = new StringBuilder(rechennya1);
|
||||
if ((index1==index4)&&(index1==min)){
|
||||
rechennya.append(text.substring(min, min+3));
|
||||
rechennya.append(" ");
|
||||
text.delete(0, min+4);
|
||||
}
|
||||
else {
|
||||
rechennya.append(text.substring(min, min+1));
|
||||
rechennya.append(" ");
|
||||
text.delete(0, min+2);
|
||||
}
|
||||
suz.append(rechennya);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
System.out.println(suz);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import java.util.Random;
|
||||
public class Cosmetic {
|
||||
private String name;
|
||||
private int price_in_$;
|
||||
private int health_damage_from1to10;
|
||||
private int attractiveness_from1to10;
|
||||
private int quality_from1to10;
|
||||
private int brightness_from1to10;
|
||||
|
||||
|
||||
public Cosmetic(String name) {
|
||||
Random random = new Random();
|
||||
|
||||
this.name= name;
|
||||
this.price_in_$ = random.nextInt(1000) + 1;;
|
||||
this.health_damage_from1to10 = random.nextInt(11);
|
||||
this.attractiveness_from1to10 = random.nextInt(11);
|
||||
this.quality_from1to10 = random.nextInt(11);
|
||||
this.brightness_from1to10 = random.nextInt(11);
|
||||
}
|
||||
|
||||
public Cosmetic(String name, int price_in_$, int health_damage_from1to10, int attractiveness_from1to10, int quality_from1to10, int brightness_from1to10) {
|
||||
Random random = new Random();
|
||||
this.name= name;
|
||||
this.price_in_$ = price_in_$;
|
||||
this.health_damage_from1to10 = health_damage_from1to10;
|
||||
this.attractiveness_from1to10 = attractiveness_from1to10;
|
||||
this.quality_from1to10 = quality_from1to10;
|
||||
this.brightness_from1to10 = brightness_from1to10;
|
||||
}
|
||||
public int getPrice_in_$() {
|
||||
return price_in_$;
|
||||
}
|
||||
public int getHealth_damage_from1to10() {
|
||||
return health_damage_from1to10;
|
||||
}
|
||||
public int getAttractiveness_from1to10() {
|
||||
return attractiveness_from1to10;
|
||||
}
|
||||
public int getQuality_from1to10() {
|
||||
return quality_from1to10;
|
||||
}
|
||||
public int getBrightness_from1to10() {
|
||||
return brightness_from1to10;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
-235
@@ -1,235 +0,0 @@
|
||||
import java.sql.SQLOutput;
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
int quantity = 0;
|
||||
while (true) {
|
||||
System.out.println("Скільки елементів в масиві ви хочете мати?");
|
||||
try {
|
||||
quantity = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз.");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
Cosmetic[] arr = new Cosmetic[quantity];
|
||||
|
||||
for (int i = 0; i < quantity; i++) {
|
||||
System.out.println("Введіть назву об'єкта №" + (i + 1) + ": ");
|
||||
String name = scanner.next();
|
||||
while (true) {
|
||||
System.out.println("Бажаєте заповнить об'єкт №" + (i + 1) + " випадковими значеннями?(Введіть так або ні)");
|
||||
String anwser = scanner.next();
|
||||
if (anwser.equalsIgnoreCase("так")) {
|
||||
arr[i] = new Cosmetic(name);
|
||||
break;
|
||||
} else {
|
||||
if (anwser.equalsIgnoreCase("ні")) {
|
||||
System.out.println("Добре, задайте дані об'єкта номер" + (i + 1) + ":");
|
||||
int price = 0;
|
||||
|
||||
while (true) {
|
||||
System.out.print("Введіть ціну в долларах: ");
|
||||
try {
|
||||
price = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз.");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int healthDamage = 0;
|
||||
while (true) {
|
||||
System.out.print("Введіть шкоду здоров'ю по шкалі від 0 до 10: ");
|
||||
while (true) {
|
||||
try {
|
||||
healthDamage = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз:");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
if (healthDamage <= 10 && healthDamage >= 0) {
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Помилка! Число знаходиться не в межах від 0 до 10.");
|
||||
}
|
||||
}
|
||||
int attractiveness = 0;
|
||||
while (true) {
|
||||
System.out.print("Введіть привабливість по шкалі від 0 до 10: ");
|
||||
while (true) {
|
||||
try {
|
||||
attractiveness = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз:");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
if (attractiveness <= 10 && attractiveness >= 0) {
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Помилка! Число знаходиться не в межах від 0 до 10.");
|
||||
}
|
||||
}
|
||||
int quality = 0;
|
||||
while (true) {
|
||||
System.out.print("Введіть якість по шкалі від 0 до 10: ");
|
||||
while (true) {
|
||||
try {
|
||||
quality = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз:");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
if (quality <= 10 && quality >= 0) {
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Помилка! Число знаходиться не в межах від 0 до 10.");
|
||||
}
|
||||
}
|
||||
int brightness = 0;
|
||||
while (true) {
|
||||
System.out.print("Введіть яркість по шкалі від 0 до 10: ");
|
||||
while (true) {
|
||||
try {
|
||||
brightness = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз:");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
if (brightness <= 10 && brightness >= 0) {
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Помилка! Число знаходиться не в межах від 0 до 10.");
|
||||
}
|
||||
}
|
||||
|
||||
arr[i] = new Cosmetic(name, price, healthDamage, attractiveness, quality, brightness);
|
||||
break;
|
||||
|
||||
} else {
|
||||
System.out.println("Ви ввели не правильне значення");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("\n\n\n\n");
|
||||
System.out.println("Чудово! Масив з елементами класу створено!");
|
||||
System.out.println("Далі треба задати поля, по яким слід сортувати елементи");
|
||||
System.out.println("Для сортування по ціні введіть - 1");
|
||||
System.out.println("Для сортування по шкоді для здоров'я введіть - 2");
|
||||
System.out.println("Для сортування по привабливосты введіть - 3");
|
||||
System.out.println("Для сортування по якості введіть - 4");
|
||||
System.out.println("Для сортування по яркості введіть - 5\n");
|
||||
|
||||
int num1 = 0;
|
||||
while (true) {
|
||||
System.out.print("Введіть поле масиву від 1 до 5 для сортуванням за зростанням: ");
|
||||
while (true) {
|
||||
try {
|
||||
num1 = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз:");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
if (num1 <= 5 && num1 >= 1) {
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Помилка! Число знаходиться не в межах від 1 до 5.");
|
||||
}
|
||||
}
|
||||
int num2 = 0;
|
||||
while (true) {
|
||||
System.out.print("Введіть поле масиву від 1 до 5 для сортування за спаданням: ");
|
||||
while (true) {
|
||||
try {
|
||||
num2 = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз:");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
if (num2 <= 5 && num2 >= 1) {
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Помилка! Число знаходиться не в межах від 1 до 5.");
|
||||
}
|
||||
}
|
||||
System.out.println("Масив відсортований за зростанням:");
|
||||
if (num1 == 1) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getPrice_in_$));
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getPrice_in_$());
|
||||
}
|
||||
} else if (num1 == 2) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getHealth_damage_from1to10));
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getHealth_damage_from1to10());
|
||||
}
|
||||
} else if (num1 == 3) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getAttractiveness_from1to10));
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getAttractiveness_from1to10());
|
||||
}
|
||||
} else if (num1 == 4) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getQuality_from1to10));
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getQuality_from1to10());
|
||||
}
|
||||
} else if (num1 == 5) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getBrightness_from1to10));
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getBrightness_from1to10());
|
||||
}
|
||||
}
|
||||
System.out.println("Масив відсортований за спаданням:");
|
||||
if (num2 == 1) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getPrice_in_$).reversed());
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getPrice_in_$());
|
||||
}
|
||||
} else if (num2 == 2) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getHealth_damage_from1to10).reversed());
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getHealth_damage_from1to10());
|
||||
}
|
||||
} else if (num2 == 3) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getAttractiveness_from1to10).reversed());
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getAttractiveness_from1to10());
|
||||
}
|
||||
} else if (num2 == 4) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getQuality_from1to10).reversed());
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getQuality_from1to10());
|
||||
}
|
||||
} else if (num2 == 5) {
|
||||
Arrays.sort(arr, Comparator.comparingInt(Cosmetic::getBrightness_from1to10).reversed());
|
||||
for (Cosmetic i : arr) {
|
||||
System.out.println(i.getName() + " - " + i.getBrightness_from1to10());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
|
||||
public class ElectroAppliance {
|
||||
// Поля що містять потужність, електромагнітне випромінювання та назву
|
||||
private int power;
|
||||
private int electromagneticRadiation;
|
||||
private String name;
|
||||
// Статичні поля, які потрібні для зберігання даних про всі об'єкти класу
|
||||
private static int totalPower = 0;
|
||||
private static ArrayList<Integer> sortedPowers = new ArrayList<Integer>();
|
||||
private static ArrayList<String> sortedNames = new ArrayList<String>();
|
||||
private static ArrayList<Integer> electromagneticList = new ArrayList<Integer>();
|
||||
private static ArrayList<String> namesList = new ArrayList<String>();
|
||||
|
||||
|
||||
public ElectroAppliance(int power, int electromagneticRadiation, String name) {
|
||||
// Присвоюємо полям значення
|
||||
this.name = name;
|
||||
this.power = power;
|
||||
this.electromagneticRadiation = electromagneticRadiation;
|
||||
// Додаємо потужність до загальної
|
||||
totalPower = totalPower + power;
|
||||
// Додаємо дані про електромагнітне випромінювання
|
||||
electromagneticList.add(electromagneticRadiation);
|
||||
namesList.add(name);
|
||||
// Відразу в конструкторі сортуємо список з потужностями
|
||||
if (sortedPowers.isEmpty()) {
|
||||
sortedPowers.add(power);
|
||||
sortedNames.add(name);
|
||||
} else {
|
||||
for (int i = sortedNames.size()-1; i>=0; i=i-1) {
|
||||
if(power>sortedPowers.get(i)){
|
||||
sortedPowers.add(i+1, power);
|
||||
sortedNames.add(i+1, name);
|
||||
} else if(i==0&&power<=sortedPowers.get(i)){
|
||||
sortedPowers.add(0, power);
|
||||
sortedNames.add(0, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void printSortedPowers(){
|
||||
for(int i = 0; i<sortedNames.size(); i=i+1){
|
||||
System.out.println(sortedNames.get(i)+": "+ Integer.toString(sortedPowers.get(i))+" Вт");
|
||||
}
|
||||
/** Метод повертає відсортований список приборів по потужності */
|
||||
}
|
||||
|
||||
public static int getTotalPower() {
|
||||
return totalPower;
|
||||
/** Метод повертає загальну потужність*/
|
||||
}
|
||||
public static void printDiapasonedElectromagneticRadiation(int[] limits){
|
||||
// Втсановлюємо границі з отриманого списку
|
||||
int top = limits[1];
|
||||
int bottom = limits[0];
|
||||
// Створюємо списки з кінцевими значеннями
|
||||
ArrayList<Integer> wantedElectromagneticRadiation = new ArrayList<Integer>();
|
||||
ArrayList<String> wantedElectromagneticNames = new ArrayList<String>();
|
||||
// Відбираємо потрібні значення
|
||||
for (int i = 0; i<=electromagneticList.size()-1; i=i+1){
|
||||
if(electromagneticList.get(i)<=top&&electromagneticList.get(i)>=bottom){
|
||||
wantedElectromagneticRadiation.add(electromagneticList.get(i));
|
||||
wantedElectromagneticNames.add(namesList.get(i));
|
||||
}
|
||||
}
|
||||
// Виводимо
|
||||
System.out.println("Шуканий список:");
|
||||
for (int i = 0; i<=wantedElectromagneticRadiation.size()-1; i=i+1){
|
||||
System.out.println(wantedElectromagneticNames.get(i)+": " +Integer.toString(wantedElectromagneticRadiation.get(i))+" Вт");
|
||||
}
|
||||
/** Метод шукає значення випромінювання в данному діапазоні і виводить ці значення */
|
||||
}
|
||||
/** Клас елктроприладів, який має може повертати відсортований список приладів по потужності, загальну потужність і
|
||||
* електромагнітне випромінювання в данному діапазоні
|
||||
*/
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
public class HeatingDevices extends ElectroAppliance {
|
||||
// Поля похідного класу Heating Devices
|
||||
private int heatTransfer;
|
||||
private static int totalHeatTransfer = 0;
|
||||
// Конструктор який задає поля і шукає загальне випромінення тепла
|
||||
public HeatingDevices(int heatTransfer, int power, int electromagneticRadiation, String name) {
|
||||
super(power, electromagneticRadiation, name);
|
||||
this.heatTransfer = heatTransfer;
|
||||
totalHeatTransfer = totalHeatTransfer + heatTransfer;
|
||||
}
|
||||
// Повертає загальне випромінення тепла
|
||||
public static int getTotalHeatTransfer() {
|
||||
return totalHeatTransfer;
|
||||
}
|
||||
/** Похідний класу електроприбору, який ще має поле випромінення тепла*/
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.InputMismatchException;
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Вмикаємо прибори
|
||||
TurnOn();
|
||||
// Виводимо відомості про систему
|
||||
String totalPower = Integer.toString(ElectroAppliance.getTotalPower());
|
||||
System.out.println("Загальна споживана потужість:" + totalPower + " Вт");
|
||||
String totalWater = Integer.toString(WashingMashines.getTotalWaterConsumption());
|
||||
System.out.println("Загальна споживана вода:" + totalWater + " Л");
|
||||
String totalHeat = Integer.toString(HeatingDevices.getTotalHeatTransfer());
|
||||
System.out.println("Загальне виділення тепла:" + totalHeat + " Дж");
|
||||
String totalMech = Integer.toString(MechanicDevices.getTotalMechanicPower());
|
||||
System.out.println("Загальн механічна потужність:" + totalMech + " Вт");
|
||||
System.out.println("-------------------------");
|
||||
//Виводимо сортовані потужності
|
||||
ElectroAppliance.printSortedPowers();
|
||||
System.out.println("-------------------------");
|
||||
//Виводимо електромагнітні випромінювання в шуканому діапазоні
|
||||
ElectroAppliance.printDiapasonedElectromagneticRadiation(getLimits());
|
||||
}
|
||||
|
||||
public static void TurnOn() {
|
||||
|
||||
if (AskTrueOrFalse("Ввімкнути в розетку посудомийну машину(введіть так або ні)?")) {
|
||||
WashingMashines DishWasher = new WashingMashines(11, 1000, 30, "Посудомийна машина");
|
||||
|
||||
}
|
||||
if (AskTrueOrFalse("Ввімкнути в розетку пральну машину(введіть так або ні)?")) {
|
||||
WashingMashines ClothesWasher = new WashingMashines(50, 2000, 10, "Пральна машина");
|
||||
}
|
||||
if (AskTrueOrFalse("Ввімкнути в розетку мікрохвильовку(введіть так або ні)?")) {
|
||||
HeatingDevices MicroWawe = new HeatingDevices(2000, 1100, 10000, "Мікрохвильвка");
|
||||
}
|
||||
if (AskTrueOrFalse("Ввімкнути в розетку духову піч(введіть так або ні)?")) {
|
||||
HeatingDevices Oven = new HeatingDevices(1000, 800, 1000, "Духова піч");
|
||||
}
|
||||
if (AskTrueOrFalse("Ввімкнути в розетку блендер(введіть так або ні)?")) {
|
||||
MechanicDevices Blender = new MechanicDevices(200, 400, 1, "Блендер");
|
||||
}
|
||||
if (AskTrueOrFalse("Ввімкнути в розетку пилосос(введіть так або ні)?")) {
|
||||
MechanicDevices VacuumCleaner = new MechanicDevices(50, 300, 3, "Пилосос");
|
||||
}
|
||||
/**
|
||||
* Цей метод створений для того, щоб запитати у користувача, які він прилади хоче ввімкнути в розетку і потім,
|
||||
* якщо відповідь буде позитивна, створює об'єект цього класу.
|
||||
*/
|
||||
}
|
||||
public static int[] getLimits(){
|
||||
int[] limits = new int[2];
|
||||
while (true) {
|
||||
int low = 0;
|
||||
System.out.println("Введіть нижню границю пошуку");
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
low = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз.");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
System.out.println("Введіть нижню границю пошуку");
|
||||
int top = 0;
|
||||
while (true) {
|
||||
try {
|
||||
top = scanner.nextInt();
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Введені символи не є цілим числом, спробуйте ще раз.");
|
||||
scanner.nextLine();
|
||||
}
|
||||
}
|
||||
if (top >= low) {
|
||||
limits[0]=low;
|
||||
limits[1]=top;
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Нижня границя більна верхньої");
|
||||
}
|
||||
}
|
||||
|
||||
return limits;
|
||||
/**
|
||||
* Цей метод створений для того, щоб запитати у користувача нижню і верхню границю пошуку, і при цьому оброботи
|
||||
* всі можливі помилки, такі як ввід не цілого числа, та перевищення нижньої границі верхньої
|
||||
*/
|
||||
}
|
||||
public static boolean AskTrueOrFalse(String question) {
|
||||
System.out.println(question);
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
boolean x = true;
|
||||
while (true) {
|
||||
String anwser = scanner.nextLine();
|
||||
if (anwser.equalsIgnoreCase("так")) {
|
||||
x = true;
|
||||
break;
|
||||
} else if (anwser.equalsIgnoreCase("ні")) {
|
||||
x = false;
|
||||
break;
|
||||
} else {
|
||||
System.out.println("Ви ввели не правильний текст, спробуйте ще раз");
|
||||
}
|
||||
}
|
||||
return x;
|
||||
}
|
||||
/**
|
||||
* Цей метод створений для того, щоб запитати у користвуча відповідь так або ні. Він приймає текстовий аргумент,
|
||||
* виводить його на екран і очікує ввід. Потім він перевіряє відповіть на рівність "так" або "ні"
|
||||
* і повертає значення true або false.
|
||||
*/
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
public class MechanicDevices extends ElectroAppliance {
|
||||
// Поля похідного класу Mechanic Devices
|
||||
private int mechanicPower;
|
||||
private static int totalMechanicPower = 0;
|
||||
// Конструктор який дає значення полям і шукає загальну механічна потужність
|
||||
public MechanicDevices(int mechanicPower, int power, int electromagneticRadiation, String name) {
|
||||
super(power, electromagneticRadiation, name);
|
||||
this.mechanicPower = mechanicPower;
|
||||
totalMechanicPower = totalMechanicPower + mechanicPower;
|
||||
}
|
||||
// Метод, який повертає загальну механічну потужність
|
||||
|
||||
public static int getTotalMechanicPower() {
|
||||
return totalMechanicPower;
|
||||
}
|
||||
/** Похідний класу електроприбору, який ще має поле механічної потужності */
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
public class WashingMashines extends ElectroAppliance {
|
||||
// Поля похідного класу Washing Machines
|
||||
private int waterConsumption;
|
||||
private static int totalWaterConsumption = 0;
|
||||
// Конструктор який задає поля і шукає загальне споживання води
|
||||
public WashingMashines(int waterConsumption, int power, int electromagneticRadiation, String name) {
|
||||
super(power, electromagneticRadiation, name);
|
||||
this.waterConsumption = waterConsumption;
|
||||
totalWaterConsumption = totalWaterConsumption + waterConsumption;
|
||||
}
|
||||
// Метод що повертає загальне споживання води
|
||||
public static int getTotalWaterConsumption() {
|
||||
return totalWaterConsumption;
|
||||
}
|
||||
/** Похідний класу електроприбору, який ще має поле споживання води */
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1,60 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
import java.util.InputMismatchException;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
System.out.println("Введіть значення n:");
|
||||
double n = 0;
|
||||
try {
|
||||
n = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
System.out.println("Введіть значення m:");
|
||||
double m = 0;
|
||||
try {
|
||||
m = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
System.out.println("Введіть значення a:");
|
||||
double a = 0;
|
||||
try {
|
||||
a = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
System.out.println("Введіть значення b:");
|
||||
double b = 0;
|
||||
try {
|
||||
b = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
if (a > n) {
|
||||
System.out.println("Значення n має бути більшим або рівним a");
|
||||
System.exit(0);
|
||||
}
|
||||
if (b > m) {
|
||||
System.out.println("Значення m має бути більшим або рівним b");
|
||||
System.exit(0);
|
||||
}
|
||||
double s1 = 0;
|
||||
double s2 = 0;
|
||||
|
||||
for (double i = a; i <= n; i++) {
|
||||
for (double j = b; j <= m; j++){
|
||||
// оскільки C дорівнює 0, то можна скоротити i
|
||||
s1=s1+(1/j);
|
||||
}
|
||||
s2=s2+s1;
|
||||
}
|
||||
System.out.println("Результат:" + s2);
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package lab2;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
System.out.println("Введіть значення n:");
|
||||
double n = 0;
|
||||
try {
|
||||
n = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
System.out.println("Введіть значення m:");
|
||||
double m = 0;
|
||||
try {
|
||||
m = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
System.out.println("Введіть значення a:");
|
||||
double a = 0;
|
||||
try {
|
||||
a = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
System.out.println("Введіть значення b:");
|
||||
double b = 0;
|
||||
try {
|
||||
b = scan.nextDouble();
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Число введене не вірно");
|
||||
System.exit(0);
|
||||
}
|
||||
if (a > n) {
|
||||
System.out.println("Значення n має бути більшим або рівним a");
|
||||
System.exit(0);
|
||||
}
|
||||
if (b > m) {
|
||||
System.out.println("Значення m має бути більшим або рівним b");
|
||||
System.exit(0);
|
||||
}
|
||||
double s1 = 0;
|
||||
double s2 = 0;
|
||||
|
||||
for (double i = a; i <= n; i++) {
|
||||
for (double j = b; j <= m; j++){
|
||||
// оскільки C дорівнює 0, то можна скоротити i
|
||||
s1=s1+(1/j);
|
||||
}
|
||||
s2=s2+s1;
|
||||
}
|
||||
System.out.println("Результат:" + s2);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user