如何在java中找到数组中第二高的数字

如何在java中找到数组中第二高的数字,java,Java,我想在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

我想在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);

    }
}

您正在尝试在填充数组时查找max和second值。尝试删除

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

你有问题吗?这回答了你的问题吗?实际上,这只适用于正数。不适用于负数。。。
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);        
    }

}