Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Проектная работа No1 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
xabko wants to merge 1 commit into main
base: main
Choose a base branch
Loading
from dev
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
27 changes: 27 additions & 0 deletions src/main/java/Car.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Класс автомобиля - участника гонки
*/
public class Car {
private String name; // Название автомобиля
private int speed; // Скорость в км/ч

public Car(String name, int speed) {
this.name = name;
this.speed = speed;
}

public String getName() {
return name;
}

public int getSpeed() {
return speed;
}

/**
* Расчет расстояния за 24 часа
*/
public double calculateDistance() {
return speed * 24; // 24 часа гонки
}
}
62 changes: 60 additions & 2 deletions src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,64 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
Car[] cars = new Car[3];
Copy link

@ArturNurtdinov ArturNurtdinov Nov 2, 2025

Choose a reason for hiding this comment

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

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


System.out.println("=== 24 часа Ле-Мана ===");

// Ввод данных для трех автомобилей
for (int i = 0; i < 3; i++) {
System.out.println("— Введите название машины No" + (i + 1) + ":");
String name = scanner.nextLine();

int speed = getValidSpeed(scanner, i + 1);

cars[i] = new Car(name, speed);
}

// Определяем победителя
Race race = new Race(cars);
Car winner = race.getLeader();

// Выводим результат
System.out.println("Самая быстрая машина: " + winner.getName());

scanner.close();
}

/**
* Метод для получения корректной скорости с проверкой
*/
private static int getValidSpeed(Scanner scanner, int carNumber) {
int speed = 0;
boolean isValid = false;

while (!isValid) {
System.out.println("— Введите скорость машины No" + carNumber + ":");
String input = scanner.nextLine();

try {
// Проверяем на дробное число
if (input.contains(".") || input.contains(",")) {
Copy link

@ArturNurtdinov ArturNurtdinov Nov 2, 2025

Choose a reason for hiding this comment

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

Уже есть обработка NumberFormatException , поэтому от этой проверки можно отказаться

System.out.println("— Неправильная скорость");
continue;
}

speed = Integer.parseInt(input);

// Проверяем диапазон
if (speed <= 0 || speed > 250) {
Copy link

@ArturNurtdinov ArturNurtdinov Nov 2, 2025

Choose a reason for hiding this comment

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

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

System.out.println("— Неправильная скорость");
} else {
isValid = true;
}

} catch (NumberFormatException e) {
System.out.println("— Неправильная скорость");
}
}

return speed;
}
}
}
36 changes: 36 additions & 0 deletions src/main/java/Race.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Класс гонки - определяет победителя
*/
public class Race {
private Car[] cars;
private Car leader;

public Race(Car[] cars) {
this.cars = cars;
calculateLeader();
}

/**
* Вычисляем лидера по пройденному расстоянию за 24 часа
*/
private void calculateLeader() {
if (cars == null || cars.length == 0) {
return;
}

leader = cars[0];
double maxDistance = leader.calculateDistance();

for (int i = 1; i < cars.length; i++) {
double currentDistance = cars[i].calculateDistance();
if (currentDistance > maxDistance) {
maxDistance = currentDistance;
leader = cars[i];
}
}
}

public Car getLeader() {
return leader;
}
}

AltStyle によって変換されたページ (->オリジナル) /