javadrjava

Finding the second largest number of given integers without using array


Using if loops, I am tasked with putting the largest & 2nd largest integers into a pair, and the smallest & 2nd largest integers into a pair, from user provided numbers.

I have tried several different if conditions, and while my program can find the 2nd smallest integer correctly, if i apply the same logic (with reversed greater than/smaller than signs), I don't get the correct answer.

           numN = keyboard.nextInt();
           if (numN > numL1){
              numL1 = numN;
           }

           if (numN < numS1){
              numS1 = numN; 
           }
           else if (numN < numS2 && numS2 > numS1){
              numS2 = numN;
           }
           else if (numN > numL2 && numL2 < numL1){
              numL2 = numN;
           }

If User inputs the four numbers 1,2,3,4

Actual results: Largest and Smallest Pairs: (4,4) (1,2)

Needed results: Largest and Smallest Pairs: (4,3) (1,2)


Solution

  • you can do this like below:

    int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE, min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE;
    
        int input = keyboard.nextInt();
        if (input > max) {
            secondMax = max;
            max = input;
        } else if (input > secondMax) {
            secondMax = input;
        }
        if (input < min) {
            secondMin = min;
            min = input;
        } else if (input < secondMin) {
            secondMin = input;
        }