每日一练110——Java提示计算器(8kyu)

题目

完成该功能,根据账单和服务的总金额计算您需要提示的数量。

您需要考虑以下评级:

  • Terrible可怕: tip小费 0%
  • Poor差: tip 5%
  • Good好: tip 10%
  • Great太棒了: tip 15%
  • Excellent优秀: tip 20%

评级不区分大小写(所以"great" = "GREAT")。如果收到无法识别的评级,则需要返回:

  • 在Java中返回......或者null

因为你是一个好人,无论服务如何,你总是围绕小费。

解题

My:

public class TipCalculator {

  public static Integer calculateTip(double amount, String rating) {
    double n = 0;
    if ("terrible".equals(rating.toLowerCase())) {
      n = 0;
    } else if ("poor".equals(rating.toLowerCase())) {
      n = 0.05;
    } else if ("good".equals(rating.toLowerCase())) {
      n = 0.1;
    } else if ("great".equals(rating.toLowerCase())) {
      n = 0.15;
    } else if ("excellent".equals(rating.toLowerCase())) {
      n = 0.20;
    } else {
      return null;
    }
    return (int)Math.ceil(n * amount); // 向上取整并强制转换int
  }
}

Other:

public class TipCalculator {

  public static Integer calculateTip(double amount, String rating) {
   
    switch(rating.toLowerCase()) {
      case "terrible": return 0;
      case "poor": return (int) Math.ceil(amount * 0.05);
      case "good": return (int) Math.ceil(amount * 0.1);
      case "great": return (int) Math.ceil(amount * 0.15);
      case "excellent": return (int) Math.ceil(amount * 0.2);
      default: return null;      
    }   
  }
}
import java.util.HashMap;
import java.util.Map;

public class TipCalculator {

    private static Map<String, Integer> tips = new HashMap<>();

    static {
        tips.put("terrible", 0);
        tips.put("poor", 5);
        tips.put("good", 10);
        tips.put("great", 15);
        tips.put("excellent", 20);
    }

    public static Integer calculateTip(double amount, String rating) {
        Integer tipRating = tips.get(rating.toLowerCase());
        if (tipRating == null) return null;
        return (int) Math.ceil(tipRating * amount / 100);
    }
}

后记

用字典也挺不错的样子。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • abandon, desert, forsake, leave, give up abandon :强调永远或完全...
    sunxiaohang阅读 3,845评论 0 3
  • Unit1 Chapter1 When are you leaving for Mumbai?你什么时候动身去孟买...
    AsaGuo阅读 528评论 0 0
  • 题目 创建一个“你在玩班卓琴吗?”这个问题回答的函数。如果您的名字以字母“R”或小写字母“r”开头,那么您正在玩班...
    砾桫_Yvan阅读 222评论 0 0
  • 黑夜与白天 相隔一瞬间 60牧慕 “你爱人的脸色太差,不适合拍婚纱照。”好心的摄影师提醒我们。其实,我知道,她何止...
    草原上的咩咩羊阅读 313评论 0 0

友情链接更多精彩内容