这里是Java新手。有人能指出为什么我的产出总是0.0美元吗
这是我写的。我主要参考了Java关于if。。。if-else语句,无法确定返回值始终为$0.0的原因这里是Java新手。有人能指出为什么我的产出总是0.0美元吗,java,Java,这是我写的。我主要参考了Java关于if。。。if-else语句,无法确定返回值始终为$0.0的原因 public class Ass1b { public static void main(String[] args) { //Importing two scanner classes for Text and Number inputs Scanner inText = new Scanner(System.in); Scann
public class Ass1b
{
public static void main(String[] args)
{
//Importing two scanner classes for Text and Number inputs
Scanner inText = new Scanner(System.in);
Scanner inNumber = new Scanner(System.in);
//Declaration of variables
String taxPayerName;
int taxPayerIncome;
double tax = 0;
//Message prompt asking user to enter a tax payers name and storing the input into the assigned String object
System.out.print("Please enter the name of the tax payer ==> ");
taxPayerName = inText.nextLine();
//Message prompt asking the user to enter the tax payers income and storing the input into the assigned Interger variable
System.out.print("Enter the income for " + taxPayerName + " ==> " );
taxPayerIncome = inNumber.nextInt();
if (taxPayerIncome > 18200) {
tax = 0;
} else if (taxPayerIncome > 37000) {
tax = (taxPayerIncome - 18200) * 0.19;
} else if (taxPayerIncome > 87000) {
tax = 3572 + (taxPayerIncome - 37000) * 0.325;
} else if (taxPayerIncome > 180000) {
tax = 19822 + (taxPayerIncome - 87000) * 0.37;
} else {
tax = 54232 + (taxPayerIncome - 180000) * 0.47;
}
//Message prompt stating the amount of tax the tax payer owes
System.out.println("The tax that " + taxPayerName + " has to pay is $" + tax);
}
}
应该像这样修改if表达式
if (taxPayerIncome > 18200 && taxPayerIncome < =37000) {
tax = 0;
} else if (taxPayerIncome > 37000 && taxPayerIncome <=87000) {
tax = (taxPayerIncome - 18200) * 0.19;
}
///and so on..
if(纳税人收入>18200&&taxPayerIncome<=37000){
税=0;
}否则如果(taxPayerIncome>37000&&taxPayerIncome首先,它不会:如果您输入一个的数字,问题在于您的If…else
代码块。如果taxPayerIncome在18200
之上,则会触发第一个If
。即使该值高于37000
或87000
第一个If
只有最后一个else
子句也很重要,因为它将获得18200
以下的所有值。但由于纳税额较低,它将返回非常低的值。通过将>翻转到a来修复此问题。您的计算是在int中完成的,然后转换为double。在int中,0.x是0。您需要显式地进行double计算。370000大于18200,因此if为true请尝试调试它。检查哪个if-else
块正在执行。@MohammedAtif如果这是错误的,则int乘以double将导致double。这里还有一个问题。if语句的顺序错误。请检查您的表达式,如果纳税人无论rIncome输入值>37000或>87000或>180000,它都>18200。这是逻辑错误。更好的是,颠倒顺序。
if (taxPayerIncome > 18200 && taxPayerIncome <= 37000)
if (taxPayerIncome > 180000) {
//calc
} else if (taxPayerIncome > 87000) {
//calc
} else if (taxPayerIncome > 37000) {
//calc
} else if (taxPayerIncome > 18200) {
//calc
} else { //below 18200
//calc
}