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.