-2

如何使用数组存储纳税人信息?假设我想输入 3 个纳税人的信息。如何使用数组将名字、姓氏、总收入等存储三遍?

numTaxpayers = Integer.parseInt(JOptionPane.showInputDialog("How many taxpayers would you like to calculate taxes for?"));
do
{
    firstName = JOptionPane.showInputDialog("What is your first name?");
    lastName = JOptionPane.showInputDialog("What is your last name?");
    grossIncome = Double.parseDouble(JOptionPane.showInputDialog("What is your gross income?"));
    numChildren = Integer.parseInt(JOptionPane.showInputDialog("How many children do you have?"));
    taxDependency = numChildren * 3000;
    taxableIncome = grossIncome - taxDependency;
    name = firstName + " " + lastName;
    tax = calculateTax(taxableIncome);
    message += "First Name: " + firstName + "\nLast Name: " + lastName + "\nGross Income: $" + String.format("%.2f",grossIncome) + "\nNumber of Children: " + numChildren + "\nTax Due: $" + String.format("%.2f",tax) + "\n\n";
    count ++;
} while (count <= numTaxpayers);
JOptionPane.showMessageDialog(null,message);
4

4 回答 4

2

您可能想要定义一个Taxpayer具有这些字段的类,然后将它们组成一个数组,也就是说,a Taxpayer[]. List<Taxpayer>尽管使用 a或类似的东西可能会更好;它会给你更大的灵活性。

于 2013-10-24T17:55:28.160 回答
1

您可以使用多维对象数组或长度为 3 * 纳税人数量的数组。但更好的选择是创建一个 TaxPayer 类并将其存储到数组(Taxpayer[])或集合(Collection)中。

于 2013-10-24T17:56:13.990 回答
0

您有这样的课程:

Class TaxPayer{
 String fName;
 String lName;
 int gross;

 public TaxPayer(String fName,String lName, int gross){
  this.fName=fName;
  this.lName=lName;
  this.gross=gross;
 }

}

现在,我可以将它用作,

List<TaxPayer> arr=new List<TaxPayer>();

TaxPayer payer1=new TaxPayer("Nicol","Mick",5000);
arr.add(payer1);

TaxPayer payer2=new TaxPayer("Mark","Tylor",5000);
arr.add(payer2);

// for retrieving values, use like
String payer1name= arr.get(0).fName;
于 2013-10-24T18:10:55.847 回答
0

创建一个名为 TaxPayer 的类,如下所示:

class TaxPayer{
    private String firstName;
    private String lastName;
    ...
}
...
do
{
    firstName = JOptionPane.showInputDialog("What is your first name?");
    lastName = JOptionPane.showInputDialog("What is your last name?");
    grossIncome = Double.parseDouble(JOptionPane.showInputDialog("What is your gross     income?"));
    numChildren = Integer.parseInt(JOptionPane.showInputDialog("How many children do you have?"));
    taxDependency = numChildren * 3000;
    taxableIncome = grossIncome - taxDependency;
    name = firstName + " " + lastName;
    tax = calculateTax(taxableIncome);
    message += "First Name: " + firstName + "\nLast Name: " + lastName + "\nGross Income: $" + String.format("%.2f",grossIncome) + "\nNumber of Children: " + numChildren + "\nTax Due: $" + String.format("%.2f",tax) + "\n\n";
    arr[count] = new TaxPayer(firstName, lastName, ...);
    count ++;
} while (count <= numTaxpayers);
于 2013-10-24T18:00:14.393 回答