在 Java 中找到第二个最大整数的程序(添加一个选项)

Program that is find the second max integer in Java (adding an option)

我有下面显示的代码,它从命令行找到第二大数字。 例如:

java FindSecondMax 3 4 5 6

输出将是第二大的,即 5。

我想在用户输入相同数字时显示 There is no second largest number。例如 4 4 4 4

我该怎么做?

public class FindSecondMax {
    public static void main(String args[]) {
    int max = Integer.parseInt(args[0]);
    int i = 1;
    while (i < args.length) {
        int nums =Integer.parseInt(args[i]);
        if (nums > max)
        max = nums;
        i++;
    }
    int max1 = max;
    max = Integer.parseInt(args[0]);
    int j = 1;
    while (j < args.length ) {
        int nums = Integer.parseInt(args[j]);
        if (nums > max && nums < max1)
        max =nums;
        j++;
    }
    int max2 = max;
    System.out.println(max2);
    }
}

只需检查所有数字是否相等

 if(isAllEqual(args)) {
      System.out.print("no second number");
    } else {
      System.out.print(max2);
    }
}//end of main
public static boolean isAllEqual(String[] cheese) {
   //figure out if each element in the array is equal
   boolean anw = true;
   for(int i = 1; i < cheese.length;i++) {
   //put some code here
   //if you find out there not equl
   //anw = false;
   //break;
   }
   return anw;
}

您的代码唯一的变化是:

  1. 在计算最大值的第一个循环中捕获最小值
  2. 告诉用户没有第二个最大值 if (min==max) else ... 执行您之前的逻辑

    public class FindSecondMax {
    
    public static void main(String args[]) {
    
    int max = Integer.parseInt(args[0]);
    int min = Integer.MAX_VALUE;
    int i = 1;
    while (i < args.length) {
    
        int nums = Integer.parseInt(args[i]);
    
        if (nums > max)
            max = nums;
        if (nums < min)
            min = nums;
        i++;
    }
    
    if (min == max) {
        System.out.println("There is no secondmax");
    } else {
        int max1 = max;
        max = Integer.parseInt(args[0]);
        int j = 1;
        while (j < args.length) {
            int nums = Integer.parseInt(args[j]);
    
            if (nums > max && nums < max1)
                max = nums;
            j++;
        }
        int max2 = max;
        System.out.println(max2);
    }
    }
    }
    

注意:排序将有助于您的方法。 min/max 是微不足道的,第二大是从最大向下的简单迭代,直到得到不同的数字。