Write a Java program. Program your code to accept a series of numbers from the k
ID: 2247052 • Letter: W
Question
Write a Java program. Program your code to accept a series of numbers from the keyboard. The numbers represent quantities such as heights of humans. The length of the series is unknown but an input of a negative number signals the end of the series. In other words, the series is terminated by a negative number (which is excluded from the calculation).
Do NOT save the numbers into an array as the length of the series is unknown and an array has a fixed size. To calculate the average, you need to know the sum and the length of the series. As you read each number, update the sum and the length along the way.
To calculate the standard deviation, you can do it the same way. There are two ways to calculate standard deviation. Use the formula that does not require the known average ahead of time. Check the topic on Wikipedia for the required formula to calculate the standard deviation without known average ahead of time.
Sample output (input in bold):
Please input the set of heights (terminated by a number < 0): 5.9 6.1 5.7 5.0 -1
The average height is XX.
The standard deviation is YY.
Explanation / Answer
MeanStddev.java
import java.util.Scanner;
public class MeanStddev {
public static void main(String[] args) {
// Declaring variables
int i = 0;
double tot = 0.0, sumOfSquares = 0.0, num = 0.0;
double stdDev = .0, avg = 0.0;
// Scanner object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
// Getting the inputs entered by the user
System.out
.println("Please input the set of heights (terminated by a number < 0):");
num = sc.nextDouble();
while (!(num < 0)) {
// Calculating the total
tot += num;
// Calculating the sum of squares
sumOfSquares += num * num;
i++;
// Calculating average
avg = tot / i;
// Calculating standard deviation
stdDev = Math.sqrt((sumOfSquares - (tot * tot) / i) / i);
num = sc.nextDouble();
}
//Displaying the outputs
System.out.println("The average height is " + avg);
System.out.printf("The standard deviation is %.2f ", stdDev);
}
}
___________________
Output:
Please input the set of heights (terminated by a number < 0):
5.9 6.1 5.7 5.0 -1
The average height is 5.675
The standard deviation is 0.41
_______________could rate me well plz..Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.