Respuesta :
Answer:
import java.util.Scanner;
public class SumOfPostiveNumbers {
public static void main(String[] args) {
//scanner object to read input from user
Scanner input = new Scanner(System.in);
boolean repeat = true;
String userChoice;
double average;
do
{
//get the average of the set of numbers using getPositiveNumber method
average = getPositiveNumber(input);
//display the output
System.out.printf("The average is: %.2f", average);
//prompt and read if user wishes to repeat the process
System.out.print("\n\nDo you want to compute another average (y/n)? ");
input.nextLine();
userChoice = input.nextLine();
//if user enters anything other than y, terminate the program
if(!(userChoice.equalsIgnoreCase("y")))
repeat = false;
System.out.println();
}while(repeat);
}
//method that read a stream of integers and returns the average
public static double getPositiveNumber(Scanner input)
{
// Variables for this method
double inputValue;
int numberofNumbers;
numberofNumbers= 1;
double average;
average=0;
double total;
total= 0;
//prompt the user to enter a set of numbers
System.out.printf("Enter a stream of non-negative numbers (negative when finished): ");
do
{
//read the number
inputValue = input.nextDouble();
//if the number is not negative
if (inputValue >= 0)
{
//add it to total
total = total + inputValue;
//compute the average
average = total / numberofNumbers;
//increment the count of numbers
numberofNumbers = numberofNumbers + 1;
}
} while (inputValue>= 0);
//return the calculates average
return average;
}
}
Explanation: