Math.max and Math.min outputting highest and lowest values allowed
Posted
by
user1696162
on Stack Overflow
See other posts from Stack Overflow
or by user1696162
Published on 2012-10-07T21:24:05Z
Indexed on
2012/10/07
21:37 UTC
Read the original article
Hit count: 568
java
so I'm trying to make a program that will output the sum, average, and smallest and largest values. I have everything basically figured out except the smallest and largest values are outputting 2147483647 and -2147483647, which I believe are the absolute smallest and largest values that Java will compute. Anyway, I want to compute the numbers that a user enters, so this obviously isn't correct.
Here is my class. I assume something is going wrong in the addValue method.
public class DataSet
{
private int sum;
private int count;
private int largest;
private int smallest;
private double average;
public DataSet()
{
sum = 0;
count = 0;
largest = Integer.MAX_VALUE;
smallest = Integer.MIN_VALUE;
average = 0;
}
public void addValue(int x)
{
count++;
sum = sum + x;
largest = Math.max(x, largest);
smallest = Math.min(x, smallest);
}
public int getSum()
{
return sum;
}
public double getAverage()
{
average = sum / count;
return average;
}
public int getCount()
{
return count;
}
public int getLargest()
{
return largest;
}
public int getSmallest()
{
return smallest;
}
}
And here is my tester class for this project:
public class DataSetTester {
public static void main(String[] arg) {
DataSet ds = new DataSet();
ds.addValue(13);
ds.addValue(-2);
ds.addValue(3);
ds.addValue(0);
System.out.println("Count: " + ds.getCount());
System.out.println("Sum: " + ds.getSum());
System.out.println("Average: " + ds.getAverage());
System.out.println("Smallest: " + ds.getSmallest());
System.out.println("Largest: " + ds.getLargest());
}
}
Everything outputs correctly (count, sum, average) except the smallest and largest numbers. If anyone could point me in the right direction of what I'm doing wrong, that would be great. Thanks.
© Stack Overflow or respective owner