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);
}
# 2 楼答案
您正在重新分配循环中的numChildren和grossIncome变量,而不是存储它们:
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());
}
# 1 楼答案
在
do-while
循环之前初始化children
和grossIncomes
数组将do while循环扩展到
JOptionPane.showMessageDialog(null,message);
不要使用
numTaxpayers
作为children
和grossIncomes
的索引。在循环开始之前,使用count
,并将count初始化为0# 2 楼答案
您正在重新分配循环中的
numChildren
和grossIncome
变量,而不是存储它们:应该是
因此,创建数组,然后为每个纳税人将其数组元素分配给查询结果
我进一步建议您将
TaxPayer
封装为一个对象,并将与之相关的方法保留在该对象中然后
稍微整洁一点,不是吗