@GromTron121

Как можно упростить этот java код?

Ребята, подскажите как можно было бы упростить этот код :
String path1 = "";  // Пути к файлам 
        String path2 = "";

        File file = new File(path1);
        Scanner sc = new Scanner(file);
        PrintWriter pw = new PrintWriter(path2);

        String match1 = sc.nextLine();
        String match2 = sc.nextLine();
        String match3 = sc.nextLine();
        String match4 = sc.nextLine();
        
        String scMatch1[] = match1.split(" ");
        String scMatch2[] = match2.split(" ");
        String scMatch3[] = match3.split(" ");
        String scMatch4[] = match4.split(" ");

        int a1 = Integer.parseInt(scMatch1[0]);
        int a2 = Integer.parseInt(scMatch2[0]);
        int a3 = Integer.parseInt(scMatch3[0]);
        int a4 = Integer.parseInt(scMatch4[0]);

        int b1 = Integer.parseInt(scMatch1[1]);
        int b2 = Integer.parseInt(scMatch2[1]);
        int b3 = Integer.parseInt(scMatch3[1]);
        int b4 = Integer.parseInt(scMatch4[1]);

        if(a1+a2+a3+a4 > b1+b2+b3+b4){
            System.out.println("1");
            pw.print("1");
        } else if(a1+a2+a3+a4 < b1+b2+b3+b4){
            System.out.println("2");
            pw.print("2");
        } else {
            System.out.println("DRAW");
            pw.print("DRAW");
        }
        sc.close();
        pw.close();
  • Вопрос задан
  • 153 просмотра
Пригласить эксперта
Ответы на вопрос 2
@p_A_m_A_git_I
Не использовать в продакшене. ̶Е̶с̶т̶ь̶ ̶ш̶а̶н̶с̶ ̶ч̶т̶о̶ ̶в̶а̶с̶ ̶п̶о̶б̶ь̶ю̶т̶.̶

public class Main {
    public static void main(String[] args) throws Exception {
        String inputFile = "", outputFile = "";
        String res = Files.lines(Paths.get(inputFile))
                .map(line -> new int[]{
                        Integer.parseInt(line.split(" ")[0]),
                        Integer.parseInt(line.split(" ")[1])}
                ).reduce((identity, accumulator) -> new int[]{
                        identity[0] + accumulator[0],
                        identity[1] + accumulator[1]
                }).map(resArr -> {
                    if (resArr[0] > resArr[1]) return "1";
                    if (resArr[0] < resArr[1]) return "2";
                    return "DRAW";
                }).get();

        PrintWriter printWriter = new PrintWriter(outputFile);
        printWriter.write(res);
        printWriter.close();
    }
}
Ответ написан
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
Добрый день. А можно ли узнать вашу конечную цель? Что вы пытаетесь реализовать?
Код действительно можно сократить, а то и лучше улучшить восприятие.
1) создайте 2 метода, первый из которых будет читать файл, а второй писать в файл. Можно воспользоваться возможностями класса Files из Java 8
2)
String match1 = sc.nextLine();
        String match2 = sc.nextLine();
        String match3 = sc.nextLine();
        String match4 = sc.nextLine();
        
        String scMatch1[] = match1.split(" ");
        String scMatch2[] = match2.split(" ");
        String scMatch3[] = match3.split(" ");
        String scMatch4[] = match4.split(" ");

        int a1 = Integer.parseInt(scMatch1[0]);
        int a2 = Integer.parseInt(scMatch2[0]);
        int a3 = Integer.parseInt(scMatch3[0]);
        int a4 = Integer.parseInt(scMatch4[0]);

        int b1 = Integer.parseInt(scMatch1[1]);
        int b2 = Integer.parseInt(scMatch2[1]);
        int b3 = Integer.parseInt(scMatch3[1]);
        int b4 = Integer.parseInt(scMatch4[1]);

тут происходит что-то странное. Скорее всего тут есть ошибка.
Вы сперва читаете строку, затем разделяете ее пробелом в массив строк, но потом почему-то присваиваете a1, а2. а3. а4 одно и то же число.
int a1 = Integer.parseInt(scMatch1[0]);
        int a2 = Integer.parseInt(scMatch2[0]);
        int a3 = Integer.parseInt(scMatch3[0]);
        int a4 = Integer.parseInt(scMatch4[0]);

скорее всего должно быть так:
int a1 = Integer.parseInt(scMatch1[0]);
        int a2 = Integer.parseInt(scMatch2[1]);
        int a3 = Integer.parseInt(scMatch3[2]);
        int a4 = Integer.parseInt(scMatch4[3]);

Такая же ситуация с перемеными b1, b2, b3, b4.
А что если человек введет не 4 элемента через пробел, а 5 и более? Или наоборот менее 4-х элементов?

Подобные выражения a1+a2+a3+a4 > b1+b2+b3+b4 с точки зрения clean code можно вынести в отдельную переменную типа boolean.
Например,
boolean isSumAGreaterThanSumB = a1+a2+a3+a4 > b1+b2+b3+b4;

Ну а далее if (isSumAGreaterThanSumB ) { ... }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы