有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    do-while循环之前初始化childrengrossIncomes数组

    将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);
                 }
    
  2. # 2 楼答案

    您正在重新分配循环中的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());
    }
    

    稍微整洁一点,不是吗