5-9 Average_Positive

posted Apr 7, 2014, 4:06 AM by dldar masud   [ updated Apr 7, 2014, 4:13 AM ]
/*
 Write a function called average that reads positive integers 
 from the user, stopping when the user enters a 0 or negative integer 
 and return the average of the positive integers then print it in main function.
*/

package average_positive;
import java.util.Scanner;

public class Average_Positive 
{

        public static void main(String[] args) 
        {
           double index=average();

            if(index!=-1)
                System.out.println("Average="+index);
            else
              System.out.println("No average"); 
        }

        public static double average()
        {
           Scanner input=new Scanner(System.in);

           System.out.println("Enter the numbers :");
           double sum=0,count=0,number;

           while((number=input.nextDouble())>0)
           {
               sum+=number;
               count++;
           }

           return(count!=0)?sum/count:-1;

        }
}

..........................................................................................
run:
Enter the numbers :
44
66
75
43
0
Average=57.0
BUILD SUCCESSFUL (total time: 18 seconds)

ċ
Average_Positive.java
(1k)
dldar masud,
Apr 7, 2014, 4:06 AM
Comments