【问题标题】:Program that is find the second max integer in Java (adding an option) [duplicate]在Java中找到第二个最大整数的程序(添加一个选项)[重复]
【发布时间】:2018-02-10 09:46:46
【问题描述】:

我有一个如下所示的代码,它可以从命令行中找到第二大数字。 例如:

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);
    }
}

【问题讨论】:

  • 将其放入代码中的一种相当简单的方法是在第一个循环中计算最小值。那么如果 min == max 你就没有第二个了。

标签: java command-line-arguments


【解决方案1】:

对代码的唯一更改是:

  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);
    }
    }
    }
    

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

【讨论】:

  • 好了,全班都到齐了
  • 感谢这个工作。
  • 如果您标记为已接受,如果此代码满足您的需要,我将不胜感激。干杯
【解决方案2】:

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

 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;
}

【讨论】:

  • 这不是“我的家庭作业网站”,但我会尝试用上面的答案为您指明方向
猜你喜欢
  • 2021-06-01
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 2019-12-18
  • 2013-05-24
  • 2015-11-26
  • 2023-03-22
  • 2020-08-17
相关资源
最近更新 更多