Есть ли другой способ написать предложение if ... if else ... в этом случае? - PullRequest
0 голосов
/ 08 февраля 2020
public class Sales {
    public static void main(String[] args) {
        int ursales = 6000;
        int target = 3000;

        if (ursales >= 2 * target) {
            System.out.println("performance Excellent");
            System.out.println("bouns 1000");
        } else if (ursales >= 1.5 * target) {
            System.out.println("performance Fine");
            System.out.println("bouns 500");
        } else if (ursales >= target) {
            System.out.println("performance Satisfactory");
            System.out.println("bouns 100");
        } else {
            System.out.println("You Are Fired!");
        }
    }
}

Я пытался написать каждое утверждение как:

performance = "...";
bonus = "...";

, но оно не сработало.

Может кто-нибудь сказать мне, есть ли другой способ написать это заявление без System.out.println?

Ответы [ 6 ]

1 голос
/ 08 февраля 2020

Готовы ли вы к многословию? Мы определяем интерфейс Bonus , который определяет, достигает ли объем продаж цели, определенной реализацией. Затем мы создаем упорядоченный поток, а затем возвращаем первый результат в потоке, которому соответствует фильтр . Плюсом этого подхода является то, что если вы хотите добавить больше бонусов в будущем, это чрезвычайно легко сделать.

    interface Bonus {

        boolean hit(int sales, int target);

    }

    static class ExcellentBonus implements Bonus {

        @Override
        public boolean hit(int sales, int target) {
            return sales >= target * 2;
        }

    }

    static class FineBonus implements Bonus {

        @Override
        public boolean hit(int sales, int target) {
            return sales >= target * 1.5;
        }
    }

    static class SatisfactoryBonus implements Bonus {


        @Override
        public boolean hit(int sales, int target) {
            return sales >= target;
        }
    }

    static class FiredBonus implements Bonus {

        @Override
        public boolean hit(int sales, int target) {
            return sales < target;
        }
    }

    public static void main(String[] args) {
        int sales = 100;

        int target = 50;

        Bonus bonus = Stream.of(new ExcellentBonus(), new FineBonus(), new SatisfactoryBonus())
                .filter(b -> b.hit(sales, target)).findFirst().orElse(new FiredBonus());

    }
1 голос
/ 08 февраля 2020

ТАК вот так?

String performance;
int bonus;

if (ursales >= 2 * target) {
    performance = "performance Excellent";
    bonus = 1000;
} else if (ursales >= 1.5 * target) {
    performance = "fine";
    bonus = 500;
} else ... etc..

System.out.println("performance " + performance );
System.out.printkn("bouns " +  bonus );
0 голосов
/ 09 февраля 2020

Это решение похоже на @ ответ Джейсона , но использует немного другой контракт. Это похоже на то, как он определяет класс для представления результата оценки производительности. Он отличается по форме тем, что позволяет определять карту факторов для оценки эффективности.

Ideone demo

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Main {
    public static void main(final String... args) {
        final String FORMAT = "Performance %s\nbonus %d";
        final Map<Double, PerformanceResult> performanceResultMap = new HashMap<>();
        performanceResultMap.put(2.0, new PerformanceResult("Excellent", 1000));
        performanceResultMap.put(1.5, new PerformanceResult("Fine", 500));
        performanceResultMap.put(1.0, new PerformanceResult("Satisfactory", 100));

        final PerformanceResult excellent =
                calculatePerformance(200.0, 100.0, performanceResultMap);
        System.out.println(String.format(FORMAT, excellent.getMessage(), excellent.getBonus()));

        final PerformanceResult fine = calculatePerformance(150.0, 100.0, performanceResultMap);
        System.out.println(String.format(FORMAT, fine.getMessage(), fine.getBonus()));

        final PerformanceResult satisfactory =
                calculatePerformance(100.0, 100.0, performanceResultMap);
        System.out.println(String.format(FORMAT, satisfactory.getMessage(), satisfactory.getBonus()));

        try {
            calculatePerformance(0, 100, performanceResultMap);
            throw new IllegalStateException("Exception should have been thrown");
        } catch (final NoFittingPerformanceResultFoundException e) {
            System.out.println("Expected exception thrown");
        }
    }

    public static PerformanceResult calculatePerformance(
            final double actual,
            final double target,
            final Map<Double, PerformanceResult> performanceResultMap) {
        return performanceResultMap.keySet().stream()
                .sorted(Collections.reverseOrder())
                .filter(factor -> actual >= target * factor)
                .findFirst()
                .map(performanceResultMap::get)
                .orElseThrow(NoFittingPerformanceResultFoundException::new);
    }
}

class PerformanceResult {
    private final String message;
    private final int bonus;

    PerformanceResult(final String message, final int bonus) {
        this.message = Objects.requireNonNull(message);
        this.bonus = bonus;
    }

    public String getMessage() {
        return message;
    }

    public int getBonus() {
        return bonus;
    }
}

class NoFittingPerformanceResultFoundException extends IllegalStateException {}
0 голосов
/ 08 февраля 2020

Вы можете использовать StringBuilder для объединения всех необходимых вам строк и распечатывать их сразу в конце.

0 голосов
/ 08 февраля 2020

Вы можете сделать это следующим образом:

public class Main {
    public static void main(String[] args) {
        int ursales = 6000;
        int target = 3000;
        String output = ursales >= 2 * target ? "performance Excellent\nbouns 1000"
                : (ursales >= 1.5 * target ? "performance fine\nbouns 500"
                        : (ursales >= target ? "performance Satisfactory\nbouns 100" : "You Are Fired!"));
        System.out.println(output);
    }
}

Вывод:

performance Excellent
bouns 1000

Подробнее о троичный оператор при https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

0 голосов
/ 08 февраля 2020

Вместо использования System.out.println() вы можете использовать System.out.print(). Это не создаст никаких новых строк при печати на консоль.

...