Write a method called printAverage that uses a sentinel loop to repeatedly prompt the user for numbers. Once the user types any number less than zero, the method should display the average of all nonnegative numbers typed.
Display the average as a double. Here is a sample dialogue with the user:
Type a number: 7
Type a number: 4
Type a number: 16
Type a number: –4
Average was 9.0
If the first number that the user types is negative, do not print an average:
Type a number: –2
package indefinite_loops;
import java.util.Scanner;
public class PrintAverage {
@SuppressWarnings("resource")
public void printAverage() {
Scanner input = new Scanner(System.in);
System.out.print("enter a number: ");
int num = input.nextInt();
if (num < 0)
return;
int sum = 0;
int count = 0;
// while loop continues counting the sum and number of values entered
while (num >= 0) {
sum += num;
count++;
System.out.print("enter a number: ");
num = input.nextInt();
}
// close the resources
input.close();
// average is toal sum divide by count
double average = sum/count;
System.out.println("The average is " + average);
}
public static void main(String[] args) {
PrintAverage print = new PrintAverage();
print.printAverage();
}
}
Output:
enter a number: 7
enter a number: 8
enter a number: 5
enter a number: 0
enter a number: -6
The average is 5.0