有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何编写这些方法?

使用以下代码。。我需要创建两个接受两个double的方法。。DollarSeeded返回整数美元,ChangeReeded返回整数金额的所需更改

这是给我的代码


import javax.swing.JOptionPane;

public class MoneyNeededTester
{
    public static void main(String[] args)
    {
        double a = 5.05, b = 10.25;

        String output = "";

        output = "If you purchased an item that cost $" +a+ ", and another that cost $"+b+"\n";
        output += "it would cost you " + MoneyNeeded.dollarsNeeded(a,b) +" dollars and "+MoneyNeeded.changeNeeded(a,b)+" cents.";
        output += "\naccording to your program.\n\n";
        output += "(The correct answer was 15 dollars and 30 cents)";
        JOptionPane.showMessageDialog(null, output);


        a = 5.82; b = 6.25;

        output = "If you purchased an item that cost $" +a+ ", and another that cost $"+b+"\n";
        output += "it would cost you " + MoneyNeeded.dollarsNeeded(a,b) +" dollars and "+MoneyNeeded.changeNeeded(a,b)+" cents.";
        output += "\naccording to your program.\n\n";
        output += "(The correct answer was 12 dollars and 7 cents)";
        JOptionPane.showMessageDialog(null, output);



        a = 5.75; b = 3.56;

        output = "If you purchased an item that cost $" +a+ ", and another that cost $"+b+"\n";
        output += "it would cost you " + MoneyNeeded.dollarsNeeded(a,b) +" dollars and "+MoneyNeeded.changeNeeded(a,b)+" cents.";
        output += "\naccording to your program.\n\n";
        output += "(The correct answer was 9 dollars and 32 cents- or perhaps 31 if your computer is annoying)";
        JOptionPane.showMessageDialog(null, output);

    }
}

共 (2) 个答案

  1. # 1 楼答案

    您需要一个包含静态方法的类,查看您的访问调用—它不绑定到实例化对象。类似于

    public class MoneyNeeded {
        public static int dollarsNeeded(double a, double b) {
            // fill in your int-returns here
            return // [int value]
        }
        public static int changeNeeded(double a, double b) {
            // and here
            return // [int value]
        }
    }
    

    四舍五入函数数学。floor()可能会有帮助,和/或整数转换(如使用(int) 15.30)将得到整数15

  2. # 2 楼答案

    将以下类添加到代码中:

    class MoneyNeeded {
    
        static int dollarsNeeded(double cost1, double cost2) {
    
            return (int) Math.floor(cost1 + cost2);
        }
    
        static int changeNeeded(double cost1, double cost2) {
    
            double total = cost1 + cost2;
            return (int) (100 * (total - Math.floor(total)));
        }
    }