我的问题是这样的,有N个人。考虑到N = 9,我必须找到那些人的应税收入。我已经为1名员工完成了数学运算,但是,将其应用于其他8个人则是重复代码太多。我可以将IF语句放入FOR循环中吗?我已经尝试过了,但是它在FOR循环中显示了一个错误(即变量N已经在main(String [])方法中定义了
public class IncomeTax {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,Tax = 0,N = 1;
System.out.print("Enter the Taxable Income of the Employee " +N+":");
i = input.nextInt();
for( int N=1 ;N<=9 ; N++ ){
if( i >= 0 & i<18200)
Tax = 0;
if( i >= 18201 & i<37000)
Tax = (int) (( i - 18200) * 0.19);
if( i >= 37001 & i<87000)
Tax = (int) ((( i - 37000) * 0.325)+3572);
if( i >= 87001 & i<180000)
Tax = (int) ((( i - 18200) * 0.37)+19822);
if( i >= 180001 )
Tax = (int) ((( i - 18200) * 0.45)+54097);
System.out.println("The Income Tax for the employee "+N+" is " + Tax);
}
}
}
输出应为N = 9,分别是雇员人数和他们的税收。 输入员工的应税收入: 员工所得税1: 输入员工的应税收入:2: 员工2的所得税: 输入员工的应税收入:3: 员工3的所得税:
答案 0 :(得分:0)
您应该将input.nextInt()
代码粘贴到for循环中。并从int i,Tax = 0,N = 1;
声明中删除N变量。因为您已经在for循环中声明了它。
解决方案:
public class IncomeTax {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,Tax = 0;
for( int N=1; N<=9; N++ ){
System.out.print("Enter the Taxable Income of the Employee " +N+":");
i = input.nextInt();
if( i >= 0 & i<18200)
Tax = 0;
if( i >= 18201 & i<37000)
Tax = (int) (( i - 18200) * 0.19);
if( i >= 37001 & i<87000)
Tax = (int) ((( i - 37000) * 0.325)+3572);
if( i >= 87001 & i<180000)
Tax = (int) ((( i - 18200) * 0.37)+19822);
if( i >= 180001 )
Tax = (int) ((( i - 18200) * 0.45)+54097);
System.out.println("The Income Tax for the employee "+N+" is " + Tax);
}
}
}
答案 1 :(得分:0)
您绝对可以在for循环中使用if语句-由于在for循环中重新声明了变量N
,因此会出现错误。我建议要么使用其他变量字母,要么根本不在扫描仪下方声明它。
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i,Tax = 0;
System.out.print("Enter the Taxable Income of the Employee " +N+":");
i = input.nextInt();
for( int N=1 ;N<=9 ; N++ ){
if( i >= 0 & i<18200)
Tax = 0;
if( i >= 18201 & i<37000)
Tax = (int) (( i - 18200) * 0.19);
if( i >= 37001 & i<87000)
Tax = (int) ((( i - 37000) * 0.325)+3572);
if( i >= 87001 & i<180000)
Tax = (int) ((( i - 18200) * 0.37)+19822);
if( i >= 180001 )
Tax = (int) ((( i - 18200) * 0.45)+54097);
System.out.println("The Income Tax for the employee "+N+" is " + Tax);
}
}