Java Tax计划帮助赞赏 - 哨兵while循环

时间:2014-09-24 16:36:22

标签: java

我正在编写一个程序,我需要输入以下内容:客户ID,他们的收入,联邦预扣税,州预扣税和扣除额。但是,当我运行我的程序时,它会询问我的customerID,就是这样......我不确定这里有什么不对。

 // Get first Customer ID
{ while(customerID != -1)
{
  System.out.print("Enter Customer ID: ");
  customerID = input.nextInt();
  // Get income and withholding information

  System.out.print("Enter Income: ");
       income = input.nextDouble();

  System.out.print("Enter Federal Taxes Withheld: ");
  federalwh = input.nextDouble();

  System.out.print("Enter State Taxes Withheld: ");
  statewh = input.nextDouble();

  System.out.print("Enter Deductions: ");
  deduction = input.nextDouble();
}

  // Get next Customer ID
 System.out.println("Enter Customer ID: ");
  customerID = input.nextInt();

2 个答案:

答案 0 :(得分:0)

尝试删除分号

if(taxableIncome > 20000 && taxableIncome <= 40000);

应该是

if(taxableIncome > 20000 && taxableIncome <= 40000)

答案 1 :(得分:0)

更新了更新问题的答案

出于流量目的,您应首先在循环外查询,然后在循环结束时再次查询以准备下一次迭代。你的订单略有偏差,所以会发生奇怪的事情,但大部分代码都是正确的。

// Get the first Customer ID
System.out.println("Enter Customer ID: ");
customerID = input.nextInt();

while(customerID != -1)
{
    // Get income and withholding information
    System.out.print("Enter Income: ");
    income = input.nextDouble();

    System.out.print("Enter Federal Taxes Withheld: ");
    federalwh = input.nextDouble();

    System.out.print("Enter State Taxes Withheld: ");
    statewh = input.nextDouble();

    System.out.print("Enter Deductions: ");
    deduction = input.nextDouble();

    //!IMPORTANT SET all values for bracket to zero here!
    bracket10to20 = 0.0;
    //you can fill in all the rest

    //put all the calculations here from original answer

    //Get next customer id
    System.out.print("Enter Customer ID: ");
    customerID = input.nextInt();
    // if it's -1, we won't go through while again
}

原始问题的原始答案

问题在于:

if(taxableIncome > 20000 && taxableIncome <= 40000);

分号打破了它。删除它。但是,我建议你改变你对ifs的态度。你已经将很多if / elses嵌套在一起,当你可以像这样链接它们时:

    taxableIncome = income - deduction;

    if (taxableIncome <= 10000) {
        federalTax = 0.0;
    } else if (taxableIncome > 10000 && taxableIncome <= 20000) {
        bracket10to20 = (taxableIncome - 10000);
    } else if (taxableIncome > 20000 && taxableIncome <= 40000) {
        bracket20to40 = taxableIncome - 20000;
        bracket10to20 = 10000;
    } else if (taxableIncome > 40000) {
        bracket40plus = taxableIncome - 30000;
        bracket10to20 = 10000;
        bracket20to40 = 20000;
    }

    federalTax = (bracket10to20 * 0.15) + (bracket20to40 * 0.2)
            + (bracket40plus * 0.3);

这非常容易阅读,您无需跟踪所有嵌套。与往常一样,格式化可以减少代码中出错的可能性,并使其他人更容易提供帮助。