1

我的作业是为一家正在补充库存的珠宝店计算税金和附加费,我遇到了一个小问题。我正在使用一种名为 calcExtraTax 的方法三次来计算劳动率以及州和联邦税。然后,我需要获取该方法的每个实例的结果,并将值传递给我的 main 方法中的适当变量。这就是我的代码现在的样子(显然不完整):

import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.JOptionPane;

public static void main(String[] args)
{

double stateRate = 0.1;
double luxuryRate = 0.2;
double laborRate = 0.05;
double extraCharge;
int numOrdered;
double diamondCost;
double settingCost;
double baseCost;
double totalCost;
double laborCost;
double stateTax;
double luxuryTax;
double finalAmountDue;

    Scanner keyInput = new Scanner(System.in);

    System.out.println("What is the cost of the diamond?");
    diamondCost = keyInput.nextDouble();
    System.out.println("What is the cost of the setting?");
    settingCost = keyInput.nextDouble();
    System.out.println("How many rings are you ordering?");
    numOrdered = keyInput.nextInt();

    baseCost = diamondCost + settingCost;
    calcExtraCost(baseCost, laborRate);
    laborCost = extraCharge;
    calcExtraCost(baseCost, stateRate);
    stateTax = extraCharge;
    calcExtraCost(baseCost, luxuryRate);
    luxuryTax = extraCharge;
    totalCost = baseCost + laborCost + stateTax + luxuryTax;
    finalAmountDue = numOrdered*totalCost;
    JOptionPane.showMessageDialog(null, "The final amount due is = " + finalAmountDue);
}
public static void calcExtraCost(double diamond, double rate)
{
    double extraCharge = diamond*rate;
    ???????????
}

我想弄清楚的是我还需要在我的辅助方法中添加什么,以便能够每次根据公式中使用的费率变量将结果传递到不同的税收成本变量中。

4

2 回答 2

1

diamond*rate您可以通过将其签名从更改voiddouble并添加一条return语句从您的辅助方法返回值:

public static double calcExtraCost(double diamond, double rate)
{
    return diamond * rate;
}

现在您可以将调用结果分配给 main 方法中的变量:

laborCost = calcExtraCost(baseCost, laborRate);
于 2013-03-19T23:20:39.017 回答
1

calcExtraCost除了将返回类型更改为 double 并返回计算值之外,您不需要对您做任何特别的事情。例如

public static double calcExtraCost(double diamond, double rate)
{
    double extraCharge = diamond*rate;
    double tax = //some calculations
    return tax
}

所以这个方法会返回计算出来的值。

在您的主要方法中,您需要将该值存储到您想要的适当双精度。例如,如果您想计算luxuryTax,那么您可以执行以下操作:

luxuryTax = calcExtraCost(baseCost, luxuryRate);

还有一些建议,而不是让你的方法static,让它成为一个non-static方法,并创建一个定义你的方法的类的对象,并在该对象上调用该方法。

例如,如果您定义方法的类称为 Tax,那么您将创建一个 Tax 对象:

Tax tax = new Tax();

并调用calcExtraCost该对象:

tax.calcExtraCost();

这样您就可以删除该方法的静态部分。所以你的方法签名变成了这样:

public double calcExtraCost(double diamond, double rate)
于 2013-03-19T23:19:21.907 回答