从输入的 BufferedReader 中查找 arrayList 中最大和最小的元素

Find the largest and smallest element in arrayList from a typed in BufferedReader

我不知道为什么我没有得到最小的数字。如果 eg.try: 129, 2, 3.

,则较大的数字是正确的
public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    int list[] = new int[3];
    int min = list[0];
    int max = list[0];
    int input;

    for (input = 0; input < list.length; input++) {
        String s = reader.readLine();
        list[input] = Integer.parseInt(s);

        if (list[input] < min) {
            min = list[input];
        } else if (list[input] > max) {
            max = list[input];
        }
    }

    System.out.println("Smallet nummber: " + min);
    System.out.println("Biggest nummber: " + max);
}

只需像这样初始化您的最小值和最大值:

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

把条件部分也改成这样:

if (list[input] < min) {
    min = list[input];
}
if (list[input] > max) {
    max = list[input];
}

当你用list[0]初始化时,min和max都会被初始化为0。现在如果你给的输入值小于0,那么只有min 值将被更新。否则,最小值永远不会更新。

min 为 0 且始终小于 list[input]。案例:

if (list[input] < min) {

永远不会发生。 在 arrayList 中使用负数 ;)

当你像这样初始化数组时:

int[] list = new int[3];

它的所有项目都是 0
所以当你初始化最小值和最大值时:

int min = list[0];
int max = list[0];

你分配给两个 0
如果您只想保留 1 个循环来获取输入并获取 minmax,您可以这样做:

if (input == 0) {
    min = list[input];          
    max = list[input];
} else if (list[input] < min) {
    min = list[input];
} else if (list[input] > max) {
    max = list[input];
}