tags:

views:

318

answers:

3

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

        }        
    }
}
+1  A: 

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);
Michael Haren
A: 

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".

twolfe18
+3  A: 

It's printing out a number every time it finds one that is higher than the current max (which happens to occur three times in your case.) Move the print outside of the for loop and you should be good.

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

A couple of other notes (not directly related to the question): You have a 0% accept rate currently, which can actually dissuade people from answering your questions. Consider going back and accepting some answers. Also this sounds like homework. If it is, please consider tagging it as such. People will still help (especially when you have obviously put effort into it like you have here) and the straightforwardness is usually appreciated.

Toji
Thanks for reminding me since I wasn't aware of it. : )
HelloWorld
NP. It's an easy thing for newcomers to miss, but the community tends to like people who reward them for their efforts and as such will usually give you more (and better) answers, which is a very good thing!
Toji