Write a Java class InputStatsArray to modify the InputStats class from Practice
ID: 3666373 • Letter: W
Question
Write a Java class InputStatsArray to modify the InputStats class from Practice Exercise 8 to:
1. Declare an int array numbers and a Scanner scanner;
2. In a loop,
a. Prompt users to input integers until they type “quit” when they’re finished;
b. Scan each integer as an int-valued numbers array element;
c. Compute the sums and squared sums of the elements in the numbers array;
3. Finally,
a. Compute the arithmetic mean (simple average) and standard deviation about the mean of the elements of the numbers array;
b. Print all the numbers on one line in format (for example):
Numbers: 1 4 33 2 5 14 22
c. Print the mean and standard deviation on the next line in the format:
Mean: 11.57142857; Std Deviation: 12.09486314
Explanation / Answer
/**The java program InputStatsArray that prompts user to
* enter numbers until user enters to quit the reading.
* Then calculates the mean and standard deviation and
* print to console*/
//InputStatsArray.java
import java.util.Scanner;
public class InputStatsArray
{
public static void main(String[] args)
{
//Create an instance of scanner class
Scanner scanner=new Scanner(System.in);
int total=0;
int count=0;
//create an array of type double
double[] arr=new double[100];
String value;
//read value from user
System.out.println("Enter a value or enter quit: ");
value=scanner.nextLine();
//Check if user does not enter quit
while(!value.equalsIgnoreCase("quit"))
{
//parse to integer
int num=Integer.parseInt(value);
//set to array
arr[count]=num;
//Add to total
total+=arr[count];
count++;
//read next vlaue
System.out.println("Enter a value or enter quit: ");
value=scanner.nextLine();
}
//calculate mean value
double mean=(double)total/count;
double standardDeviation=0;
total=0;
for (int index = 0; index < count; index++)
{
total+=Math.pow((arr[index]-mean),2.0);
}
//calculate standard devation
standardDeviation=Math.sqrt(total/(count-1));
for (int i = 0; i < count; i++)
{
System.out.println(arr[i]+" ");
}
//print mean and standard deviation
System.out.println("Mean : "+mean+";"
+"Std Deviation:"+standardDeviation);
}
}
-----------------------------------------------------------------------------------------------------------------------
Sample output:
Enter a value or enter quit:
1
Enter a value or enter quit:
4
Enter a value or enter quit:
33
Enter a value or enter quit:
2
Enter a value or enter quit:
5
Enter a value or enter quit:
14
Enter a value or enter quit:
22
Enter a value or enter quit:
quit
1.0
4.0
33.0
2.0
5.0
14.0
22.0
Mean : 11.571428571428571;Std Deviation:12.041594578792296
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.