第一种方法: 直接排序再取值
public class Test3 {
public static void main(String[] args) {
int[] a = { 5, 4, 9, 8, 10,12,2,24,35,42,4,3,5 };
int max, temp;
max = temp = a[0];
int n,i;
for (n = 0; n < a.length; n++) {
for(i=0;i<a.length-1;i++){
if(a[i]>a[i+1]){
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
System.out.println(a[a.length-2]);
}
}
第二种方法:
public class Test {
public static void main(String[] args) {
int[] a = { 5, 4, 9, 8, 10,12,2,24,35,42,4,3,5 };
int max, max2;
max = max2 = a[0];
int n;
for (n = 1; n < a.length; n++) {
if (a[n] > max2) {
if (a[n] > max) {
max2 = max;
max = a[n];
} else {
max2 = a[n];
}
}
}
System.out.println(max2);
}
}
第三种方法: 简单方法:
public class Test2 {
public static void main(String[] args) {
int [] a={2,4,56,7,45,6,76};
int max=0,max2=0;
int i;
for(i=0;i<a.length;i++){
if(max<a[i]){
max2=max;
max=a[i];
}
}
System.out.println(max2);
}
} |
|