Java netbeans问题

mwkjh3gx  于 2022-11-10  发布在  Java
关注(0)|答案(1)|浏览(194)

请帮助我这个netbeans的任务代码。我已经工作了几个小时,我不明白它。

谢谢你!

nhn9ugyo

nhn9ugyo1#

现在我会避免使用原始的用户输入,而只专注于创建一个可重用的方法,在内部进行计算。没有理由强制转换为浮点型,因为所有的值都应该是浮点值。
calc方法会行程您已复制贴上三次的计算。

public class CalculateHalfLife {
    public static double calc(double amount, double halfLife, double hours) {
        return amount / (Math.pow(2, (hours / halfLife)));
    }

     public static void main(String[] args) {
        double amount = 100; // mg of caffeine
        double halfLife = 6; // hours

        double[] allHours = { 6, 12, 24 };

        for (double hours : allHours) {
            double output = calc(amount, halfLife, hours);
            System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
        }
    }
}

如果要支持用户输入,则应提示用户输入输入:

import java.util.Scanner;

public class CalculateHalfLife {
    private static double amount = 100; // mg of caffeine
    private static double halfLife = 6; // hours
    private static double[] allHours = { 6, 12, 24 };

    public static double calc(double amount, double halfLife, double hours) {
        return amount / (Math.pow(2, (hours / halfLife)));
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter an amount: ");
        float amount = sc.nextFloat();
        System.out.println();

        for (double hours : allHours) {
            double output = calc(amount, halfLife, hours);
            System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
        }

        sc.close();
    }
}

相关问题