Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code to print the highest value in an array: 

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);

         }

        }        

    }

}

When I run this code, it prints three values for the highest value in an array. Can anyone tell me why it happens? 

1 Answer

0 votes
by (19.7k points)

You have to move the print statement outside for a loop. Because in your case, it prints whenever it finds a number higher than the current maximum. 

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);

Interested in Java? Check out this Java Certification by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 24, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
0 votes
1 answer
asked Apr 11, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...