Question

Write a program that calculates the average of a stream of non-negative numbers. The user can...

Write a program that calculates the average of a stream of non-negative numbers. The user can enter as many non-negative numbers as they want, and they will indicate that they are finished by entering a negative number. For this program, zero counts as a number that goes into the average. Of course, the negative number should not be part of the average (and, for this program, the average of 0 numbers is 0).

You must use a method to read in the numbers, keep track of the running sum and count, compute the average, and return the average to the main() method. Note that you must use a loop to do this, as you don't know how many numbers the user will enter ahead of time.

The main() method must print the average (which was returned from your method) using two decimal places, and then ask the user if they want to repeat the entire process. The user should be allowed to repeat the process as many times as they wish. This means you will have a loop in your main() method that instructs the user what to do, calls your average method, reports the result, and finally asks the user if they want to calculate another average for a different set of numbers. Importantly, your program will not function correctly if is more than one Scanner object looking to the keyboard. Thus, since both main() and your averaging method need to get input from the keyboard, you will have to declare and initialize a Scanner variable in main(), then pass it as an argument to the averaging method. Furthermore, note that your method that reads in the numbers and computes the average must have no System.out.println() statements -all output must happen in main(). Be sure you take the time to think through the pieces and, more importantly, implement in small steps. I suggest you proceed like so:

1. Get the structure of defining and calling your method down first, with no loops involved.

2. Fill in the method with a loop that runs while the user enters non-negative numbers.

3. Modify the loop to keep track of the sum and count, then print the average in the function.

4. Modify the method to actually return the average.

5. Modify main() to use another loop to ask the user if they want to repeat the entire calculations

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java Program:

/* Java Program that reads in non negative integers from user and prints their sum and average */

import java.util.Scanner;

//Class definition
class IntegerAverage
{
   //Method that returns the average of values entered by user
   public static double getAverage(Scanner ip)
   {
       int temp, sum = 0, cnt = 0;
      
       double avg;
      
       //Reading a number
       System.out.print("\n Enter a Non-Negative Number: ");
       temp = ip.nextInt();
      
       //Loop till user enters a negative number
       while(temp >= 0)
       {
           //Calculating sum
           sum += temp;
          
           //Updating number of elements
           cnt++;
          
           //Reading a number
           System.out.print("\n Enter a Non-Negative Number: ");
           temp = ip.nextInt();
       }
      
       //Calculating average
       avg = sum / (double) cnt;
      
       //Return average
       return avg;
   }
  
   //Main method
   public static void main(String args[])
   {
       String userChoice;
      
       //Scanner object
       Scanner sc = new Scanner(System.in);
      
       //Loop till user want to stop
       do
       {
           //Calling method and printing average
           System.out.println("\n Average: " + getAverage(sc));
          
           sc.nextLine();
          
           //Reading user choice
           System.out.print("\n Do you want to continue? (Press Y/y): ");
           userChoice = sc.nextLine();
          
       //While condition check  
       }while(userChoice.charAt(0) == 'Y' || userChoice.charAt(0) == 'y');
   }
}

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

Sample Output:

C:Windowslsystem32\cmd.exe Dav>javac IntegerAverage. java D:Java> java IntegerAverage Enter a Non-Negative Number: 10 Enter a

Add a comment
Know the answer?
Add Answer to:
Write a program that calculates the average of a stream of non-negative numbers. The user can...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 1- Write a program to read 10 numbers and find the average of these numbers. Use...

    1- Write a program to read 10 numbers and find the average of these numbers. Use a while loop to read these numbers and keep track of input numbers read. Terminate the while loop with a sentinel value. 2- Now modify the program to find the maximum of these numbers as well. The program should print the number of elements read as input and run until -1 is entered. (-1 is the sentinel that terminates the loop and the program)...

  • Write a program and flowchart. The program should ask the user how many customers they want to track. Then, it asks for customer numbers, and sales by customer. At the end, it prints out the customer...

    Write a program and flowchart. The program should ask the user how many customers they want to track. Then, it asks for customer numbers, and sales by customer. At the end, it prints out the customer number, the customer sales, and then the total sales and average sales. You must use two different arrays, one for customer number, and one for sales. These are, in effect, parallel arrays.   You must use a "while" loop to gather customer number and sales....

  • Write a program and flowchart. The program should ask the user how many customers they want...

    Write a program and flowchart. The program should ask the user how many customers they want to track. Then, it asks for customer numbers, and sales by customer. At the end, it prints out the customer number, the customer sales, and then the total sales and average sales. You must use two different arrays, one for customer number, and one for sales. These are, in effect, parallel arrays.   You must use a "while" loop to gather customer number and sales....

  • write a program code that asks the user how many numbers they wish to find the...

    write a program code that asks the user how many numbers they wish to find the statistics of and then asks the user to enter those numbers. The program must then calculate and display the average variance and standard deviation of the numbers entered by the user. the program code must -ask three user how many numbers they wish to find the statistics of -ask the user to enter those numbers and store them in an array - use a...

  • (Count positive and negative numbers and compute the average of numbers) Write a program that reads...

    (Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number. If you entire input is 0, display 'No numbers are entered except 0.' *So I think my code is looping because the...

  • Suppose you are writing a program that asks the user to enter a non-negative score. You...

    Suppose you are writing a program that asks the user to enter a non-negative score. You want to keep correcting them and re-asking them to enter it as long as they do it wrong. Which is the better type of loop to use? A. for loop B. do-while loop

  • Change your C++ average temperatures program to: In a non range-based loop Prompt the user for...

    Change your C++ average temperatures program to: In a non range-based loop Prompt the user for 5 temperatures. Store them in an array called temperatures. Use a Range-Based loop to find the average. Print the average to the console using two decimals of precision. Do not use any magic numbers. #include<iostream> using namespace std; void averageTemperature() // function definition starts here {    float avg; // variable declaration    int num,sum=0,count=0; /* 'count' is the int accumulator for number of...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Write a program that will do the following. The main function should ask the user how...

    Write a program that will do the following. The main function should ask the user how many numbers it will read in. It will then create an array of that size. Next, it will call a function that will read in the numbers and fill the array (fillArray). Pass the array that was made in themain function as a parameter to this function. Use a loop that will read numbers from the keyboard and store them in the array. This...

  • In this exercise, write a complete Java program that reads integer numbers from the user until...

    In this exercise, write a complete Java program that reads integer numbers from the user until a negative value is entered. It should then output the average of the numbers, not including the negative number. If no non-negative values are entered, the program should issue an error message. You are required to use a do-while loop to solve this problem. Solutions that do not use a do-while loop will be given a zero. Make sure to add appropriate comments to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT