gpt4 book ai didi

java - 在数组中查找 3 个最大整数

转载 作者:行者123 更新时间:2023-12-01 12:55:23 25 4
gpt4 key购买 nike

我试图在数组中找到最大的三个元素。到目前为止,我已经想出了这个,但它不能正常工作(输出为 9 8 3):

public class Test {

public static void main(String[] args) {
int max1, max2, max3;
int[] test= {2,4,8,3,9,1};

max1= test[0];
max2= test[0];
max3= test[0];
for(int i = 1; i < test.length; i++) {
if(max1 < test[i]) {
max2= max1;
max1= test[i];
}
else if (max2 < test[i]) {
max3= max2;
max2= test[i];
}
else if (max3 < test[i]) {
max3= test[i];
}

}
System.out.println(max1 + " " + max2 + " " + max3);

}

}
我已经设法做最大的 2 个整数,但我不能做 3 个。如何只使用 1 次遍历数组来编写代码?

最佳答案

在第一个“if”语句中,您不包括:

max3 = max2

关于java - 在数组中查找 3 个最大整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63002487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com