我试图在一个数组中找到最大的三个元素。目前我已经想出了下面的代码,但它没有正确运行(输出是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);
}
}
我已经能够计算出最大的两个整数,但无法计算出最大的三个,如何只遍历一次数组并编写代码?
max2= max1
设置之前先设置max3= max2
。 - GriffeyDog