viewing paste CountNumbers | Java

Posted on the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
//Import JOptionPane to get the dialog box to work
import javax.swing.JOptionPane;
 
public   class CountNumbers{
   
   public   static   void  main(String[] args){
      
        String input = JOptionPane.showInputDialog(null, "Please Enter a number, enter 0 to stop", "CPSC Lab 4", JOptionPane.QUESTION_MESSAGE);
 
        //Initialize all variable & turning the string input into an integer
        int data = Integer.parseInt(input);
        int count = 0;
        double calc = data;
        double average = 0;
        
        //First check to prevent the program from continuing and increasing the variable used later for the average
        if(data != 0)
            count++;
 
        while(data != 0){
 
            String inputInt = JOptionPane.showInputDialog(null, "Please Enter a number, enter 0 to stop", "CPSC Lab 4", JOptionPane.QUESTION_MESSAGE);
            
            //Turn the string inputInt into an integer
            data = Integer.parseInt(inputInt);
 
            //Add numbers to the variable calc, which will help give a final total/result and compute the average
            calc += data;
            
            //Second check to prevent the program from continuing even if user has already entered a 0, resulting in 1 too much
            //Problem could also be resolved by editing the count variable in the average calculation e.g. average = calc/(count-1);
            //That would however be unprofessional
            if(data != 0)
                count++;
            else
                average = calc/count;
 
        }
        
            JOptionPane.showMessageDialog(null, "Your total is: "+calc+". # of items: "+count+". Average is: "+average+".");
 
      }
      
   }
Viewed 1089 times, submitted by Streusel.