gpt4 book ai didi

java - 如何使用数组计算数字范围?

转载 作者:行者123 更新时间:2023-11-30 06:52:55 25 4
gpt4 key购买 nike

我的任务真的很简单。有人输入收入数字,如果低于 9000,则按 10% 征税,超过 9000 则按 15% 征税,等等。

但是其中一个要求是“您将在每种方法中将收入范围组织为数组,并选择一个数组记录来计算税级中的特定税”

那会如何运作?数组不是只接受特定值而不接受值范围吗?

这是我到目前为止的代码

public static int calcTax(int status, int income)
{
if (status == 0)
{
return singleFiling(income);
}
if (status == 1)
{
return jointFiling(income);
}
if (status == 2)
{
return headFiling(income);
}
else
System.out.println("Error: invalid status. Enter a number between 0 to 2 only.");
return income;

}

static int ninek = 9075;
static int thrirtysixk = 36900;
static int eightyninek = 89350;
static int oneeightysixk = 186350;
static int fourofivek = 405100;
static int fourosixk = 406750;
static int eighteenk = 18150;
static int seventythreek = 73800;
static int onefortyeightk = 148850;
static int twotwentysixk = 226850;
static int fourfivesevenk = 457600;
static int twelveninefifty = 12950;
static int fourninek = 49400;
static int onetwentysevenk = 127550;
static int twoosixk = 206600;
static int fpurthreetwok = 432200;

static double tax = 0;
static int singleFiling(double userIncome)
{
if (userIncome >= 1 && userIncome <= ninek )
tax = userIncome * 0.10;

System.out.println("Your payable Federal tax is: " + tax);

return 0;
}
static int jointFiling(double userIncome)
{
if (userIncome >= 1 && userIncome <= oneeightysixk )
tax = userIncome * 0.10;

System.out.println("Your payable Federal tax is: " + tax);

return 0;
}
static int headFiling(double userIncome)
{
if (userIncome >= 1 && userIncome <= twelveninefifty )
tax = userIncome * 0.10;

System.out.println("Your payable Federal tax is: " + tax);

return 0;
}
}

最佳答案

考虑到评论,您的代码可能如下所示:

static int[] incomeLevel = new int[]{9075, 186350, 12950};
static double[] taxRate = new double[]{.1, .15, .2}

static double tax = 0.0;

public static int calcTax(int status, int income) {
if (status < 0 || status > 2) {
System.out.println("Error: invalid status. Enter a number between 0 to 2 only.")
return income;
}
if (income > 0 && income <= incomeLevel[status])
tax = income * taxRate[status];
System.out.println("Your payable Federal tax is: " + tax)
return 0;
}

当然,必须添加收入水平的其他值,税率也是如此。

您可以使用状态作为数组索引,而不是在另一个方法中计算每个值,而是通过状态进行选择。这样做的优点是只需要一次代码,而不是三次,但需要一些其他值。

现在您只需检查您的状态是否在您想要的范围内。

关于java - 如何使用数组计算数字范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42408320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com