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
126 changes: 126 additions & 0 deletions java/pro/sky/java/course1/homework6/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package pro.sky.java.course1.homework6;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

@AlBrkn AlBrkn Jul 24, 2022

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.

  1. Формат компилируемых файлов должен быть *.java
  2. Класс с точкой входа принято называть Main
  3. Наименование файла должно совпадать с наименованием класса
  4. package подразумевает, что файл находится в директории, а не в корне проекта
  5. Желательно добавлять комментарий к классу в формате
    /* <Что делает класс>
    @autor Имя_Фамилия
    */

public static void checkYear(int year) {

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.

наименование checkIsLeap(int year) лучше отражает функциональность

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.printf("%d is a leap year\n", year);
} else {
System.out.printf("%d is not a leap year\n", year);
}
}

public static void checkOS(int deviceYear, int clientOS) {

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.

предлагаю выделить из данного метода два метода:

  1. метод получения OS - возвращать iOS или Android
  2. метод, который определяет, какое обновление нужно lite-version или full-version
    при этом нужно не забыть про модификаторы доступа

а в основной метод передавать результат выполнения предыдущих двух и печатать информацию через
System.out.println(String.format("Install the %s for %s at the link", typeOfUpdate, osName));

из плюсов- уходим от вложенности if-else.

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.

также нужно переименовать метод т.к. данное название не совсем отображает то, что делает метод

int currentYear = LocalDate.now().getYear();
if (clientOS == 1) {

@AlBrkn AlBrkn Jul 24, 2022

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.

вынести в константы значения, которые отвечают за определение OS
private static final int ANDROID_OS = 0;
private static final int IOS_OS = 1;

if (deviceYear < currentYear) {
System.out.println("Install the lite-version for iOS at the link");
} else if (deviceYear == currentYear) {
System.out.println("Install the full-version for iOS at the link");
} else {
System.out.println("Incorrect input!");
}
} else if (clientOS == 0) {
if (deviceYear < currentYear) {
System.out.println("Install the lite-version for Android at the link");
} else if (deviceYear == currentYear) {
System.out.println("Install the full-version for Android at the link");
} else {
System.out.println("Incorrect input!");
}
} else {
System.out.println("Incorrect input!");
}
}

public static int calcDeliveryTime(int deliveryDistance) {
int deliveryTime = 1;
if (deliveryDistance > 20) {
deliveryTime++;
}
if (deliveryDistance > 60) {

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.

условия >20 и >60 перекрывают друг-друга, соответственно
if (deliveryDistance > 60) можно убрать

deliveryTime++;
}
if (deliveryDistance <= 0) {
System.out.println("Incorrect input!");
return 0;
}
return deliveryTime;
}

public static void checkDoubles(String str) {

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.

предлагаю переименовать метод в checkDuplicateCharacter

for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == str.charAt(i + 1)) {
System.out.printf("Duplicate character '%c' found.\n", str.charAt(i));
return;
}
}
System.out.println("Duplicate characters not found.");
}

public static void reverseArrayOrder(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int t = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = t;
}
}

public static int[] generateRandomArray() {
java.util.Random random = new java.util.Random();
int[] arr = new int[30];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(100_000) + 100_000;
}
return arr;
}

public static double getAverage(int[] arr) {
double sum = getSum(arr);
double averageValue = sum / arr.length;
return averageValue;
}

public static double getSum(int[] arr) {

@AlBrkn AlBrkn Jul 24, 2022

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.

сумма целых чисел не может быть вещественным числом. возвращаемым значением должен быть int

int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}


public static void main(String[] args) {

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.

перенести данный метод в начало класса, так будет проще отследить что делает данный класс

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.

блоки(таски) предлагаю вынести в отдельные методы

//task1
Scanner input = new Scanner(System.in);
System.out.print("Enter the year: ");
int y = input.nextInt();
checkYear(y);
//task2
System.out.print("Enter the year of manufacture of the device: ");
int deviceYear = input.nextInt();
System.out.print("Enter 0 if you have Android OS or 1 if iOS: ");
int deviceOS = input.nextInt();
checkOS(deviceYear, deviceOS);
//task3
System.out.print("Enter the distance: ");
int dist = input.nextInt();
System.out.printf("Delivery will take %d days.\n", calcDeliveryTime(dist));
//task4
System.out.print("Enter some line: ");
String s = input.next();
checkDoubles(s);
input.close();
//task5
int[] array = {7, 4, 5, 8, 1};
reverseArrayOrder(array);
System.out.println("The reversed array looks like this: " + Arrays.toString(array));
//task6
int[] arr = generateRandomArray();
double averageArr = getAverage(arr);
System.out.printf("The average expenditure was %.2f rubles. \n", averageArr);
}
}