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
64 changes: 61 additions & 3 deletions src/main/java/Main.java
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!");
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Race race = new Race();

for (int i = 1; i <= 3; i++){
System.out.println("- Введите название машины №" + i);
String name;
while (true){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не рекомендую писать бесконечные циклы через while (true) - лучше всегда явно прописывать условие выхода из цикла, чтобы уменьшить вероятность ошибиться и повысить читабельность кода

name = scanner.nextLine();
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.

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

break;
} else {
System.out.println("- Неверное название!");
}
}
System.out.println("- Введите скорость машины №" + i);
int speed;
while (true){
if(scanner.hasNextInt()){
speed = scanner.nextInt();
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.

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

scanner.nextLine();
break;
} else {
System.out.println("- Неверная скорость!");
}
} else {
System.out.println("- Нужно ввести целое число");
scanner.next(); //загуглил, что стоит очищать буффер
}
}
Car car = new Car(name, speed);
race.getWinner(car);
}
System.out.println("Победитель: " + race.winner);}
}


class Car{
int speed = 0;
String name;

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 name, int speed){
this.name = name;
this.speed = speed;
}
}

class Race{
String winner = "";
int distance = 0;

public void getWinner(Car car) {
int distance = car.speed * 24;
if (distance > this.distance){
this.distance = distance;
winner = car.name;

}
}
}