Skip to content
Open
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
157 changes: 156 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,161 @@
import java.util.Scanner;

class Car {
int id;
String carName;
int carSpeed;
Comment on lines +4 to +6
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(int id, String name, int speed) {
this.id = id;
this.carName = name;
this.carSpeed = speed;
}

public int getId() {
return id;
}

public String getCarName() {
return carName;
}

public int getCarSpeed() {
return carSpeed;
}

static boolean checkSpeed(int speed) {
if (speed < 0) {
System.out.println("Ошибка: скорость не может быть отрицательной");
return false;
}
if (speed > 250) {
Comment on lines +27 to +31
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

System.out.println("Ошибка: скорость превышает максимум (250)");
return false;
}
return true;
}

}

class Race {
String winCarName;
int winCarId;
Comment on lines +41 to +42
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше целиком хранить объект класса Car в качестве машины-победителя, это исключает ситуацию рассинхрона между данными в этом классе

int distance;

Race() {
this.distance = 0;
}

public int getDistance() {
return distance;
}

public String getWinCar() {
return winCarName;
}

public int getWinCarId() {
return winCarId;
}

public void setWinCarId(int winCarId) {
this.winCarId = winCarId;
}

public void setWinCar(String car) {
this.winCarName = car;
}

public void setDistance(int distance) {
this.distance = distance;
}

public int calcDistance(int speed) {
return speed * 24;
}

public void checkAndSetLeader(Car car) {
int carDistance = calcDistance(car.getCarSpeed());
if (carDistance > this.getDistance()) {
this.setWinCar(car.getCarName());
this.setDistance(carDistance);
this.setWinCarId(car.getId());
}
}

public void printFlag(){
int rows = 8;
int cols = 32;
int cellSize = 2;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if ((i / cellSize + j / cellSize) % 2 == 0) {
System.out.print("██");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

public class Main {
static boolean isEmptyCheck(String input){
if (input.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.

Проверку можно заменить на isBlank - таким образом, объектов будет создано меньше

System.out.println("Ошибка: ничего не введено!");
return true;
}
return false;
}

public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
Race race = new Race();

System.out.println();
System.out.println("Приготовьтесь к захватывающей гонке, которая оставит вас без дыхания и подарит незабываемые эмоции!");
race.printFlag();
System.out.println("Присоединяйтесь к нам на невероятном соревновании, где скорость встречается с мастерством, а адреналин зашкаливает!");

for (int i = 1; i <= 3; i++) {
boolean validNameInput = false;
String name = "";
while (!validNameInput){
System.out.println("— Введите название машины гонщика №" + i + ": ");
name = scanner.nextLine();
if (isEmptyCheck(name)){
continue;
}
name = name.trim();
validNameInput = true;
}

boolean validSpeedInput = false;
int speed;
while (!validSpeedInput) {
System.out.println("— Введите скорость машины " + name + " гонщика №" + i + ": ");
String input = scanner.nextLine().trim();
if (!isEmptyCheck(input)) {
try {
speed = Integer.parseInt(input);
if (Car.checkSpeed(speed)) {
Car car = new Car(i, name, speed);
race.checkAndSetLeader(car);
validSpeedInput = true;
}
}
catch (NumberFormatException e) {
System.out.println("Ошибка: введите целое число! Попробуйте ещё раз.");
}
}
}
}

System.out.println("Гонка закончена!!!");
System.out.println("Победитель - гонщик №" + race.getWinCarId());
System.out.println("На машине - " + race.getWinCar());
System.out.println("С результатом - " + race.getDistance() +" километров");
scanner.close();
}
}