user1696162
user1696162

Reputation: 105

Math.max and Math.min outputting highest and lowest values allowed

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.

Upvotes: 3

Views: 23141

Answers (2)

Reimeus
Reimeus

Reputation: 159844

Reverse your largest & smallest initial values and Math.max & Math.min will select the correct value accordingly:

largest = Integer.MIN_VALUE;
smallest = Integer.MAX_VALUE;

As Integer.MIN_VALUE is the smallest possible value for an integer, the statement:

largest = Math.max(x, largest);

will yield the value x the first time it is called.

Upvotes: 7

Guido Simone
Guido Simone

Reputation: 7952

In think you meant in your initialization:

largest = Integer.MIN_VALUE;
smallest = Integer.MAX_VALUE;

Upvotes: 2

Related Questions