java - 将 double 变量从一种方法传递到另一种方法

标签 java variables methods

我有一个计算收入应付税款的程序。第一个方法taxPayable() 计算将为此收入支付的税额,第二个方法 IncomeRemaining() 应该计算扣除税款后剩余的收入,但可变税将变回其第一个赋值0。我如何更改我的代码,以便将其转移到下一个方法?

public class TaxCalculator {
static double tax = 0;
public static void taxPayable(int income) {
    if (0 <= income && income <= 100) {
        double tax = 0;
        System.out.print("Tax payable on this income is equal to " + tax);
    }
    else if (101 <= income && income <= 150) {
        double tax = 0 + (income-100)*0.1;
        System.out.print("Tax payable on this income is equal to " + tax);
    }
    else if (151 <= income && income <= 200) {
        double tax = 0 + 50*0.1 + (income-150)*0.2;
        System.out.print("Tax payable on this income is equal to " + tax);
    }
    else if (201 <= income && income <= 300) {
        double tax = 0 + 50*0.1 + 50*0.2 + (income-200)*0.4;
        System.out.print("Tax payable on this income is equal to " + tax);
    }
    else if (301 <= income && income <= 400) {
        double tax = 0 + 50*0.1 + 50*0.2 + 100*0.4 + (income-300)*0.6;
        System.out.print("Tax payable on this income is equal to " + tax);
    }
    else {
        double tax = 0 + 50*0.1 + 50*0.2 + 100*0.4 + 100*0.6 + (income-400)*1.2;
        System.out.print("Tax payable on this income is equal to " + tax);
    }
}
public static void incomeRemaining(int income) {
    TaxCalculator.taxPayable(income);
    double $$ = income - tax;
    System.out.println("\nIncome remaining after tax is equal to " + $$);
}
public static void main(String[] args) {
    TaxCalculator.incomeRemaining(400);
}

}

最佳答案

您的问题是您的方法内的本地变量tax遮蔽外部静态tax变量。

所以你的代码更新了“内部”税;但不是外部。

因此:只需删除所有这些

double tax = 0;

方法正文中的语句!

但是:更好的方法是您的方法返回该值。使用全局变量来“传达”值没有多大意义;当你的方法可以简单地返回它们时!因此,将方法从“void”更改为“double”,然后简单地返回计算值!

另外:您无缘无故地复制了这些打印语句。只需在方法末尾执行 one 打印即可!说真的:每当你有两段代码做完全相同的事情时......以某种方式摆脱第二段!

最后:永远不要在代码中使用特殊字符,例如 $ 来表示变量/方法/...名称!

关于java - 将 double 变量从一种方法传递到另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40132831/

相关文章:

java - 使用 ViewModel 仅在用户干预时调用

根据文件中的数字创建新变量 - C

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

Java - 通过从文本文件中选择特定数字来创建字符串

algorithm - 递归函数的最小深度/基础深度是多少,0 还是 1?

java - 使用 Java 中的 log4j2 进行 Windows 事件日志记录

java - 倒计时什么时候开始将数据插入数组java

java - 使用字符串名称创建变量

post - PayPal `rm` 隐藏值不返回 POST 数据

java - 无法获取 Ajax 响应中的值