2013-10-24 21 views

回答

2

初始化do-while循环之前的childrengrossIncomes阵列。

延长do-while循环,直到JOptionPane.showMessageDialog(null,message);

不要使用numTaxpayerschildrengrossIncomes指数。在循环开始之前,使用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

这是正确的,但是一旦你扩展了循环,你应该在while循环之前初始化数组(double [] grossIncomes'和int [] children')。然后是while循环,并使用'count'而不是'numTaxpayers'。 –

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()); 
} 

有点整洁,不是吗?

+0

那么不要使用do-while循环? – Dan

+0

你使用什么并不重要。你需要保持你阅读的价值。您正在重新分配每个迭代的值。无论如何,'for'循环要简单得多。 –