Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Find High and Low Number in an Array

Tags:

java

I'm trying to find the high and low number in an array, but I'm not sure why my codes not working correctly. It's giving me the output of 0 and 56. I understand why it's giving the 0, but where did the 56 come from?

package test;

public class Test {

    public static void main(String[] args) {
        int[] numbs = { '2', '4', '2', '8', '4', '2', '5'};

        int count = 0;
        int low = 0;
        int high = 0;

        while(count < numbs.length)
        {
             if(numbs[count]< low) {
                low = numbs[count];
            }

            if(numbs[count]> high) {
                high = numbs[count];
            }

            count++;   
        }

        System.out.println(low); 
        System.out.println(high);           

    }
}
like image 376
Philip Rego Avatar asked Jun 26 '26 08:06

Philip Rego


2 Answers

You need to start the low low enough; currently, you start it at zero - too low to "catch" the lowest element of the array.

There are two ways to deal with this:

  • Use Integer.MAX_VALUE and Integer.MIN_VALUE to start the high and low, or
  • Use the initial element of the array to start both high and low, then process the array starting with the second element.

int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;

P.S. You would find strange numbers printed, because you used characters instead of integers:

int[] numbs = { 2, 4, 2, 8, 4, 2, 5};
like image 196
Sergey Kalinichenko Avatar answered Jun 28 '26 21:06

Sergey Kalinichenko


Also.. It is probably printing the ASCII representation... use actual integers (I'm not sure if your usage of chars was intentional).

like image 34
Lews Therin Avatar answered Jun 28 '26 20:06

Lews Therin