简体   繁体   中英

Sum function not working in Java.

I'm new to Java programming. I have a project that is supposed to sum a series of inputs and also calculate the average of those numbers. Right now the Total is coming up as zero no matter what I put in for values. I'm stuck. Please help. Thank you.

   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();
          }

}

It should be total += numInput instead of 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;
}

Your problem appears to be here

numInput +=total; 

It should be

total += numInput;

The += operator works the other way around.

Your issue is here:

numInput += total;

Should be

total += numInput;

Aren't you supposed to switch total and 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;                        
             }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM