【发布时间】:2016-03-21 09:55:41
【问题描述】:
我正在尝试使下面的嵌套语句正常工作,但在让它们在第一条语句之后执行时遇到问题。我尝试嵌套语句,但只是第一个 if 执行。非常感谢任何有关格式化的反馈,我知道可能有更有效的方法来实现这一点,但我必须使用嵌套语句执行代码。
package incometax;
import java.util.Scanner;
import java.text.DecimalFormat;
public class IncomeTax {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
DecimalFormat df = new DecimalFormat ("#,###,000.00");
String singleStatus = "single";
String marriedStatus = "married";
String maritalStatus = "";
double annualIncome = 0;
double taxAmount = 0;
System.out.println("Please enter your martial status: ");
maritalStatus = scnr.next();
if (maritalStatus.compareTo(singleStatus) == 0){
System.out.println("Please enter your annual income: ");
annualIncome = scnr.nextDouble();
if (annualIncome <= 30000){
taxAmount = (annualIncome * .15);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) + " your tax is " + "$ " +
df.format(taxAmount));
if (annualIncome > 30000){
taxAmount = (annualIncome * .25);
System.out.println("Based on annual income of "+ "$ " +
df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
}
}
else {
if (maritalStatus.compareTo(marriedStatus) == 0){
if(annualIncome <= 30000){
taxAmount = (annualIncome * .12);
System.out.println("Based on annual income of "+ "$ "
+ df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
if(annualIncome > 30000){
taxAmount = (annualIncome * .20);
System.out.println("Based on annual income of "+
"$ " + df.format(annualIncome) +
" your tax is " + "$ " + df.format(taxAmount));
}
}
}
}
}
}
}
【问题讨论】:
-
你试过调试了吗?
-
如果你的缩进是一致的,就会更容易看到发生了什么。
-
你的条件永远不会是真的。例如,在
if (annualIncome <= 30000)的块内,您有if (annualIncome > 30000),这将始终为假,因为annualIncome没有改变。 -
不要使用嵌套语句,将它们更改为更简单的语句,使用提前返回模式。
-
您的 IDE 应该能够为您修复缩进。在我的 Eclipse(在 Mac 上)中,command-shift-F 可以解决问题。
标签: java if-statement nested