Finding the minimum value of int numbers in an array (Java)

后端 未结 10 1936
天涯浪人
天涯浪人 2020-12-22 10:42

I\'m trying to find the minimum value of numbers in an array but it doesn\'t always work out properly. This is the code I wrote:

        for (int i=0; i <         


        
相关标签:
10条回答
  • 2020-12-22 11:01

    One option is sort your array and get the first element:

    import java.util.Arrays;
    
    ...
    
    int ints[] = {30,5,7,4,10};
    Arrays.sort(ints);
    
    int min = ints[0];
    int max = ints[ints.length - 1];
    
    0 讨论(0)
  • 2020-12-22 11:03

    If arr is an array of non-primitive numerics, I'd recommend

    java.util.Collections.min(java.util.Arrays.asList(arr));

    as that will be simpler to maintain. There's some justification in reverting to hand-coding if you need to pull the minimum and maximum out at the same time but I'd advise against hand-coding loops if there's a library function available.

    In any case, you ought to check arr != null and the existence of a zeroth element.

    0 讨论(0)
  • 2020-12-22 11:03

    TRY this:

    int min = arr[0];
        for(int j=1;j<arr.length;j++)
        {
                if(min>arr[j])
                {
                    min= arr[j];
                }
        }
        System.out.println("min no is "+min);
    
    0 讨论(0)
  • 2020-12-22 11:07

    I am entering 5 values and storing them in the array and looping through them to find the min value but it prints 0 all the time. What's wrong in this code? I used the same logic for the max value and has no problem.

    public class FindMinValue {
    
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            int i;
            int NUM_VALUES = 5;
            int[] userVals = new int [NUM_VALUES];
            
            System.out.println("Enter " + NUM_VALUES + " values one at a time.");
            
            int minVal = userVals[0]; //min value so far
            
            for(i = 0; i < userVals.length; ++i) {
                userVals[i] = scnr.nextInt();
                if(userVals[i] < minVal) {
                    minVal = userVals[i];
                }
            }
            System.out.println("Min Value is :" + minVal);
            
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-22 11:09
    int min = arr[0];
    for(int num : arr) {
        if (num < min){
            min = num;
        }
    }
    

    min now contains minimum value.

    0 讨论(0)
  • 2020-12-22 11:15
          int min=0; 
            for (int i = 0; i < array.length; i++) {
            if (min > array[i]) {
            min = array[i];
            }
    }
    
        System.out.println(min);
    

    simple way to get MAX and MIN

    To get MIN

    System.out.println(getMinValue(your array)); 
    

    and for MAX

    System.out.println(getMaxValue(your array));
    
    0 讨论(0)
提交回复
热议问题