Compare commits

...

3 Commits

Author SHA1 Message Date
cvoluj
7424afd92e add lab3 2023-06-09 20:08:36 +03:00
cvoluj
6d106ee74f add lab4, lab6 2023-06-09 20:03:09 +03:00
cvoluj
3cd448eeda added lab 1, lab 2 2023-04-05 21:14:30 +03:00
33 changed files with 932 additions and 474 deletions

2
.idea/misc.xml generated
View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_18" default="true" project-jdk-name="openjdk-18" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_19" default="true" project-jdk-name="openjdk-18" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
</project> </project>

View File

@@ -1,58 +0,0 @@
public class Lab1 {
public static void main(String[] args) {
// char c = 'a' + '1';
char c = 97;
// char c = '1';
System.out.println(c);
System.out.println((int) c);
c++;
System.out.println(c);
System.out.println((int) c);
System.out.println((double)'1'/'3');
// System.out.println( (double) 0 / 0 );
// System.out.println( Math.sqrt(-1) );
double s = 0;
/*for (int i = 1; i <= 3; i++) { // 1) <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> i = 1, 2) <20><><EFBFBD><EFBFBD> <20> <= 3, 3) <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 䳿 <20> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>,
System.out.println(i); // 4) <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><> 1, 5) <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD> 2
// s = s + i;
s += i;
}*/
/*int[] array = new int[2];
for (int i = 0; i < array.length; i++) {
}*/
final int A = -3;
final int B = 0;
final int N = 2;
final int M = 2;
final int C = 1;
// boolean wasDivisionByZero = false;
// todo char
// todo[clear code] think about avoiding brackets
if ((A <= -C && -C <= N) || (B <= 0 && 0 <= M)) {
System.out.println("Division by zero!");
return;
}
/*myLabel:*/for (int i = A; i <= N /*&& !wasDivisionByZero*/; i++) {
/*if (i + C == 0) { // todo optimize
System.out.println("Division by zero!");
wasDivisionByZero = true;
break; //todo flag vs return;
}*/
for (int j = B; j <= M; j++) {
/*if (j == 0) {
System.out.println("Division by zero!");
return;
// wasDivisionByZero = true;
// break myLabel;
}*/
s += (double) (i / j) / (i + C);
}
}
// if (!wasDivisionByZero) {
System.out.println("s = " + s);
// }
}
}

140
src/Lab1/Lab1.java Normal file
View File

@@ -0,0 +1,140 @@
package Lab1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Lab1 {
public static void main(String[] args) {
int C2, C3, C5, C7; // creating variables
int numBook = 2401; // default value of scorebook
Scanner sc = new Scanner(System.in); // scanner creating for inputing values from keyboard
System.out.println("By default number of scorebook is 2401. \nEnter to skip or input new value: ");
String input = sc.nextLine();
if (!input.equals("")) { // try-catch for checking correct inputing of value
try {
numBook = Math.abs(Integer.parseInt(input)); // scorebook can be only unsigned
} catch (NumberFormatException e) {
System.out.println("Invalid input. Using default value 2401"); // printing that will be used default value
}
}
String[] operations1 = {"+", "-"};//
String[] operations2 = {"*", "/", "%", "+", "-"}; // String array for choosing operations
String[] operations3 = {"byte", "short", "int", "long", "char", "float", "double"}; //
// determining variables
C2 = numBook % 2;
C3 = numBook % 3;
C5 = numBook % 5;
C7 = numBook % 7;
String O1 = operations1[C2];
int C = C3;
String O2 = operations2[C5];
String O3 = operations3[C7];
System.out.println("C2 is: " + C2 + ", operation is: " + O1); //
System.out.println("C3 is: " + C); // printing parameters that user got
System.out.println("C5 is: " + C5 + ", operation is: " + O2); //
System.out.println("C7 is: " + C7 + ", Type of indexes i and j is: " + O3); //
Number i = 0; // creating objects i j of (abstract)superclass Number
Number j = 0; //
System.out.println("\nEnter a value for i and j in the " + O3 + " type: ");
switch (O3) { // Choosing type of i and j by C7
case "byte" -> {
try {
i = sc.nextByte();
j = sc.nextByte();
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid byte value.");
sc.nextLine();
}
}
case "short" -> {
i = sc.nextShort();
j = sc.nextShort();
}
case "int" -> {
i = sc.nextInt();
j = sc.nextInt();
}
case "long" -> {
i = sc.nextLong();
j = sc.nextLong();
}
case "char" -> {
System.out.println("Read only first character!");
i = (int) sc.next().charAt(0);
j = (int) sc.next().charAt(0);
}
case "float" -> {
i = sc.nextFloat();
j = sc.nextFloat();
}
case "double" -> {
i = sc.nextDouble();
j = sc.nextDouble();
}
}
System.out.println("The value of the created variables is: " + i + " and " + j);
class Sum { // creating class Sum
int n, m;
double i, j;
public Sum(double i, double j, int n, int m) { // Constructor to initialize all variables
this.i = i;
this.j = j;
this.n = n;
this.m = m;
}
public void calc() { // create method for our class
double sum = 0, result = 0, result2 = 0;
if ((O1.equals("-") && i + n >= C && i <= C) || (C == 0 && i == 0)) { // exclude situations
System.out.println("dividing by zero!"); // with dividing by 0
} else if (i > n || j > m) {
System.out.println("i or j greater than n or m");
} else {
for (double b = i; b <= n; b++) {
for (double a = j; a <= m; a++) {
switch (O2) {
case "+" -> result = b + a;
case "-" -> result = b - a;
case "*" -> result = b * a;
case "/" -> result = b / a;
case "%" -> result = b % a;
}
switch (O1) {
case "+" -> result2 = b + C;
case "-" -> result2 = b - C;
}
sum += result / result2;
}
}
System.out.println("Sum is: " + sum);
}
}
}
System.out.print("Enter value for n and m: \n");
int n = sc.nextInt();
int m = sc.nextInt();
Sum sum = new Sum(i.doubleValue(), j.doubleValue(), n, m); // creating new instance of Sum class
// .doubleValue() converting our variables to double
sum.calc();
sc.close();
}
}

View File

@@ -1,102 +0,0 @@
public class Lab2 {
public static void main(String[] args) {
final int A = 2;
final int[][] MATRIX_B = {
{1, 202, 1, 1, 202, 3, 1, 202, 3,},
{1, 202, 1, 1, 202, 3, 1, 202, 3,},
{1, 1, 3, 1, 202, 3, 1, 202, 3,},
// {4, 5, 6,},
};
int[][] MATRIX_C = multiplication(A, MATRIX_B);
print(MATRIX_C);
System.out.println("Sum of smallest elements in every column: " + sumOfSmallestElementsInEveryColumn(MATRIX_C));
/*int[] array = {1, 2, 3};
int[] array2 = new int[3];
Object[] array3 = new String[3];
System.out.println(array3[0]); //nothing, trash from the memory, null || null
System.out.println(array2[0]); //nothing, trash from the memory, null || 0
System.out.println(array[0]); // || 1
int[][] matrix2 = new int[2][3];
matrix2[0] = new int[2];
matrix2[1] = new int[1];
for (int i = 0; i < array.length; i++) {
if (i % 2 == 0) {
System.out.println("!" + array[i]);
} else {
System.out.println("?" + array[i]);
}
}
for (int i = 0; i < array.length; i+=2) {
System.out.println("!" + array[i]);
}
for (int i = 1; i < array.length; i+=2) {
System.out.println("?" + array[i]);
}
// зубчасті матриці
int[][] matrix = {
{1, 2},
{3}
};
// C=a×B, a - const
// final int[][] MATRIX_C = int;
MATRIX_B[0][0] = 2;
MATRIX_B[0] = new int[]{1, 2};
System.out.println(MATRIX_B[0][0]);
MATRIX_B = new int[][]{
{1, 2},
{3}
};*/
}
private static int sumOfSmallestElementsInEveryColumn(final int[][] MATRIX_C) {
// todo check different length of rows
// todo try to change i and j
// todo check repetition of minimal elements
int sum = 0;
for (int i = 0; i < MATRIX_C[0].length; i++) {
int tmpSmallest = MATRIX_C[0][i];
for (int j = 1; j < MATRIX_C.length; j++) {
if (MATRIX_C[j][i] < tmpSmallest) {
tmpSmallest = MATRIX_C[j][i];
}
}
sum += tmpSmallest;
}
return sum;
}
private static void print(final int[][] MATRIX_C) {
for (int i = 0; i < MATRIX_C.length; i++) {
for (int j = 0; j < MATRIX_C[i].length; j++) {
// System.out.print(MATRIX_C[i][j] + "\t");//printf("%4d",
System.out.printf("%4d ", MATRIX_C[i][j]);//printf("%4d",
}
System.out.println();
}
}
private static int[][] multiplication(int A, final int[][] MATRIX_B) {
final int[][] MATRIX_C = new int[MATRIX_B.length][/*MATRIX_B[0].length*/]; // todo !!!DANGER different lengths of rows
// final int[][] MATRIX_C = MATRIX_B;
for (int i = 0; i < MATRIX_B.length; i++) {
MATRIX_C[i] = new int[MATRIX_B[i].length];
for (int j = 0; j < MATRIX_B[i].length; j++) {
MATRIX_C[i][j] = MATRIX_B[i][j] * A;
}
}
return MATRIX_C;
}
}

153
src/Lab2/Lab2.java Normal file
View File

@@ -0,0 +1,153 @@
package Lab2;
import java.util.Scanner;
import java.util.Random;
public class Lab2 {
public static void main(String[] args) {
final int C5, C7, C11, NumBook;
NumBook = 2401;
C5 = NumBook % 5;
C7 = NumBook % 7;
C11 = NumBook % 11;
System.out.println("-----------------------------------------------------");
System.out.println("C5 is: " + C5 + " - act with martix is C=Bт");
System.out.println("C7 is: " + C7 + " - type of elements is double");
System.out.println("C11 is: " + C11 + " - calculate the sum of the largest elements\n" +
"of each row of the matrix");
System.out.println("-----------------------------------------------------");
int Mside = 0;
int Nside = 0;
int Choose;
double MaxSum = 0;
Random rand = new Random();
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter random or handle input(1 or 0): ");
Choose = Math.abs(Integer.parseInt(sc.nextLine()));
if (Choose == 1 || Choose == 0) {
break;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter an integer.");
}
}
while (true) {
try {
System.out.print("Enter number of rows: ");
Mside = Math.abs(Integer.parseInt(sc.nextLine()));
if (Mside <= 0) {
System.out.println("Invalid input. Number of rows must be greater than 0");
} else {
break;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter an integer.");
}
}
while (true) {
try {
System.out.print("Enter number of columns: ");
Nside = Math.abs(Integer.parseInt(sc.nextLine()));
if (Nside <= 0) {
System.out.println("Invalid input. Number of columns must be greater than 0");
} else {
break;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter an integer.");
}
}
final int lenghtMaxElements = 5;
double[][] CArray = new double[Mside][Nside];
double[][] TransposedArray = new double[Nside][Mside];
double[][] MaxElements = new double[Nside][lenghtMaxElements];
if (Choose == 1) {
for (int i = 0; i < Mside; i++) {
for (int j = 0; j < Nside; j++) {
CArray[i][j] = rand.nextDouble(-100, 100);
}
}
}
if (Choose == 0) {
for (int i = 0; i < Mside; i++) {
for (int j = 0; j < Nside; j++) {
while (true) {
try {
System.out.printf("Enter the element at position (%d,%d): ", i + 1, j + 1);
CArray[i][j] = Double.parseDouble(sc.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
}
}
}
}
}
for (int i = 0; i < Mside; i++) {
for (int j = 0; j < Nside; j++) {
System.out.printf("%8.2f", CArray[i][j]);
}
System.out.println();
}
for (int i = 0; i < Nside; i++) {
for (int j = 0; j < Mside; j++) {
TransposedArray[i][j] = CArray[j][i];
}
}
System.out.println("Transposed array is:");
int row, cols;
for (row = 0; row < Nside; row++) {
for (cols = 0; cols < Mside; cols++) {
System.out.printf("%8.2f", TransposedArray[row][cols]);
}
System.out.println();
}
for (int i = 0; i < Nside; i++) {
MaxElements[i][0] = TransposedArray[i][0];
for (int j = 1; j < Mside; j++) {
MaxElements[i][1] = i;
if (TransposedArray[i][j] > MaxElements[i][0]) {
MaxElements[i][0] = TransposedArray[i][j];
MaxElements[i][2] = j;
} else if (TransposedArray[i][j] == MaxElements[i][0]) {
MaxElements[i][3] = MaxElements[i][0];
MaxElements[i][4] = 1;
}
}
//System.out.println(MaxElements[i][0] +" "+ MaxElements[i][1] +" "+ MaxElements[i][2] + " " + MaxElements[i][3] + " " + MaxElements[i][4]);
//code i used for debug
}
System.out.println("Max elements for each row:");
if (Mside == 1) {
System.out.println("I can`t find max element for mx1 matrix");
} else {
for (int i = 0; i < Nside; i++) {
if (MaxElements[i][0] == MaxElements[i][3] && MaxElements[i][4] == 1) {
System.out.printf("In row %1.0f does not exist a max element\n", MaxElements[i][1] + 1);
} else {
System.out.printf("%8.2f is max value and his coordinate: (%1.0f, %1.0f)\n", MaxElements[i][0], MaxElements[i][1] + 1, MaxElements[i][2] + 1);
MaxSum += MaxElements[i][0];
}
}
System.out.printf("Sum of elements with max values is: %.2f\n", MaxSum);
}
}
}

73
src/Lab3/Lab3.java Normal file
View File

@@ -0,0 +1,73 @@
package Lab3;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Lab3 {
public static void main(String[] args) {
System.out.println("Введіть текст:");
Scanner scan = new Scanner(System.in); // Створюємо об'єкт Scanner для зчитування введеного тексту з консолі
String inputText = scan.nextLine(); // Зчитуємо введений текст користувача
StringBuffer textBuffer = new StringBuffer(inputText); // Створюємо відподні об'єкти StringBuffer
StringBuffer result = new StringBuffer();
while (!textBuffer.isEmpty()) { // Починаємо цикл, який виконується, доки об'єкт textBuffer не стане порожнім
int index1 = textBuffer.indexOf("."); // Знаходимо індекси для символів, які закінчують речення
int index2 = textBuffer.indexOf("!");
int index3 = textBuffer.indexOf("?");
int index4 = textBuffer.indexOf("...");
int[] SplitIndexArray = {index1, index2, index3, index4};
ArrayList<Integer> list = new ArrayList<>();
for (int j : SplitIndexArray) { // Перебираємо кожну позицію з масиву
if (j >= 0) { // Якщо символ не стоїть перед реченням, додаємо його
list.add(j);
}
}
int min = Collections.min(list); // Знаходимо мінімальну позицію, щоб працювати з першим реченням
String sentenceString = textBuffer.substring(0, min); // Виділяємо перше речення до знайденого розділового знаку
StringBuffer sentence = new StringBuffer(sentenceString); // Створюємо об'єкт StringBuffer для речення з пробілом
if (sentenceString.contains(" ")) { // Перевіряємо, чи перше речення містить більше одного слова
String firstword1;
String secondword1 = textBuffer.substring(sentence.lastIndexOf(" ") + 1, sentence.length()); // Виділяємо друге слово з речення
String secondword2;
secondword2 = secondword1.substring(0, 1).toUpperCase() + secondword1.substring(1, secondword1.length()); // Першу літеру робимо великою, решту слова копіюємо
StringBuffer secondword = new StringBuffer(secondword2);
if (sentence.charAt(sentence.indexOf(" ") - 1) == ',') { // Перевіряємо, чи перед першим словом є кома
firstword1 = textBuffer.substring(0, sentence.indexOf(" ") - 1); // Виділяємо перше слово з речення
secondword.append(","); // Додаємо кому до другого слова
} else {
firstword1 = textBuffer.substring(0, sentence.indexOf(" ")); // Виділяємо перше слово з речення
}
String firstword2 = firstword1.substring(0, 1).toLowerCase() + firstword1.substring(1, firstword1.length()); // Перетворюємо першу літеру першого слова малою
StringBuffer firstword = new StringBuffer(firstword2);
firstword.insert(0, " "); // Додаємо пробіл перед першим словом
sentence.delete(0, sentence.indexOf(" ")); // Видаляємо перше слово з речення
sentence.insert(0, secondword); // Додаємо друге слово на початок речення
sentence.delete(sentence.lastIndexOf(" "), sentence.length()); // Видаляємо останнє слово з речення
sentence.append(firstword); // Додаємо перше слово в кінець речення
}
if ((index1 == index4) && (index1 == min)) { // Перевіряємо випадок, коли речення закінчується на "..."
sentence.append(textBuffer.substring(min, min + 3)); // Додаємо "..." до речення
textBuffer.delete(0, min + 4); // видаляємо з textBuffer
} else {
sentence.append(textBuffer.substring(min, min + 1)); // Додаємо '.' до речення
textBuffer.delete(0, min + 2); // видаляємо з textBuffer
}
sentence.append(" "); // Додаємо пробіл
result.append(sentence); // Додаємо речення до результату
}
System.out.println(result);
}
}

118
src/Lab4/Airplane.java Normal file
View File

@@ -0,0 +1,118 @@
package Lab4;
import java.util.Comparator;
public class Airplane {
private int number; // Номер літака
private String model; // Модель літака
private String airline; // Компанія-власник
private int capacity; // Ємність для пасажирів
private double fuelCapacity; // Ємність палива
private boolean isFlying; // Стан літака: летить/в ангарі
// Конструктор класа
public Airplane(int number, String model, String airline, int capacity, double fuelCapacity) {
this.number = number;
this.model = model;
this.airline = airline;
this.capacity = capacity;
this.fuelCapacity = fuelCapacity;
this.isFlying = false;
}
// Методи доступу, а саме геттери
public int getNumber() {
return number;
}
public String getModel() {
return model;
}
public String getAirline() {
return airline;
}
public int getCapacity() {
return capacity;
}
public double getFuelCapacity() {
return fuelCapacity;
}
public boolean isFlying() {
return isFlying;
}
public void setFlying(boolean flying) {
isFlying = flying;
}
// Метод для запускання літака
public void takeOff() {
if (isFlying) { // Перевірка, якщо літає, то його знову не запустити,
// у мому коді до цього уже є перевірка, але якщо наприклад розришяти
// для інших програм, де перевірки не буде, то воно збереже від помилки
System.out.println("The airplane is already flying.");
} else {
System.out.println("Taking off...");
// Виводимо інформацію про взліт літака, міняємо прапор на 'true'
isFlying = true;
System.out.println("Airplane " + number + " took off!");
}
}
// Метод для посадки літака
public void land() {
if (!isFlying) { // та сама перевірка, тільки для посадки
System.out.println("The airplane is already on the ground.");
} else {
// садимо літак, пасажири плескають в долоні, а прапор 'false'
System.out.println("Landing...");
isFlying = false;
System.out.println("Airplane number " + number + " landed!");
System.out.println("Passengers: *claps*");
}
}
// Перевизначений метод toString для виведення інформації про літак у зручному форматі
@Override
public String toString() {
String flying = "In angar";
if (isFlying) {
flying = "Flying"; // друкувати стан прапора було би не естетично, тому перевіряємо 'true' - Flying
}
return String.format("%-7d | %-25s | %-10s | %-8d | %-12.1f | %-10s",
number, model, airline, capacity, fuelCapacity, flying); // використовуємо метод .format для зручного виведення
}
}
// Клас, що реалізує інтерфейс Comparator для порівняння літаків за номером
class SortByNumber implements Comparator<Airplane> {
public int compare(Airplane a, Airplane b) {
return a.getNumber() - b.getNumber();
}
}
// Клас, що реалізує інтерфейс Comparator для порівняння літаків за моделлю
class SortByModel implements Comparator<Airplane> {
public int compare(Airplane a, Airplane b) {
return a.getModel().compareTo(b.getModel()); // Для типу String використовуємо метод compareTo
}
}
// Клас, що реалізує інтерфейс Comparator для порівняння літаків за ємністю
class SortByCapacity implements Comparator<Airplane> {
public int compare(Airplane a, Airplane b) {
return a.getCapacity() - b.getCapacity();
}
}
// Клас, що реалізує інтерфейс Comparator для порівняння літаків за ємністю палива
class SortByFuelCapacity implements Comparator<Airplane> {
public int compare(Airplane a, Airplane b) {
return Double.compare(a.getFuelCapacity(), b.getFuelCapacity()); // Для типу double застосовуємо відповідний метод
// з абстрактного класу Double
}
}

101
src/Lab4/Lab4.java Normal file
View File

@@ -0,0 +1,101 @@
package Lab4;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Lab4 {
int C11 = 2401 % 11; // 3 - Визначити клас літак, який складається як мінімум з 5-и полів.
public static void main(String[] args) {
Airplane[] airplanes = { // Створюємо масив літаків, можливості створити літак, який одразує літає неможливо,
// що логічно
new Airplane(1, "Boeing 747", "Airline 1", 20, 50000.0),
new Airplane(2, "Airbus A320", "Airline 1", 300, 3000.0),
new Airplane(3, "Embraer E190", "Airline 2", 1700, 2000.0),
new Airplane(4, "Cessna 172", "Airline 3", 400, 1500.0),
new Airplane(5, "Bombardier Global 6000", "Airline 1", 100, 800.0),
};
Scanner scanner = new Scanner(System.in); // Підключаємо Scanner
boolean quit = false;
while (!quit) { // Нескінченний цикл поки користувач не введе 'q'
System.out.print("\nEnter the field to sort by (number, model, capacity, fuelcapacity), 'fly' to fly airplane or enter 'q' to exit: ");
String input = scanner.nextLine();
// перевірка чи правильно введено слово
if (!input.equals("number") && !input.equals("model") && !input.equals("capacity") && !input.equals("fuelcapacity") && !input.equals("q") && !input.equals("fly")) {
System.out.println("Invalid field to sort by! Please enter 'number', 'model', 'capacity', 'fuelcapacity'.");
continue;
}
// перевірка виходу з програми
if (input.equals("q")) {
quit = true;
System.out.println("Closing program...");
continue;
}
// перевірка, чи користувач хоче запустити літак
if (input.equals("fly")){
buildBoard(airplanes); // виводимо таблицю літаків, через функцію buildBoard
System.out.print("Enter the airplane number to make it fly or land if it already fly: ");
int airplaneNumber = scanner.nextInt();
scanner.nextLine();
// Знаходимо вибраний літак
Airplane selectedAirplane = null;
for (Airplane airplane : airplanes) {
if (airplane.getNumber() == airplaneNumber) {
selectedAirplane = airplane;
break;
}
}
// перевірка, якщо літає - садимо на землю, якщо в ангарі, то запускаємо в повітр'я
if (selectedAirplane != null) {
if (selectedAirplane.isFlying()) {
selectedAirplane.land(); // викликаємо метод для посадки
} else {
selectedAirplane.takeOff(); // викликаємо метод для запуску
}
} else {
System.out.println("No airplane found with the specified number.");
}
continue;
}
String field = input;
System.out.print("Enter the sort order (asc or desc): "); // вибір користувачем сортування за спаданням
String order = scanner.nextLine(); // чи зростанням
if (!order.equals("asc") && !order.equals("desc")) { // перевірка чи правильно введено символ
System.out.println("Invalid sort order! Please enter 'asc' or 'desc'.");
continue;
}
// "потужний" swtich
Comparator<Airplane> comparator = switch (field) { // в залежності від введеного слова - певний метод сортування
case "number" -> new SortByNumber();
case "model" -> new SortByModel();
case "capacity" -> new SortByCapacity();
case "fuelcapacity" -> new SortByFuelCapacity();
default -> null;
};
if (order.equals("desc")) { // інвертуємо для зворотнього порядку
comparator = comparator.reversed();
}
Arrays.sort(airplanes, comparator); // сортуємо літаки за результатами компоратора
System.out.println("\nSorted by " + field + " (in " + order + "ending order):");
buildBoard(airplanes); // виклик функції buildBoard
}
}
public static void buildBoard(Airplane[] airplanes){ // Функція нічого не повертає, приймає на вхід масив літаків
System.out.println(String.format("%n%-7s | %-25s | %-10s | %-6s | %12s | %-10s", "Number", "Model", "Airline", "Capacity", "Fuel Capcity", "Is flying"));
System.out.println("---------------------------------------------------------------------------------------");
for (Airplane airplane : airplanes) { // "потужний" цикл for, щоб зручно перебрати літаки
System.out.println(airplane.toString()); // викликаємо метод toSring(), який є прикладом поліморфізму
}
}
}

97
src/Lab6/Car.java Normal file
View File

@@ -0,0 +1,97 @@
package Lab6;
import java.util.Comparator;
/**
* Абстрактний клас Car представляє основні властивості автомобіля
* Він містить конструктор для ініціалізації властивостей автомобіля,
* а також методи доступу до цих властивостей.
*/
public abstract class Car {
private final String make; // Марка автомобіля
private final String model; // Модель автомобіля
private final int year; // Рік випуску автомобіля
private final int price; // Ціна автомобіля
private final int speed; // Швидкість автомобіля
private final double fuelConsumption;// Споживання палива автомобілем
/**
* Конструктор класу Car ініціалізує властивості автомобіля.
*
* @param make марка автомобіля
* @param model модель автомобіля
* @param year рік випуску автомобіля
* @param price ціна автомобіля
* @param speed швидкість автомобіля
* @param fuelConsumption споживання палива автомобілем
*/
public Car(String make, String model, int year, int price, int speed, double fuelConsumption) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
this.speed = speed;
this.fuelConsumption = fuelConsumption;
}
// Звичайні геттери, тому їх сильно не розписував
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public int getPrice() {
return price;
}
public int getSpeed() {
return speed;
}
public double getFuelConsumption() {
return fuelConsumption;
}
/**
* Перезаписаний метод toString для представлення об'єкту автомобіля у вигляді рядка.
*
* @return рядок, що містить всі властивості абстрактного автомобіля
*/
@Override
public String toString() {
return String.format("%-10s | %-7s | %-6s | %-6d | %-5d | %-5s | ",
make, model, year, price, speed, fuelConsumption);
}
}
/**
* Клас SortByFuelConsuming реалізує інтерфейс Comparator і використовується для порівняння автомобілів
* за споживанням палива.
*/
class SortByFuelConsuming implements Comparator<Car> {
/**
* Метод compare порівнює два об'єкти Car за споживанням палива.
* Він порівнює значення споживання палива для обох автомобілів.
*
* @param a перший автомобіль
* @param b другий автомобіль
* @return -1, 0 або 1, якщо перше значення менше, рівне або більше другого відповідно
*/
public int compare(Car a, Car b) {
return Double.compare(a.getFuelConsumption(), b.getFuelConsumption());
}
}
// Щоб реалізувати ієрархію я рішив використати абстрактний клас машини, який має всі базові якості машини
// його нащадки мають додаткове поле, крім того різних типів
// Клас SortByFuelConsuming є інтерфейсом Comparator і використовується для порівняння автомобілів
// за споживанням палива.
// повертає значення за яким потім буде сортуватися масив машин

20
src/Lab6/Coupe.java Normal file
View File

@@ -0,0 +1,20 @@
package Lab6;
public class Coupe extends Car {
private final String bodyType;
// Клас купе має додатковий тип який визначає тип кузова, або можна написати чи машина без криші чи з кришою
public Coupe(String make, String model, int year, int price, int speed, double fuelConsumption, String bodyType) {
super(make, model, year, price, speed, fuelConsumption);
this.bodyType = bodyType;
}
public String getBodyType() {
return bodyType;
}
@Override
public String toString() {
return super.toString()+ String.format("Type: %-10s |" , bodyType); // викликаємо супер-метод, додаємо тип кузова
}
}

24
src/Lab6/Hatchback.java Normal file
View File

@@ -0,0 +1,24 @@
package Lab6;
public class Hatchback extends Car {
private int numberOfDoors;
// Клас Hatchback має додаткову властивість - кількість дверей
public Hatchback(String make, String model, int year, int price, int speed, double fuelConsumption, int numberOfDoors) {
super(make, model, year, price, speed, fuelConsumption);
this.numberOfDoors = numberOfDoors;
}
public int getNumberOfDoors() {
return numberOfDoors;
}
public void setNumberOfDoors(int numberOfDoors) {
this.numberOfDoors = numberOfDoors;
}
@Override
public String toString() {
return super.toString() + String.format("Doors: %-10d |" , numberOfDoors); // додаємо до супер-методу нову властивість
}
}

23
src/Lab6/Sedan.java Normal file
View File

@@ -0,0 +1,23 @@
package Lab6;
public class Sedan extends Car {
private int seatingCapacity;
// У об'єктів класу седан особливим є кільість пасажирських місць
public Sedan(String make, String model, int year,int price, int speed, double fuelConsumption, int seatingCapacity) {
super(make, model, year, price, speed, fuelConsumption);
this.seatingCapacity = seatingCapacity;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
@Override
public String toString() {
return super.toString() + String.format("Seats: %-10d |" , seatingCapacity); // додаємо до супер-методу додаткову властивість
}
}

182
src/Lab6/TaxiPark.java Normal file
View File

@@ -0,0 +1,182 @@
package Lab6;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TaxiPark {
private static List<Car> cars;
public TaxiPark() {
cars = new ArrayList<>();
} // Створюємо у таксопарка масив машин
public void addAutomobile(Car car) {cars.add(car);} // Метод для додавання машини у таксопарк
// Метод для додавання машини у таксопарк, але користувачем
public void addAutomobileConsole(String carType, String maker, String model, int year, int price, int speed, double fuelConsumption, Object additionalProperty){
Car car;
switch (carType) { // Удосконалений switch для створення конкретного типу машини
case "Coupe" ->
car = new Coupe(maker, model, year, price, speed, fuelConsumption, (String) additionalProperty); //
// Я придумав, що у купе поліморфізм виражається у тому, що вона може бути купе, без криші, туфелькою
// я дуже погано в машинах розбираюсь, тому надіюсь ви мене зрозуміли
case "Hatchback", "Sedan" ->
car = new Hatchback(maker, model, year, price, speed, fuelConsumption, (int) additionalProperty);
default -> {
System.out.println("Invalid car type");
return;
}
}
addAutomobile(car); // Виклик метода для додаваня машини у таксопарк, можна було без нього,
// одною строкою, але так мені це показалось логічним
}
public double calculateFleetCost() { // Метод для обрахунку ціни усіх машин
double totalCost = 0.0;
for (Car car : cars) {
totalCost += car.getPrice(); // Перебираємо усі машини, викликаємо у них метод getPrice()
}
return totalCost; // Повертаємо результат
}
public List<Car> findCarsBySpeedRange(int minSpeed, int maxSpeed) { // Метод для знаходження машин у діапазоні
List<Car> carsInSpeedRange = new ArrayList<>();
for (Car car : cars) {
if (car.getSpeed() >= minSpeed && car.getSpeed() <= maxSpeed) {
carsInSpeedRange.add(car); // Перебираємо машини, які задовольняються умові діапазону
}
}
return carsInSpeedRange;
}
public void boardCars(List<Car> cars){ // Метод для будування таблиці, приймає масив машин, і створює красиву табличку
System.out.println("----------------------------------------------------------------------------");
System.out.printf("%-10s | %-7s | %-6s | %-6s | %-5s | %-5s | %-10s | %n",
"Maker", "Model", "Year", "Price", "Speed", "Fuel", "Special");
System.out.println("----------------------------------------------------------------------------");
for (Car car : cars) {
System.out.println(car.toString());
}
System.out.println("----------------------------------------------------------------------------");
}
public void sortByFuelConsumption() { // Метод у таксопарка, який викликає клас для сортування
cars.sort(new SortByFuelConsuming());
boardCars(TaxiPark.cars); // будуємо відсортовану табличку
}
public static void main(String[] args) {
int C13 = 2401 % 13;
System.out.println("C13 - " + C13 + ", отже треба створити таксопар та ієрархію автомобілів.");
System.out.println("--------------------------------------------------------------\n");
TaxiPark taxiPark = new TaxiPark();
// Додати автомобілі до таксопарку
taxiPark.addAutomobile(new Sedan("Toyota", "Camry", 2020, 3500, 220, 7.5, 5));
taxiPark.addAutomobile(new Coupe("BMW", "M4", 2021, 3000, 150, 9.2, "Coupe"));
taxiPark.addAutomobile(new Hatchback("Volkswagen", "Golf", 2019, 6000, 200, 6.8, 6));
Scanner scanner = new Scanner(System.in); // Під'єднуємо сканер
boolean quit = false;
while (!quit) { // Нескінченний цикл поки користувач не введе 'q'
System.out.print("""
Enter:
'cost' - show total fleet
'sort' - show cars sorted by fuel consumption
'board' - show cars
'add' - buy car on your TaxiPark
'find' - find cars that in speed diapason
or enter 'q' to exit:\s""");
String input = scanner.nextLine();
// Перевірка чи правильно введено слово
if (!input.equals("cost") && !input.equals("sort") && !input.equals("board") && !input.equals("add") && !input.equals("q") && !input.equals("find")) {
System.out.println("Invalid field to sort by! Please enter 'cost', 'sort', 'board', 'add', 'find'.");
continue;
}
// Перевірка виходу з програми
if (input.equals("q")) {
quit = true;
System.out.println("Closing program...");
continue;
}
if (input.equals("cost")){
// Порахувати вартість автопарку
double fleetCost = taxiPark.calculateFleetCost(); // Викликаємо метод, який вже описав
System.out.println("Total fleet cost: $" + fleetCost);
continue;
}
if (input.equals("sort")){
// Відсортувати автомобілі за витратами палива
taxiPark.sortByFuelConsumption();
continue;
}
if (input.equals("board")){
taxiPark.boardCars(TaxiPark.cars); // Виведення таблички
continue;
}
if (input.equals("find")){
int minSpeed, maxSpeed;
System.out.println("Enter min speed: "); // Користувач вводе межі діапазона
minSpeed = scanner.nextInt();
System.out.println("Enter max speed:");
maxSpeed = scanner.nextInt();
scanner.nextLine(); // Тут залишався \n тому ми його з'їли
List<Car> carsInSpeedRange = taxiPark.findCarsBySpeedRange(minSpeed, maxSpeed); // Масив машин діапазону
System.out.println("Cars within the speed range of " + minSpeed + " km/h to " + maxSpeed + " km/h:");
taxiPark.boardCars(carsInSpeedRange); // Створенний масив передаємо методу для будування таблички
}
if (input.equals("add")){
// Користувач вводе багато значень, перевірки не добавив, тому акуратно)
System.out.println("Choose type of car: 'Sedan', 'Coupe', 'Hatchback'");
String carType = scanner.nextLine();
System.out.println("Enter Maker: ");
String maker = scanner.nextLine();
System.out.println("Enter Model: ");
String model = scanner.nextLine();
System.out.println("Enter year: ");
int year = scanner.nextInt();
System.out.println("Enter price (int)");
int price = scanner.nextInt();
System.out.println("Enter speed (int)");
int speed = scanner.nextInt();
System.out.println("Enter fuel consumption");
double fuelConsumption = scanner.nextDouble();
scanner.nextLine();
Object additionalProperty = null; // Абстрактний об'єкт, далі в switch він набуде тип
switch (carType) {
case "Sedan", "Hatchback" -> {
System.out.println("Enter special(int):");
additionalProperty = scanner.nextInt();
}
case "Coupe" -> {
System.out.println("Enter special(any):");
additionalProperty = scanner.nextLine();
}
default -> System.out.println("Invalid car type");
}
// Передаємо всі введені значення методу для купівлі машини у таксопарк
taxiPark.addAutomobileConsole(carType, maker, model, year, price, speed, fuelConsumption, additionalProperty);
}
}
}
}

View File

@@ -1,42 +0,0 @@
public class Main {
public static void main(String[] args) {
System.out.println(args[2]);
System.out.println("Hello world!");
// System.out.println(1);
int a = 1;
int b = 2;
int c = 1;
int d = 1;
System.out.println(2&1);
System.out.println(2|1);
int aa = 2;
/*if (aa) {
}*/
// System.out.println("a"&"b");
System.out.println('a'&'b');
if ((a > b) & MyBooleanMethod()) {
System.out.println("?????????????????????????");
}
}
static boolean MyBooleanMethod() {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return true;
}
void myFunction() {
}
int myFunction2() {
return 1;
}
}

View File

@@ -1,20 +0,0 @@
package encapsulationInheritancePolymorphism;
public class Encapsulation {
/*private*/ int field;
private int field2;
// int a = 1;
public void myMethodForTheField () {
System.out.println(field);
}
public void myMethodForTheField2 () {
System.out.println(field);
}
public void myMethodForTheFieldAndTheField2 () {
System.out.println(field);
}
}

View File

@@ -1,10 +0,0 @@
package encapsulationInheritancePolymorphism;
public class EncapsulationInheritancePolymorphism {
public static void main(String[] args) {
int a = 1;
// var b = 2;
// System.out.println(b);
}
}

View File

@@ -1,14 +0,0 @@
package encapsulationInheritancePolymorphism;
public class Main {
public static void main(String[] args) {
Student student = new Student();
//...
student.setFaculty("FPM", "MO-22");
}
}

View File

@@ -1,18 +0,0 @@
package encapsulationInheritancePolymorphism;
public class Student {
private String name;
private String surname;
private String group;
private String faculty;
public String getName() {
return name;
}
public void setFaculty(String faculty, String group) {
this.faculty = faculty;
this.group = group;
}
}

View File

@@ -1,9 +0,0 @@
package encapsulationInheritancePolymorphism.inheritance;
public class ElectricEngine extends Engine {
private String batteryType;
/*private class Engine {
private int power;
}*/
}

View File

@@ -1,5 +0,0 @@
package encapsulationInheritancePolymorphism.inheritance;
public class Engine {
private int power;
}

View File

@@ -1,5 +0,0 @@
package encapsulationInheritancePolymorphism.inheritance;
public class FuelEngine extends Engine {
private String fuelType;
}

View File

@@ -1,8 +0,0 @@
package encapsulationInheritancePolymorphism.inheritance;
public class Main {
public static void main(String[] args) {
ElectricEngine electricEngine = new ElectricEngine(); // створення нового об'єкту (екземпляру) класу ElectricEngine
FuelEngine fuelEngine = new FuelEngine();
}
}

View File

@@ -1,14 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism;
public class ElectricEngine extends Engine {
private String batteryType;
@Override
public int getPower() {
return 20;
}
/*private class Engine {
private int power;
}*/
}

View File

@@ -1,9 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism;
public class Engine {
private int power;
public int getPower() {
return power;
}
}

View File

@@ -1,10 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism;
public class FuelEngine extends Engine {
private String fuelType;
@Override
public int getPower() {
return 50;
}
}

View File

@@ -1,38 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism;
/*import encapsulationInheritancePolymorphism.inheritance.ElectricEngine;
import encapsulationInheritancePolymorphism.inheritance.FuelEngine;*/
public class Main {
public static void main(String[] args) {
/*encapsulationInheritancePolymorphism.inheritance.*/ElectricEngine electricEngine = new ElectricEngine(); // створення нового об'єкту (екземпляру) класу ElectricEngine
/*encapsulationInheritancePolymorphism.inheritance.*/FuelEngine fuelEngine = new FuelEngine();
Engine engine1 = fuelEngine;
Engine[] engines = {
electricEngine,
fuelEngine
};
for (Engine engine : engines) {
System.out.println(engine.getPower());
}
/*for (int i = 0; i < engines.length; i++) {
System.out.println(engines[i].getPower());
}*/
// +
int a = 1;
int b = 1;
int c = a + b;
System.out.println(c);
String sA = "1";
String sB = "1";
String sC = sA + sB;
System.out.println(sC);
}
}

View File

@@ -1,19 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism.enhanced;
public class ElectricEngine extends Engine {
private String batteryType;
private int chargeLevel = 9;
private int criticalChargeLevel = 10;
private float coefficientCriticalPowerCut = 0.1f;
@Override
public int getPower() {
return chargeLevel > criticalChargeLevel
? super.getPower()
: (int) (super.getPower() * coefficientCriticalPowerCut);
}
/*private class Engine {
private int power;
}*/
}

View File

@@ -1,9 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism.enhanced;
public class Engine {
private int power = 100;
public int getPower() {
return power;
}
}

View File

@@ -1,10 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism.enhanced;
public class FuelEngine extends Engine {
private String fuelType;
/*public int getPower() {
return 50;
}*/
}

View File

@@ -1,28 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism.enhanced;
/*import encapsulationInheritancePolymorphism.inheritance.ElectricEngine;
import encapsulationInheritancePolymorphism.inheritance.FuelEngine;*/
public class Main {
public static void main(String[] args) {
/*encapsulationInheritancePolymorphism.inheritance.*/
ElectricEngine electricEngine = new ElectricEngine(); // створення нового об'єкту (екземпляру) класу ElectricEngine
/*encapsulationInheritancePolymorphism.inheritance.*/
FuelEngine fuelEngine = new FuelEngine();
Engine engine1 = fuelEngine;
Engine[] engines = {
electricEngine,
fuelEngine
};
for (Engine engine : engines) {
System.out.println(engine.getPower());
}
/*for (int i = 0; i < engines.length; i++) {
System.out.println(engines[i].getPower());
}*/
}
}

View File

@@ -1,17 +0,0 @@
package encapsulationInheritancePolymorphism.polymorphism.overload;
public class MyClassForOverloadExample {
void myMethod(int a) {
System.out.println("Integer: " + a);
}
void myMethod(double a) {
System.out.println("Double: " + a);
}
public static void main(String[] args) {
MyClassForOverloadExample overload = new MyClassForOverloadExample();
overload.myMethod(1);
overload.myMethod(0.1);
}
}

View File

@@ -1,13 +0,0 @@
package test;
public class A {
/*private*/ int f/* = 3*/;
public int getF() {
return f;
}
public void setF(int f) {
this.f = f;
}
}

View File

@@ -1,15 +0,0 @@
package test;
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getF());
a.setF(1);
System.out.println(a.getF());
System.out.println(a.f);
int[] array = {1, 2, 1};
System.out.println(array.length);
}
}