user3018155
user3018155

Reputation: 3

Java array min and max issue

package array;
import java.util.*;
public class Array {

public static void main(String[] args) {
     int [] a = new int [10];
     Random number = new Random ();
     int x;
      int min, max ;
      min = max = a[0];

for (int b = 0; b<a.length; b++)
   {
       x = number.nextInt (100);
      // System.out.println (x); just for testing x

      a [b]= x;
       System.out.println (a[b]);

       if (a[b] < min) min = a[b];
       if (a[b] > max) max = a[b];
   }

 System.out.println ("Min is: " + min + " " + "Max is: "+ max );
}
}

When i set min = a[0]; and max = a[0], it only returns max value and min is always 0; Can not figure whats wrong. But when I assign values for a[0]..a[9] it works. Can someone help me please?

Upvotes: 0

Views: 1132

Answers (4)

FTibor
FTibor

Reputation: 1

//if (a[b] < min) min = (a[b]);
//the condition is never met because the min value of x is always 0
package array;
import java.util.*;

public class Array {

    public static void main(String[] args) {
        int [] a = new int [10];
        Random number = new Random ();
        int x;
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        for (int b = 0; b<a.length; b++){
            x = number.nextInt (100);
            // System.out.println (x); just for testing x

            a [b]= x;
            System.out.println (a[b]);

            if (a[b] < min) min = a[b];
            if (a[b] > max) max = a[b];
        }

        System.out.println ("Min is: " + min + " " + "Max is: "+ max ); 
}

Upvotes: 0

Asif Bhutto
Asif Bhutto

Reputation: 3994

min = max = a[0];  // this statement initialize min variable with 0

if (a[b] < min) min = a[b]; // this statement will never execute because your are assigning new value to a[] on each index, even random class generate 0. 

Upvotes: 0

Thomas
Thomas

Reputation: 88707

I assume you only enter positive numbers. For this to work as intended (I assume you want to get the least entered number), initialize min with Integer.MAX_VALUE.

The problem is the following:

int [] a = new int [10]; will create an array of 10 ints and since the elements are primitive integers they're initialized with 0.

min = max = a[0]; will subsequently initialize min with 0, even though x = number.nextInt (100); might later return only numbers greater than 0.

Even initializing max with 0 is wrong, if you try to generate negative numbers as well. Thus better initialize max with Integer.MIN_VALUE.

Upvotes: 0

Alexis C.
Alexis C.

Reputation: 93842

Well number.nextInt (100); will return a number between 0 ans 99. Since you initialize min with a[0]; (which is is 0 when you created your int array), you always get 0 as minimum.

Try to initialise min with min = Integer.MAX_VALUE;

Upvotes: 6

Related Questions