Sum函数在Java中不起作用。

时间:2013-04-19 19:45:14

标签: java

我是Java编程的新手。我有一个项目,应该总结一系列输入,并计算这些数字的平均值。现在无论我投入什么价值,总计都会变为零。我被卡住了。请帮忙。谢谢。

   private class InputButtonListener implements ActionListener
   {
          public void actionPerformed(ActionEvent e)
          {  
                 for(int i=0; i<7; i++)
                 {
                       numInput = 0.0;
                       strInput = JOptionPane.showInputDialog(null, "How many hours did you sleep on day " + (i+1));
                       numInput = Double.parseDouble(strInput);
                       numInput +=total;                        
                 }
          }
   }
   private class CalcButtonListener implements ActionListener
   {
          public void actionPerformed(ActionEvent e)
          {
                 JOptionPane.showMessageDialog(null,"The total amount of sleep for the week is " + total + " hours");

                 JOptionPane.showMessageDialog(null,"The average amount of sleep for 7 days is " + avg + " hours");
          }
   }
   public static void main(String[] args)
          {
                 HoursSlept HS = new HoursSlept();
          }

}

4 个答案:

答案 0 :(得分:1)

应该是total += numInput而不是numInput += total

for(int i=0; i<7; i++)
{
    strInput = JOptionPane.showInputDialog(null, "How many hours did you sleep on day " + (i+1));
    numInput = Double.parseDouble(strInput);
    total += numInput;
}

答案 1 :(得分:1)

您的问题似乎在这里

numInput +=total; 

应该是

total += numInput;

答案 2 :(得分:0)

+ =运算符以相反的方式工作。

您的问题在这里:

numInput += total;

应该是

total += numInput;

答案 3 :(得分:0)

你不应该切换总数和numInput吗?

for(int i=0; i<7; i++)
             {
                   numInput = 0.0;
                   strInput = JOptionPane.showInputDialog(null, "How many hours did you sleep on day " + (i+1));
                   numInput = Double.parseDouble(strInput);
                   total +=numInput;                        
             }