当使用其中一个for循环时,我需要打破if语句。但是当我编译并运行它时,当我只需要一个时,所有三个for循环都会返回信息。我知道答案是盯着我看,但我无法弄清楚它是什么。
if (filestat == 'S' || filestat == 's')
{
for ( a = 0; a < 5000; a++)
{
taxableincome = grossincome - 5000 - (1000 * exemptions);
taxrate = .15;
taxAmount = taxableincome * taxrate;
System.out.println("Your Taxpayer ID is " + taxid);
System.out.println("Your taxable income is $" + taxableincome);
System.out.println("Your tax rate is %" + taxrate);
System.out.println("Your tax amount is $" + taxAmount);
break;
}
for (a = 5000; a <= 20000; a++)
{
taxableincome = grossincome - 5000 - (1000 * exemptions);
taxrate = .22;
taxAmount = taxableincome * taxrate;
System.out.println("Your Taxpayer ID is " + taxid);
System.out.println("Your taxable income is $" + taxableincome);
System.out.println("Your tax rate is %" + taxrate);
System.out.println("Your tax amount is $" + taxAmount);
break;
}
for (a = 20001; a >= 20001; a++)
{
taxableincome = grossincome - 5000 - (1000 * exemptions);
taxrate = .31;
taxAmount = taxableincome * taxrate;
System.out.println("Your Taxpayer ID is " + taxid);
System.out.println("Your taxable income is $" + taxableincome);
System.out.println("Your tax rate is %" + taxrate);
System.out.println("Your tax amount is $" + taxAmount);
break;
}
}
答案 0 :(得分:0)
如果要打印所有可能a
的输出,只需删除break
语句即可。 (但是你必须为第三个循环提供一个上限。)
如果您只想为一个特定a
打印输出,则应使用if
代替for
。
if (filestat == 'S' || filestat == 's')
{
if (a < 5000)
{
taxableincome = grossincome - 5000 - (1000 * exemptions);
taxrate = .15;
taxAmount = taxableincome * taxrate;
}
else if (a <= 20000)
{
taxableincome = grossincome - 5000 - (1000 * exemptions);
taxrate = .22;
taxAmount = taxableincome * taxrate;
}
else
{
taxableincome = grossincome - 5000 - (1000 * exemptions);
taxrate = .31;
taxAmount = taxableincome * taxrate;
}
}
System.out.println("Your Taxpayer ID is " + taxid);
System.out.println("Your taxable income is $" + taxableincome);
System.out.println("Your tax rate is %" + taxrate);
System.out.println("Your tax amount is $" + taxAmount);
答案 1 :(得分:0)
当使用其中一个for循环时,我需要打破if语句。
这根本没有意义。因为在if
语句中,所有循环至少无条件地运行一次(无论break
语句都没有意义),你不能指望Java神奇地“选择”其中一个循环。
如果您不想运行后两者,为什么不删除它们呢?
答案 2 :(得分:0)
我猜你试图根据a的值进行计算,你可以使用嵌套的if-else语句而不是使用循环并在第一次迭代时将其分解。
`if (filestat == 'S' || filestat == 's')
{
if( a >= 0 && a < 5000 )
//do some work
else if( a >= 5000 && a <= 20000 )
//do some work
else if( a > 20000)
//do some work
}`
您可以选择将代码包装在函数中并将税率作为参数传递,因为它是唯一取决于a的值的变量。