[java] Java: Finding the highest value in an array

For some reason this code is printing three values for the highest value in the array when I'm trying to print just one (which is 11.3). Can someone please explain to me why it is doing this?

Thanks.

import java.util.Scanner;

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

        double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
            8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
            3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};

        double total = 0, avgMax = 0;

        for (int counter = 0; counter < decMax.length; counter++)
        {
         total += decMax[counter];
        }

        avgMax = total / decMax.length;

        System.out.printf("%s %2.2f\n", "The average maximum temperature for December was: ", avgMax);

        //finds the highest value
        double max = decMax[0];

        for (int counter = 1; counter < decMax.length; counter++)
        {
         if (decMax[counter] > max)
         {
          max = decMax[counter];
          System.out.println("The highest maximum for the December is: " + max);
         }

        }        
    }
}

This question is related to java arrays max

The answer is


Easiest way which I've found, supports all android versions

Arrays.sort(series1Numbers);

int maxSeries = Integer.parseInt(String.valueOf(series1Numbers[series1Numbers.length-1]));

If you don't want to use any java predefined libraries then below is the

simplest way

   public class Test {

    public static void main(String[] args) {
        double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
            8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
            3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};

        double maxx = decMax[0];

        for (int i = 0; i < decMax.length; i++) {
            if (maxx < decMax[i]) {
                maxx = decMax[i];
            }
        }
        System.out.println(maxx);

    }
}

An easy way without using collections

public void findHighestNoInArray() {
        int[] a = {1,2,6,8,9};
        int large = a[0];
            for(int num : a) {
                if(large < num) {
                    large = num;
                }
            }
            System.out.println("Large number is "+large+"");
        }

You need to print out the max after you've scanned all of them:

for (int counter = 1; counter < decMax.length; counter++)
{
    if (decMax[counter] > max)
    {
        max = decMax[counter];
        // not here: System.out.println("The highest maximum for the December is: " + max);
    }
}  
System.out.println("The highest maximum for the December is: " + max);

A shorter solution to have the max value of array:

double max = Arrays.stream(decMax).max(Double::compareTo).get();

You have your print() statement in the for() loop, It should be after so that it only prints once. the way it currently is, every time the max changes it prints a max.


You can write like this.

import java.util.Scanner;
class   BigNoArray{

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter how many array element");
        int n=sc.nextInt();
        int[] ar= new int[n];
        System.out.println("enter "+n+" values");
        for(int i=0;i<ar.length;i++){
            ar[i]=sc.nextInt();
        }
        int fbig=ar[0];
        int sbig=ar[1];
        int tbig=ar[3];
            for(int i=1;i<ar.length;i++){
                if(fbig<ar[i]){
                    sbig=fbig;
                    fbig=ar[i];
                }
                else if(sbig<ar[i]&&ar[i]!=fbig){
                    sbig=ar[i];
                }
                else if(tbig<ar[i]&&ar[i]!=fbig){
                    tbig=ar[i];
                }
            }
        System.out.println("first big number is "+fbig);
        System.out.println("second big number is "+sbig);
        System.out.println("third big number is "+tbig);
    }
}

void FindMax()
{
    int lessonNum;

    System.out.print("Enter your lesson numbers : ");
    lessonNum = input.nextInt();
    int[] numbers = new int[lessonNum];
    for (int i = 0; i < numbers.length; i++)
    {
        System.out.print("Please enter " + (i + 1) + " number : ");
        numbers[i] = input.nextInt();
    }
    double max = numbers[0];
    for (int i = 1; i < numbers.length; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
    }
    System.out.println("Maximum number is : " + max);
}

You can use a function that accepts a array and finds the max value in it. i made it generic so it could also accept other data types

public static <T extends Comparable<T>> T findMax(T[] array){       
    T max = array[0];
    for(T data: array){
        if(data.compareTo(max)>0)
            max =data;                
    }
    return max;
}

Same as suggested by others, just mentioning the cleaner way of doing it:

int max = decMax[0];
for(int i=1;i<decMax.length;i++)
    max = Math.max(decMax[i],max);
System.out.println("The Maximum value is : " + max);

If you are looking for the quickest and simplest way to perform various actions in regards to arrays, the use of the Collections class is extremely helpful (documentation available from https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html), actions ranges from finding the maximum, minimum, sorting, reverse order, etc.

A simple way to find the maximum value from the array with the use of Collections:

Double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4, 8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2, 3.5, 3.0, 1.1, 6.5, 5.1, -1.2, -5.1, 2.0, 5.2, 2.1};
List<Double> a = new ArrayList<Double>(Arrays.asList(decMax));
System.out.println("The highest maximum for the December is: " + Collections.max(a));

If you are interested in finding the minimum value, similar to finding maximum:

System.out.println(Collections.min(a));

The simplest line to sort the list:

Collections.sort(a);

Or alternatively the use of the Arrays class to sort an array:

Arrays.sort(decMax);

However the Arrays class does not have a method that refers to the maximum value directly, sorting it and referring to the last index is the maximum value, however keep in mind sorting by the above 2 methods has a complexity of O(n log n).


import java.util.*;
class main9 //Find the smallest and 2lagest and  ascending and descending order of  elements in array//
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the array range");
        int no=sc.nextInt();
        System.out.println("Enter the array element");
        int a[]=new int[no];
        int i;
        for(i=0;i<no;i++)
        {
            a[i]=sc.nextInt();
        }
        Arrays.sort(a);
        int s=a[0];
        int l=a[a.length-1];
        int m=a[a.length-2];
        System.out.println("Smallest no is="+s);
        System.out.println("lagest 2 numbers are=");
        System.out.println(l);
        System.out.println(m);
        System.out.println("Array in ascending:");
        for(i=0;i<no;i++)
        {
            System.out.println(a[i]);
        }
        System.out.println("Array in descending:");
        for(i=a.length-1;i>=0;i--)
        {
            System.out.println(a[i]);
        }
    }
}

To find the highest (max) or lowest (min) value from an array, this could give you the right direction. Here is an example code for getting the highest value from a primitive array.

Method 1:

public int maxValue(int array[]){
  List<Integer> list = new ArrayList<Integer>();
  for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
  }
 return Collections.max(list);

}

To get the lowest value, you can use

Collections.min(list)

Method 2:

public int maxValue(int array[]){
  int max = Arrays.stream(array).max().getAsInt();
  return max;
}

Now the following line should work.

System.out.println("The highest maximum for the December is: " + maxValue(decMax)); 

You are just Compare zeroth element with rest of the elements so it will print the value last largest value which it will contain, in you case, same problem is happening. To compare each and every elements we have to swap the values like:

double max = decMax[0];
    for (int counter = 1; counter < decMax.length; counter++){
        if(max<decMax[i]){
            max=decMax[i]; //swapping
            decMax[i]=decMax[0];
        }
    }
    System.out.println("The max value is "+ max);

Hope this will help you


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