Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cmdCompile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

//Компиляция
javac /home/alexandr/prj/android/Java-Module-Project-YP/src/main/java/Main.java

//Запуск
cd /home/alexandr/prj/android/Java-Module-Project-YP && java -cp src/main/java Main
Binary file added src/main/java/Calc.class

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сами скомпилированные файлы .class не нужно копировать в source директории и пушить на гит

Binary file not shown.
Binary file added src/main/java/Car.class
Binary file not shown.
Binary file added src/main/java/InputData.class
Binary file not shown.
Binary file added src/main/java/Main.class
Binary file not shown.
118 changes: 117 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,122 @@
import java.util.HashSet;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
//Ввод данных
InputData input = new InputData();
Car[] cars = input.getCars();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

От хранения массива машин и лишнего цикла при определении победителя можно избавиться, если при вводе данных сразу вычислять победителя и хранить его в отдельной переменной, тогда программа будет требовать меньше памяти и работать быстрее


//расчёты
Calc calc = new Calc();
Car fastest = calc.findFastest(cars);

//вывод результата
Output output = new Output();
output.printResult(fastest);
}
}

class InputData {
private Scanner scanner = new Scanner(System.in);

public Car[] getCars() {
System.out.println("Эта программа - симулятор гонок. В гонках участвует 3 автомобиля.");
Car[] cars = new Car[3];

for (int i = 0; i < 3; i++) {
System.out.println("\n--- Автомобиль " + (i + 1) + " ---");

String name;
boolean validName;

do {
System.out.print("Введите имя машины " + (i + 1) + ": ");
name = scanner.nextLine();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Код для считывания непустой строки с ввода лучше вынести в отдельную функцию - код, разделённый на небольшие функции, легче читать, поддерживать и переиспользовать


// Проверяем, что имя не пустое
if (name.trim().isEmpty()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вместо .trim().isEmpty() можно сделать isBlank() - тогда не будет создаваться новый объект для этой проверки

System.out.println("Ошибка! Имя не может быть пустым.");
validName = false;
continue;
}

// Проверяем, есть ли уже машина с таким именем
validName = true;
for (int j = 0; j < i; j++) {
if (cars[j] != null && cars[j].name.equalsIgnoreCase(name)) {
System.out.println("Ошибка! Машина с именем '" + name + "' уже существует.");
validName = false;
break;
}
}
} while (!validName);

int speed = inputSpeed(i + 1);
cars[i] = new Car(name, speed);
}

scanner.close();
return cars;
}

//Метод для ввода скорости
private int inputSpeed(int carNumber) {
int speed = 0;
boolean validInput = false;

while (!validInput) {
try {
System.out.print("Введите скорость машины " + carNumber + " (1-250 км/ч): ");
String input = scanner.nextLine();
speed = Integer.parseInt(input);

//Проверка диапазона
if (speed > 0 && speed <= 250) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Минимальную и максимальную скорости лучше вынести в константы для повышения читабельности кода

validInput = true;
} else {
System.out.println("Ошибка! Скорость должна быть в диапазоне от 1 до 250 км/ч.");
}
} catch (NumberFormatException e) {
System.out.println("Ошибка! Введите целое число.");
}
}

return speed;
}
}

class Calc {
//Метод для расчёта самой быстрой машины
public Car findFastest(Car[] cars) {
Car fastest = null;
for (Car car : cars) {
if (fastest == null || car.speed > fastest.speed) {
fastest = car;
}
}
return fastest;
}
}

class Output {
//Вывод
public void printResult(Car fastest) {
System.out.println("Самая быстрая машина: " + fastest.name);
}
}

// Класс машина
class Car {
// Поля
String name; // Название
int speed; // Скорость (км/ч)
int distance; // Расстояние за 24 часа езды (км)
Comment on lines +112 to +114

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поля лучше пометить final, тем самым исключив возможность их модификации извне


// Конструктор
Car(String carName, int carSpeed) {
name = carName;
speed = carSpeed;
distance = carSpeed * 24;
}
}
Binary file added src/main/java/Output.class
Binary file not shown.