我该如何编写这些方法?

时间:2015-09-03 22:00:47

标签: java

使用以下代码..我需要创建两个接收两个双精度数的方法.canyNeeded返回一个int数的美元,而changeNeeded返回一个int所需的更改量。

这是我给出的代码..

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 个答案:

答案 0 :(得分:0)

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

的东西
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]
    }
}

舍入函数Math.floor()可能会有所帮助,和/或整数转换(如(int) 15.30)将为您提供整数15

答案 1 :(得分:-1)

将以下类添加到您的代码中:

$objPHPExcel->getActiveSheet()->getCell('B3')->getValue();