Home > Back-end >  Finding Max/Min values in user-defined integer array. Negative numbers included
Finding Max/Min values in user-defined integer array. Negative numbers included

Time:09-14

All of this works to some degree. Here's the issue:

1: User specifies array size. Let's assume size = 5.

2: User inputs 1 2 3 4 5

3: MAX number and MIN number works. All good.

ISSUE: 2: User inputs 5 4 3 2 1

3: MAX number fails. It's defaulted to Integer.MAX_VALUE

This is defined above:

int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;

The Code is here:

for (int i = 0; i < numbers.length; i  ) { //READ INPUT, find smallest / largest
            numbers[i] = myScanner.nextInt();
            sum  = numbers[i]; //ADD Array element values to sum.
            if (numbers[i] < min) { //Loop through array to find smallest value
                min = numbers[i];
            } else if (numbers[i] > max) { //Loop through array to find largest value
                max = numbers[i];
            }
        }

Note: This is a code snippet. "sum" belongs to the rest of the code.

CodePudding user response:

Remove the "else", the two conditions can be true.

for (int i = 0; i < numbers.length; i  ) {largest
    numbers[i] = myScanner.nextInt();
    sum  = numbers[i];
    if (numbers[i] < min) {
        min = numbers[i];
    }
    if (numbers[i] > max) {
        max = numbers[i];
    }
}

CodePudding user response:

If you dry-run the code

User inputs 5 4 3 2 1

  1. 5<min(Integer.MIN_VALUE) so min = 5
  2. 4<min(5) so min = 4
  3. 3<min(4) so min = 3
  4. 2<min(3) so min = 2
  5. 1<min(2) so min = 1

Since you are having an else-if condition.

It never goes to the else condition and max is always Integer.MIN_VALUE

So remove the else-if to if condition.

CodePudding user response:

just remove else in your code, because two condition can be true at the same time

  • Related