如何使用数组存储信息?

时间:2013-10-24 17:52:15

标签: java

如何使用数组存储纳税人信息?说我想输入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 个答案:

答案 0 :(得分:2)

您可能希望定义具有这些字段的Taxpayer类,然后创建它们的数组,也就是说Taxpayer[]。虽然你可能会更好地使用List<Taxpayer>或类似的东西;它会给你更大的灵活性。

答案 1 :(得分:1)

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

答案 2 :(得分: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);

答案 3 :(得分: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;