I need help because my brain cells cannot find what is wrong with this program! Here\'s the code
import java.util.*;
public class student{
publ
When you go through to look for either the minimum or maximum of a set of values, it's better to assume that all values will be larger than a default maximum value (i.e. set your maximum value to the smallest possible integer), and that all values will be smaller than a default minimum value (i.e. set your minimum value to be the largest possible integer).
The above sounds counterintuitive, but as you iterate through the array, if you come across a value that is "larger" than the maximum, you update your max value. The same idea applies for the minimum (i.e. if you find a value smaller than your minimum). Since both would start out at their logical extremes, you'll be able to find the true minimum/maximum easier.
The code
int maxValue=myArray[0];
int minValue=myArray[0];
implies that both maxValue
and minValue
are 0, since a primitive integer array will always populate itself with zeroes. Instead, you should try this:
int maxValue=Integer.MIN_VALUE;
int minValue=Integer.MAX_VALUE;
For some clarification on those Integer
constants, check out Integer.MAX_VALUE and Integer.MIN_VALUE in the API.