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
8 changes: 8 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
public class Car {
String name;
int speed;
Comment on lines +2 to +3

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;
}
}
39 changes: 37 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
import java.util.ArrayList;
import java.util.Scanner;

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

@ArturNurtdinov то есть просто создать 3 разных объекта? car1, car2, car3 и при создании дергать класс гонки, чтобы сетить лидера?

for(int i=0; i<3; i++){
String carName = "";
int carSpeed = -1;
while(carName.isEmpty()){
System.out.println("Введите марку автомобиля №" + (i+1));
carName = scanner.nextLine();
if(carName.isEmpty()){
System.out.println("Марка автомобиля не может быть пустой \n");
}
}
Comment on lines +11 to +17

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(carSpeed<0 || carSpeed > 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.

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

System.out.println("Введите скорость автомобиля №" + (i+1) + " в диапазоне от 0 до 250");
try{
carSpeed = scanner.nextInt();
} catch (Exception e) {
scanner.nextLine();
}

if(carSpeed < 0 || carSpeed > 250) {
System.out.println("Наверная скорость автомобиля\n");
}

}
Car car = new Car(carName, carSpeed);
cars.add(car);
}
Race megaRace = new Race();
for(Car car: cars){
megaRace.setLeader(car.name, car.speed);
}

System.out.println("Самая быстрая машина: " + megaRace.getLeader() );
}
}
}
17 changes: 17 additions & 0 deletions src/main/java/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class Race {
String leader = "";
int distance = 0;
Comment on lines +2 to +3

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

public void setLeader(String carName, int carSpeed){
int distance = 24*carSpeed;
if(distance > this.distance && !this.leader.equalsIgnoreCase(carName)){
this.distance = distance;
this.leader = carName;
} else {
this.distance = distance;
this.leader = carName;
}
}
public String getLeader(){
return this.leader;
}
}