0

Here are fragments of the code I have so far. My problem is that the min values come up as Integer.MAX_VALUE, instead of the value I want. iSpeedMph and pressure are both one-dimensional integer arrays.

    //calculating mins
    Integer min = Integer.MAX_VALUE;
    int minSpeed = Integer.MAX_VALUE;
    int minPressure = Integer.MAX_VALUE;
    for(i = 0; i < iSpeedMph.length; i++)
    {
        if (min > iSpeedMph[i])
        {
            min = iSpeedMph[i];
            minSpeed = iSpeedMph[i];
        }
    }

    min = Integer.MAX_VALUE;

    for(i = 0; i < pressure.length; i++)
    {
        if (min > pressure[i])
        {
            min = pressure[i];
            minPressure = pressure[i];
        }
    }
...
    System.out.printf("%7s%2s%-9s%4s%8s%5s%13.3s%5s%16.2s\n", "Minimum",  " ", " ", " ", " ", " ", minPressure, " ", minSpeed);

When I print out the last line, the terminal shows 214 for pressure and 21 for speed, which, without the formatting, means that they are both Integer.MAX_VALUE.

Eli
  • 111
  • 1

5 Answers5

2

You are checking if the current item is greater than the current min, which is Integer.MAX_VALUE, but you want to check if the current item is less than the current min instead, e.g.

if (iSpeedMph[i] < min)

and likewise for the other min determinations.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

The test

if (iSpeedMph[i] > min) 

always returns false. You have to reverse the comparison.

if (iSpeedMph[i] < min) 

or as alternative

if (min > iSpeedMph[i])
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
1

The below condition will never become true for any integer, since min is Integer.MAXVALUE.

if (iSpeedMph[i] > min)

just initialize it 0, to check if you are searching min of all in array or, assign min with first array value and loop the array from 2nd element.

rajuGT
  • 6,224
  • 2
  • 26
  • 44
0

if (iSpeedMph[i] > min) how could this give you the new min value?

Also, please use min methods already written for you, e.g. https://stackoverflow.com/a/1658144/499922

Community
  • 1
  • 1
billc.cn
  • 7,187
  • 3
  • 39
  • 79
0

As others have pointed out you have the comparison in the if statements wrong. But finding min and max in arrays is very simple with Java 8 streams :

int minSpeed = Arrays.stream(iSpeedMph).min().get();
int minPressure = Arrays.stream(pressure).min().get();
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82