1

我是 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

4 回答 4

2

你的问题似乎在这里

numInput +=total; 

它应该是

total += numInput;
于 2013-04-19T19:48:04.963 回答
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;
}
于 2013-04-19T19:47:35.423 回答
0

你不应该切换total和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;                        
             }
于 2013-04-19T20:05:17.620 回答
0

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

你的问题在这里:

numInput += total;

应该

total += numInput;
于 2013-04-19T19:49:56.047 回答