谁帮我写一下

lcsdss 2014-05-10 02:05:14


这个怎么做啊 我不会。。。
...全文
215 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
日知己所无 2014-05-10
  • 打赏
  • 举报
回复

import java.math.*;
import java.util.*;

public class CalculateGratuity {

    public static void main(final String[] args) {
        try {
            boolean calculateResult = calculateGratuity();
            if (!calculateResult) {
                System.out.println(ErrorMessage);
            }
        } catch (Exception e) {
            System.out.println(ErrorMessage);
        }
    }

    public static boolean calculateGratuity() {
        boolean returnValue = false;
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Enter the subtotal and a gratuity rate:");
            String scannerNextLine = scanner.nextLine();
            String[] scannerNextLineArray = scannerNextLine.split(" ");

            if (scannerNextLineArray.length == 2) {
                BigDecimal subtotal = new BigDecimal(scannerNextLineArray[0]);
                BigDecimal gratuityRate = new BigDecimal(scannerNextLineArray[1]);

                // gratuity = subtotal * gratuityRate / 100
                BigDecimal gratuity
                        = subtotal.multiply(gratuityRate).divide(BigDecimal.valueOf(100.0)).
                        setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();

                // total = subtotal + gratuity
                BigDecimal total
                        = subtotal.add(gratuity).
                        setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros();

                System.out.println("The gratuity is " + gratuity + " and total is " + total);

                returnValue = true;
            }
        } catch (Exception e) {
            throw (e);
        }

        return returnValue;
    }

    private static final String ErrorMessage = "Cann't Calculate the Gratuity!";
}
输入输出1:(原题的正常值) Enter the subtotal and a gratuity rate:15.69 15 The gratuity is 2.35 and total is 18.04 输入输出2:(楼主给出的正常值) Enter the subtotal and a gratuity rate:10 15 The gratuity is 1.5 and total is 11.5 输入输出3:(缺少一个值的时候) Enter the subtotal and a gratuity rate:10 Cann't Calculate the Gratuity! 输入输出4:(输入值是字母的时候) Enter the subtotal and a gratuity rate:subtotal gratuity Cann't Calculate the Gratuity!

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧