import java.util.Arrays; public class Work1 { public static void main(String[] args) { //1、实现方法:随机生成10个整数,存入数组 //2、实现方法:求出数组中所有数的和 //3、实现方法:求数组中的最大值,第二大值 //4、实现方法:从大到小 int[] s = new int[]{8, 8, 4, 4, 1, 5}; int[] s1 = sele(s); for (int i = 0; i < s.length; i++) { for (int j = i+1; j < s.length; j++) { if (s[i] < s[j]) { int tem = s[j]; s[j] = s[i]; s[i] = tem; } } //System.out.println(s[i]); } //通过Arrays类的toShing方法输出数组 //System.out.println(Arrays.toString(s)); System.out.println(Arrays.toString(s1)); } public static int[] sele(int[] s){ int max = 0; //第二大数 int second = 0; int x = 0; //-------第一种方法: if (s[0] > s[1]){ max = s[0]; second = s[1]; }else { max = s[1]; second = s[0]; } for (int i = 2; i < s.length; i++) { if (s[i] > max){//第一种比现在max大 second = max; max = s[i]; }else if(s[i] < max && s[i] > second || max == second){ //第二种比现在max小,此处当前两个数相同时之间将后一项值赋给second second = s[i]; } //第三种比现在second大 } /*--------第二种方法: for (int i = 1; i < s.length; i++) {//此处是得到最开始两个不等值 if (s[0] > s[i]){ max = s[0]; second = s[i]; x = i; break; }else if (s[0] == s[i]){ continue; } else{ max = s[i]; second = s[0]; x = i; break; } } System.out.println(x); for (int i = 2; i < s.length; i++) { if (s[i] > max){//第一种比现在max大 second = max; max = s[i]; }else if(s[i] < max && s[i] > second){ //第二种比现在max小 second = s[i]; } //第三种比现在second大 } */ //System.out.println(second); int[] s1 = new int[]{max,second}; return s1; } }
两种方法实现求数组第一大和第二大值
最新推荐文章于 2023-11-30 15:08:46 发布