The program is supposed to generate 5 random numbers into an array and find the maximum and minimum values in separate methods. I have no issue with the maximum, but whenever i return the minimum I always get zero.
public class ArrayMethods
{
public static void main(String[] args)
{
System.out.print("The array is ");
int[] arr = new int[1000];
for (int i = 0; i < 5; i++)
{
arr[i] = (int)(Math.random() * 1000);
System.out.print(arr[i] + " ");
}
System.out.println("\nThe max is " + arrayMax(arr));
System.out.println("The min is " + arrayMin(arr));
}
public static int arrayMax(int[] arr)
{
int arrayMax = arr[0];
for(int i = 1; i < arr.length; i++)
{
if (arr[i] > arrayMax)
{
arrayMax = arr[i];
}
}
return arrayMax;
}
public static int arrayMin(int[] arr)
{
int arrayMin = arr[0];
for(int i = 1; i < arr.length; i++)
{
if (arr[i] < arrayMin)
{
arrayMin = arr[i];
}
}
return arrayMin;
}
}
5 Answers 5
arr
is an array containing 1000 entries, all of which are initialized to zero by default. Your loop sets five of them to some random positive non-zero value, so when you look for the minimum, if none of the random numbers were zero, then one of the later zeros already there will be the minimum.
Comments
Instead of:
int[] arr = new int[1000];
for (int i = 0; i < 5; i++)
{
..
}
use:
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++)
{
..
}
Comments
your array is declared to have 1000
elements, and therefore after initialising the first five elements; the remaining elements from the 5th
index until 999
will consist of zeros (as this is the default behaviour for integer arrays if you don't explicitly specify the elements), so the minimum will always be 0
.
you only need to do:
int[] arr = new int[5];
Comments
You're getting 0 because that's the default value of integer field and since your array size is 1000 there are integers which have value of 0.
Comments
Of course your are. You initialize an array of 1000 int values (defaulting all to zero), but only set the the first five to another value. When you check in arrayMin, you check all 1000 values, where 995 of them are zero. As Aominé commented, you should size the array to the number of values you are goind to fill. On the side line, I would set the initial values of arrayMax and arrayMin to Integer.MIN_VALUE (arrayMax) and Integer.MAX_VALUE (arrayMin) respectively, if you do not want to use the built-in Collections.min/max methods.
java.util.Collections.max/min
, so you only need to doCollections.max(Arrays.asList(array))