-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIncrementalStatistics.java
More file actions
46 lines (41 loc) · 1.41 KB
/
IncrementalStatistics.java
File metadata and controls
46 lines (41 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Scanner;
public class IncrementalStatistics {
public static void main(String[] args) {
double perviousAverage = 0;
double currentAverage = 0;
double perviousVariance = 0;
double currentVariance = 0;
int inputNumber = 0;
int amountOfNumbersEntered = 0;
boolean finished = false;
Scanner inputNum = new Scanner(System.in );
System.out.println("This program computes the average and variance of all numbers entered.");
while (!finished)
{
System.out.print("Enter another number (or type 'exit'): ") ;
if(inputNum.hasNextInt() )
{
inputNumber = inputNum.nextInt();
amountOfNumbersEntered++;
perviousAverage = currentAverage;
perviousVariance = currentVariance;
currentAverage = (perviousAverage + (inputNumber - perviousAverage)/ amountOfNumbersEntered);
currentVariance = ((( perviousVariance * (amountOfNumbersEntered -1 ))
+ (inputNumber - perviousAverage) * (inputNumber - currentAverage)) /amountOfNumbersEntered);
System.out.println("So far the average is " + currentAverage
+ " and variance is " +currentVariance );
}
else if ((inputNum.hasNext("exit")) || (inputNum.hasNext("quit")))
{
finished = true;
}
else if(inputNum.hasNext())
{
System.out.println("Sorry this input is invalid.") ;
inputNum = new Scanner(System.in );
}
}
System.out.print("Goodbye.") ;
inputNum.close();
}
}