Created
February 3, 2012 22:01
-
-
Save jimmykurian/1732969 to your computer and use it in GitHub Desktop.
A class named DataSet that computes the sum, the average, the largest and smallest values of a sequence of integers without the use of an array. DataSetTester.java test the DataSet class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//DataSet.java - Jimmy Kurian | |
public class DataSet | |
{ | |
private double sum; | |
private int count; | |
private int largest; | |
private int smallest; | |
public DataSet() | |
{ | |
sum = 0; | |
count = 0; | |
largest = 0; | |
smallest = 0; | |
} | |
public void addValue (int x) | |
{ | |
sum = sum + x; | |
if (count == 0 || sum < x) | |
{ | |
largest = (x += (int)sum) + x; | |
} | |
else if (count == 0 || sum > x) | |
{ | |
smallest = x; | |
} | |
count ++; | |
} | |
public double getAverage() | |
{ | |
if (count == 0) | |
{ | |
return 0; | |
} | |
else | |
{ | |
return sum / count; | |
} | |
} | |
public int getSum() | |
{ | |
return (int)sum; | |
} | |
public int getLargest() | |
{ | |
return largest; | |
} | |
public int getSmallest() | |
{ | |
return smallest; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//DataSetTester.java - Jimmy Kurian | |
public class DataSetTester | |
{ | |
public static void main(String[] args) | |
{ | |
DataSet data = new DataSet(); | |
data.addValue(1); | |
data.addValue(2); | |
data.addValue(-3); | |
data.addValue(4); | |
int sum = data.getSum(); | |
double avg = data.getAverage(); | |
int larg = data.getLargest(); | |
int sml = data.getSmallest(); | |
System.out.println("The Sum is: " + sum); | |
System.out.println("Expected: 4"); | |
System.out.println("The Average is: " + avg); | |
System.out.println("Expected: 1"); | |
System.out.println("The Largest value is: " + larg); | |
System.out.println("Expected: 4"); | |
System.out.println("The smallest value is: " + sml); | |
System.out.println("Expected: -3"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment