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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
# Пустой репозиторий для работы с Java кодом в Android Studio
1я практическая работа. Черников Д.В.

17 changes: 17 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class Car {
private String name;
private int speed;
Comment on lines +2 to +3

Choose a reason for hiding this comment

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

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


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

public String getName() {
return name;
}

public int getSpeed() {
return speed;
}
}
42 changes: 40 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,44 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
Race race = new Race(); // создаем объект класса Race

for (int i = 1; i <=3; i++) { // цикл для ввода данных для 3 машин

// введение названия
System.out.println("Введите название машины №" + i + ":");
String name = scanner.nextLine(); // считываем название

while(name.isEmpty()) { // проверяем, вдруг название пусто

Choose a reason for hiding this comment

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

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

System.out.println("Название отсутствует. Введите название машины:");
name = scanner.nextLine();
}

// введение скорости
int speed;
while (true) { // цикл для ввода корректной скорости

Choose a reason for hiding this comment

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

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

System.out.println("Введите скорость машины №" + i + ":");

if (scanner.hasNextInt()) { // проверяем, что будет введено целое число
speed = scanner.nextInt();
scanner.nextLine(); //очистка буфера

if (speed > 0 && speed <= 250) { // проверяем, что скорость в диапазоне

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("Скорость должна быть в пределах 0 - 250");
}
} else {
System.out.println("Необходимо ввести число"); // если не число
scanner.nextInt(); // очситка буфера в случает неверного ввода
}
}

Car car = new Car(name, speed); // создаем объект класса Car
race.checkLeader(car); // проверяем, является ли эта машина лидером
}
System.out.println("Самая быстрая машина: " + race.getLeaderName());
}
}
}
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 {
private String leaderName = "";
private int leaderDistance = 0;

public void checkLeader(Car car) {
int distance = car.getSpeed() * 24;

if (distance > leaderDistance) {
leaderDistance = distance;
leaderName = car.getName();
}
}

public String getLeaderName() {
return leaderName;
}
}