简体   繁体   中英

Java Max/Min Program Keeps Returning incorrect Min Value

I'm supposed to get the smallest and largest number out of a sequence of numbers that the user inputs. The largest is being printed correctly, but I can't figure out why the smallest keeps being printed as 0? any help?

在此处输入图像描述

在此处输入图像描述

This is because smallest is initialized with value 0 in the constructor of NumberList class. Now, if you input a number greater than 0 , the Math.min(smallest, number) would always be 0 .

Also the largest will give the incorrect result if all the input values are negative.

So, you'd have to initialize the smallest with largest possible value and largest with smallest possible value in the constructor:

public NumberList() {
    ...    
    smallest = Integer.MAX_VALUE;
    largest = Integer.MIN_VALUE;
}

or in the initialization block of the class:

class NumberList {
    ...
    private int smallest = Integer.MAX_VALUE;
    private int largest = Integer.MIN_VALUE;
    ...
}

Edit: Also, it'd be best to initialize smallest and largest in one place, otherwise makes the code hard to debug.

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