SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:12 | ISBN:9780136091813 | Edition: 2

Question

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.