简体   繁体   English

我如何编写这些方法?

[英]How do I write these methods?

Using the following code.. I need to create two methods that take in two doubles.. dollarsNeeded returns an int number of dollars, and changeNeeded returns an int amount of change needed..使用下面的代码..我需要创建两个接受两个双打的方法..dollarNeeded 返回一个整数的美元数,changeNeeded 返回一个整数所需的更改量..

Here is the code I'm given..这是我得到的代码..


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);

    }
}

You will need a class that contains static methods, looking at your access calls it's not tied to an instantiated object.您将需要一个包含静态方法的类,查看您的访问调用,它与实例化对象无关。 Something like ths像这样的东西

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]
    }
}

Rounding functions Math.floor() might help so, and/or integer casting such as with (int) 15.30 will give you the integer 15舍入函数 Math.floor() 可能会有所帮助,和/或整数转换,例如(int) 15.30会给你整数 15

Add following class to your code:将以下类添加到您的代码中:

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)));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM