简体   繁体   中英

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.

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.

In think you meant in your initialization:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM