-1

I want to find second highest number in array in java. I tied to solve problem from this code.

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

    }
}

2 Answers2

1

You're trying to find the max and second values while populating the array. Try removing

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

from the for loop. Then add a separate (not nested) for loop to search the array:

   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];
    }
Bluejay
  • 47
  • 6
0
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);        
    }

}