0

I am trying to print the occurrences of the two highest integers in an integer array but the output keeps coming out with the top three.

Integer[] scores = {4,4,4,6,6,4,2,3};
        Arrays.sort(scores, Collections.reverseOrder());

        int flag = 0;
        System.out.println(scores[0]);
        int first = scores[0];

        for (int i = 1; i < scores.length; i++) {;
            if(first == scores[i]) {
                System.out.println(scores[i]);
            }else {
                first = scores[i];
                flag++;
                System.out.println(scores[i]);
            }
            if(flag == 2) {
                break;
            }
        }

Is there a better way to have them print? They are currently printing out as 6 6 4 4 4 4 3. The correct output should be 6 6 4 4 4 4

3 Answers3

0

The problem is the System.out.println(scores[i]) after you increment the flag to be 2. You shouldn't be printing when this is the third number in the list.

I've changed/simplified the code as

int flag = 0;
int first = scores[0];
for (int i = 0; i < scores.length; i++) {
    if(first != scores[i]) { //Encountering second number
        first = scores[i];
        flag++;
    }
    if(flag == 2) { //If already seen three numbers, break
        break;
    }
    System.out.println(scores[i]); //Good to print it
}

It is more intuitive to rename first as number or something else as it can hold the first or the second number.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0

Integer[] scores = {4,4,4,6,6,4,2,3}; Arrays.sort(scores, Collections.reverseOrder());

    int flag = 0;
    System.out.println(scores[0]);
    int first = scores[0];
    for (int i = 1; i < scores.length; i++) {;
        if(first == scores[i]) {
            System.out.println(scores[i]);
        }else if(first != scores[i] && flag == 0) {//you need to change this 
            first = scores[i];
            flag++;
            System.out.println(scores[i]);
        }else{ // if you dont want to traverse list after getting desired output
            break;
        }

    }
SSP
  • 2,650
  • 5
  • 31
  • 49
0

I would prefer an int[] over Integer[], and iterate the sorted array backwards. You actually don't need an else here, simply check that you aren't at the end of the array - and if you aren't check that the current score differs from the next (since we're iterating backwards). You only need to test flag when that condition is met (and break after the second change). Like,

int[] scores = { 4, 4, 4, 6, 6, 4, 2, 3 };
Arrays.sort(scores);
for (int i = scores.length - 1, flag = 0; i >= 0; i--) {
    if (i != scores.length - 1 && scores[i] != scores[i + 1]) {
        flag++;
        if (flag >= 2) {
            break;
        }
    }
    System.out.println(scores[i]);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249