纳税人信息存储与数组

时间:2013-10-24 19:37:00

标签: java

那么,如果我要问“x”税额

,该怎么办?

2 个答案:

答案 0 :(得分:2)

children循环之前初始化grossIncomesdo-while数组。

将do-while循环扩展到JOptionPane.showMessageDialog(null,message);

请勿使用numTaxpayers作为childrengrossIncomes的索引。在循环开始之前使用count并将count初始化为0。

            int[] children = new int[numTaxpayers];
            double[] grossIncomes = new double[numTaxpayers];
            int count = 0;
            while (count < numTaxpayers)
            {
                int numChildren = Integer.parseInt(JOptionPane.showInputDialog("How many children do you have?"));
                double grossIncome = Double.parseDouble(JOptionPane.showInputDialog("What is your gross income?"));

                children[count] = numChildren;
                grossIncomes[count] = grossIncome;

                count ++;
                // Calculations goes here
                //....
                //...
                JOptionPane.showMessageDialog(null,message);
             }

答案 1 :(得分:0)

您正在重新分配循环中的numChildrengrossIncome变量,而不是存储它们:

    do
    {
        numChildren = Integer.parseInt(JOptionPane.showInputDialog("How many children do you have?"));
        grossIncome = Double.parseDouble(JOptionPane.showInputDialog("What is your gross income?"));
        count ++;
    } while (count <= numTaxpayers);

应该是

final int[] children = new int[numTaxpayers];
final double[] grossIncomes = new double[numTaxpayers];
for(int i = 0; i < numTaxpayers; ++i) {
    children[i] = Integer.parseInt(JOptionPane.showInputDialog("How many children do you have?"));
    grossIncomes[i] = Double.parseDouble(JOptionPane.showInputDialog("What is your gross income?"));
}

因此,您创建数组,然后为每个纳税人将您的数组元素分配给查询结果。

我还建议你将TaxPayer封装为一个对象,并将与它们相关的方法保存在该对象中。

public class TaxPayer {

   private final int numChildren;
   private final int grossIncome;

   private TaxPayer(final int numChildren, final int grossIncome) {
       this.numChildren = numChildren;
       this.grossIncome = grossIncome;
   }

   public static TaxPayer requestTaxPayerDetails() {
       final int numChildren = Integer.parseInt(JOptionPane.showInputDialog("How many children do you have?"));
       final int grossIncome = Double.parseDouble(JOptionPane.showInputDialog("What is your gross income?"));
       return new TaxPayer(numChildren, grossIncome);
   }

   public int findTaxDependency() {
       // do stuff
   }

   public double calculateTax() {
      // do stuff
   }
}

然后

final List<TaxPayer> taxpayers = new LinkedList<TaxPayer>();
for(int i = 0; i < numTaxpayers; ++i) {
    taxpayers.add(TaxPayer.requestTaxPayerDetails());
}

有点整洁,没有?

相关问题