gpt4 book ai didi

java - 有什么办法可以让这段代码更短吗?

转载 作者:行者123 更新时间:2023-12-02 11:16:03 25 4
gpt4 key购买 nike

这是一个简单的代码,但是,我想知道是否可以以某种方式使其更短,我什至不知道要寻找什么,所以我不想找人为我重写,我只想有人告诉我应该使用什么方法,如何调用用户在 if 外部编写的变量,或者这些对我有帮助的事情。我是编码新手,很抱歉如果我提出了一个愚蠢的问题。

    System.out.println("Write name: ");
name = s.nextLine();
System.out.println("Write last name: ");
lastName = s.nextLine();
System.out.println("Write id: ");
id = s.nextInt();
System.out.println("Write your average GPA: ");
average = s.nextDouble();

System.out.println("Your name is:" +name+ "\nYour last name is: "
+lastName+ "\nYour GPA is: " +average+ "\nYearly tuition is: "
+tuitionCost);

if(average >= 9.0){
System.out.println("Your discount is: 20% off.");
d = 100-20;
total = (d * tuitionCost)/100;
System.out.println("Your yearly tuition is: " +total);
}
else if(average <= 8.99 && average >= 8.5){
System.out.println("Your discount is: 10% off.");
d = 100-10;
total = (d * tuitionCost)/100;
System.out.println("Your yearly tuition is: " +total);
}
else if(average <= 8.49 && average >= 8.0){
System.out.println("Your discount is: 5% off.");
d = 100-5;
total = (d * tuitionCost)/100;
System.out.println("Your yearly tuition is: " +total);
}
else{
System.out.println("You have no discount. Your yearly tuition is: "
+tuitionCost);
}

最佳答案

您可以将折扣变成一类:

class Discount {
private final List<Tier> tiers = List.of(
new Tier(0.0, 0), new Tier(8.0, 5), new Tier(8.5, 10), new Tier(9.0, 20));

private class Tier {
private final double gpa;
private final int discount;
}

private int discount(double gpa) {
return tiers.stream().filter(t -> t.gpa <= gpa)
.mapToDouble(t -> t.discount).max().getAsDouble();
}

public double tuition(double gpa, double base) {
return (1.0 - discount(gpa)/100.0) * base;
}

public String discountMessage(double gpa) {
if (discount(gpa) == 0)
return "You have no discount";
else
return "Your discount is " + discount(gpa) + "%";
}
}

我遗漏了一些细节,但你明白了。

这可能有点过分了——这取决于等级变化的频率。但它确实满足了 DRY 原则(不要重复自己)。这使您的代码更具弹性:您不太可能在一处更改代码而忘记在其他地方更改它。

您提到要缩短代码。我赞同这样的原则:先求清晰,再求简洁。

关于java - 有什么办法可以让这段代码更短吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50283082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com