5-9 Average_Positive
Post date: Apr 7, 2014 11:06:51 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)