[java] Java Minimum and Maximum values in Array

My code does not give errors, however it is not displaying the minimum and maximum values. The code is:

Scanner input = new Scanner(System.in);

int array[] = new int[10];

System.out.println("Enter the numbers now.");

for (int i = 0; i < array.length; i++) {
    int next = input.nextInt();
    // sentineil that will stop loop when 999 is entered
    if (next == 999) {
        break;
    }
    array[i] = next;
    // get biggest number
    getMaxValue(array);
    // get smallest number
    getMinValue(array);
}

System.out.println("These are the numbers you have entered.");
printArray(array);


// getting the maximum value
public static int getMaxValue(int[] array) {
    int maxValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] > maxValue) {
            maxValue = array[i];
        }
    }
    return maxValue;
}

// getting the miniumum value
public static int getMinValue(int[] array) {
    int minValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] < minValue) {
            minValue = array[i];
        }
    }
    return minValue;
}

//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
    int n = arr.length;

    for (int i = 0; i < n; i++) {
        System.out.print(arr[i] + " ");
    }
}

Do I need a system.out.println() to display it, or should the return work?

This question is related to java arrays max minimum

The answer is


your maximum, minimum method is right

but you don't print int to console!

and... maybe better location change (maximum, minimum) methods

now (maximum, minimum) methods in the roop. it is need not.. just need one call

i suggest change this code

    for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       break;
       array[i] = next;
}
System.out.println("max Value : " + getMaxValue(array));
System.out.println("min Value : " + getMinValue(array));
System.out.println("These are the numbers you have entered.");
printArray(array);

You can try this too, If you don't want to do this by your method.

    Arrays.sort(arr);
    System.out.println("Min value "+arr[0]);
    System.out.println("Max value "+arr[arr.length-1]);

You are doing two mistakes here.
1. calling getMaxValue(),getMinValue() methods before array initialization completes.
2.Not storing return value returned by the getMaxValue(),getMinValue() methods.
So try this code

   for (int i = 0 ; i < array.length; i++ ) 
  {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
       break;
       array[i] = next;
  }
  // get biggest number
  int maxValue = getMaxValue(array);
  System.out.println(maxValue );

  // get smallest number
  int minValue = getMinValue(array);
  System.out.println(minValue);

You just throw away Min/Max values:

  // get biggest number
  getMaxValue(array); // <- getMaxValue returns value, which is ignored
  // get smallest number
  getMinValue(array); // <- getMinValue returns value, which is ignored as well

You can do something like

  ... 
  array[i] = next;

  System.out.print("Max value = ");
  System.out.println(getMaxValue(array)); // <- Print out getMaxValue value

  System.out.print("Min value = ");
  System.out.println(getMinValue(array)); // <- Print out getMinValue value

  ...  

Imho one of the simplest Solutions is: -

//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);

//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);

Here you haven't print the max and min values. Print the max and min values in the getMaxVal and getMin val methods or after the call. This is the output.

Enter the numbers now.
5
Max: 5
Min: 0
3
Max: 5
Min: 0
7
Max: 7
Min: 0
3
Max: 7
Min: 0
90
Max: 90
Min: 0
43
Max: 90
Min: 0
100
Max: 100
Min: 0
45
Max: 100
Min: 0
23
Max: 100
Min: 0
22
Max: 100
Min: 3
These are the numbers you have entered.
5 3 7 3 90 43 100 45 23 22

Also when you are declaring an array, it has all 0s initially.


I have updated your same code please compare code with your's original code :

public class Help {

public static void main(String args[]){
    Scanner input = new Scanner(System.in);

    int array[] = new int[10];

    System.out.println("Enter the numbers now.");

    for (int i = 0; i < array.length; i++) {
        int next = input.nextInt();
        // sentineil that will stop loop when 999 is entered
        if (next == 999) {
            break;
        }
        array[i] = next;
    }

    System.out.println("These are the numbers you have entered.");
    printArray(array);

    // get biggest number
    System.out.println("Maximum: "+getMaxValue(array));
    // get smallest number
    System.out.println("Minimum: "+getMinValue(array));
}

// getting the maximum value
public static int getMaxValue(int[] array) {
    int maxValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] > maxValue) {
            maxValue = array[i];
        }
    }
    return maxValue;
}

// getting the miniumum value
public static int getMinValue(int[] array) {
    int minValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] < minValue) {
            minValue = array[i];
        }
    }
    return minValue;
}

//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
    int n = arr.length;

    for (int i = 0; i < n; i++) {
        System.out.print(arr[i] + " ");
    }
}
}

//To Find Max and Min value in an array without sorting in java

import java.util.Scanner;
import java.util.*;
public class MaxMin_WoutSort {
 public static void main(String args[])
   {
      int n,max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
      System.out.println("Enter the number of elements: ");
      Scanner sc = new Scanner(System.in);

      int[] arr = new int[sc.nextInt()]; //U can't say static or dynamic.
                                         //UnWrapping object sc to int value;sc.nextInt()
      System.out.println("Enter the elements: ");
      for(int i=0;i<arr.length;i++)      //Loop for entering values in array
      {
          int next = sc.nextInt();
          arr[i] = next;
      }
      for(int j=0;j<arr.length;j++)
     {
          if(arr[j]>max)               //Maximum Condition
            max = arr[j];
          else if(arr[j]<min)         //Minimum Condition
              min = arr[j];
     }
     System.out.println("Highest Value in array: " +max);
     System.out.println("Smallest Value in array: "+min);

 }
}

Here is the working code to find the min and max in the array.I hope you will find it helpful:

 import java.util.Random;
 import java.util.Scanner;
 public class FindMin {
    public static void main(String[] args){
        System.out.println("Main Method Started");
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the size of the arr");
        int size = in.nextInt();
        System.out.println("Enter the maximum value of the arr");
        int max = in.nextInt();
        int [] arr  = initializeArr(max, size);
        print(arr);
        findMinMax(arr);
        System.out.println("Main Method Ended");
    }
    public static void print(int[] arr){
        for(int val:arr){
            System.out.print(val + " ");
        }
        System.out.println();
    }
    public static int[] initializeArr(int max,int size){
        Random random = new Random();
        int [] arr = new int[size];
        for(int ii=0;ii<arr.length;ii++){
            arr[ii]=random.nextInt(max);
        }
        return arr;
    }
    public static void findMinMax(int[] arr){
        int min=arr[0];
        int max=arr[0];
        for(int ii=0;ii<arr.length;ii++){
            if(arr[ii]<min){
                min=arr[ii];
            }
            else if(arr[ii]>max){
                max=arr[ii];
            }
        }
        System.out.println("The minimum in the arr::"+min);
        System.out.println("The maximum in the arr::"+max);
    }
}

import java.util.*;
class Maxmin
{
    public static void main(String args[])
    {
        int[] arr = new int[10];
        Scanner in = new Scanner(System.in);
        int i, min=0, max=0;
        for(i=0; i<=arr.length; i++)
        {
            System.out.print("Enter any number: ");
            arr[i] = in.nextInt();          
        }
        min = arr[0];
        for(i=0; i<=9; i++)
        {
            if(arr[i] > max)
            {
                max = arr[i];
            }
            if(arr[i] < min)
            {
                min = arr[i];
            }
        }
        System.out.println("Maximum is: " + max);
        System.out.println("Minimum is: " + min);
    }
}

Sum, Maximum and Minimum value of an Array in One Line

 public static void getMinMaxByArraysMethods(int[] givenArray){

       //Sum of Array in One Line 
       long sumofArray =  Arrays.stream(givenArray).sum();

       //get Minimum Value in an array in One Line
        int minimumValue = Arrays.stream(givenArray).min().getAsInt();

        //Get Maximum Value of an Array in One Line
        int MaxmumValue =  Arrays.stream(givenArray).max().getAsInt();

    }

Yes you need to use a System.out.println. But you are getting the minimum and maximum everytime they input a value and don't keep track of the number of elements if they break early.

Try:

for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
           break;

       array[i] = next;
 }
 int length = i;
 // get biggest number
 int large = getMaxValue(array, length);
 // get smallest number
 int small = getMinValue(array, length);

 // actually print
 System.out.println( "Max: " + large + " Min: " + small );

Then you will have to pass length into the methods to determine min and max and to print. If you don't do this, the rest of the fields will be 0 and can mess up the proper min and max values.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to max

Min and max value of input in angular4 application numpy max vs amax vs maximum mongodb how to get max value from collections Python find min max and average of a list (array) Max length UITextField How to find the highest value of a column in a data frame in R? MAX function in where clause mysql Check if all values in list are greater than a certain number How do I get the max and min values from a set of numbers entered? SQL: Group by minimum value in one field while selecting distinct rows

Examples related to minimum

Java Minimum and Maximum values in Array Python: Find index of minimum item in list of floats How to scale down a range of numbers with a known min and max value find a minimum value in an array of floats Get the key corresponding to the minimum value within a dictionary