【问题标题】:How to find second highest number in array in java [duplicate]如何在java中找到数组中的第二大数字[重复]
【发布时间】:2020-05-27 15:00:49
【问题描述】:

我想在 java 的数组中找到第二大的数字。 我绑从这段代码解决问题。

class Example{
    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        //Random r=new Random();
        int max=0;
        int secondMax = 0;
        for(int i=0; i<10; i++){
            System.out.print("Input an integer : ");
            int num = input.nextInt();

            if (num>max)
            {   
                secondMax=max;
                max=num;
            }       

        }

        System.out.println("Max number is : "+max);
        System.out.println("Second Max number is : "+secondMax);

    }
}

【问题讨论】:

标签: java


【解决方案1】:

您试图在填充数组时找到最大值和第二个值。尝试删除

        if (num>max)
        {   
            secondMax=max;
            max=num;
        }

来自 for 循环。然后添加一个单独的(不是嵌套的)for循环来搜索数组:

   for (int i = 0; i < 10; i++){
      if (input[i] > max){
        secondMax = max;
        max = input[i];
      }

      if ((input[i] < max) && (input[i] > secondMax))
        secondMax = input[i];
    }

【讨论】:

  • 实际上这仅适用于正数。不适用于负数...
【解决方案2】:
import java.util.*;
class Example{
    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        int []numbers=new int[10];
        for (int i = 0; i <10 ; i++)
        {
            System.out.print("Input an integer: ");
             numbers[i]=input.nextInt();
        }
        int max=0;
        int secondHighest=0;
        for (int i = 0; i < numbers.length; i++)
        {       
            if (numbers[i]>max)
            {
                secondHighest=max;
                max=numbers[i];
            }
            if (numbers[i]<max && numbers[i]>=secondHighest )
            {
                secondHighest=numbers[i];
            }

        }
        System.out.println("Max number is : "+max);
        System.out.println("Second highest number is : "+secondHighest);        
    }

}

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 2012-11-01
    • 2014-02-20
    • 2018-03-21
    • 2014-02-12
    • 2023-03-22
    • 1970-01-01
    • 2022-12-31
    • 2017-01-04
    相关资源
    最近更新 更多