-2

So I have searched for different methods, and they all seem WAY to complicated. So exactly what do I need to do, I would prefer not use the array util, in order to print the array? So far I have this:

public static void main(String[] args) 
{
    int a[] = {2, 3, 5, 7, 11, 13};

    int sum = 0;

    System.out.printf("The average of  \n" + a );

    for(int i = 0; i < a.length; i++)
        sum = sum + a[i];

    double avg = sum / a.length;

    System.out.println("\nis\n  " + avg);
}

And it prints this:

The average of
[I@1bd0dd4 is 6.0

Which I am assuming (not sure I am correct) means that it is printing the location of the array not what is contained. (Please do correct me if I am wrong) As well, we were given the answer which is 6.83 and mine is reading out at 6.0 which means I am doing something wrong. Any ideas as to what how to print the array without using any special libraries and where the math issue is coming from?

10
  • 4
    See stackoverflow.com/questions/409784/… and stackoverflow.com/questions/19620225/… Commented Oct 16, 2015 at 21:49
  • 1
    System.out.println(Arrays.toString(a)); Commented Oct 16, 2015 at 21:49
  • 1
    In all actuality though, you shouldn't resist Arrays#toString. It's amazing and far more readable than anything else. Commented Oct 16, 2015 at 21:51
  • 1
    You're going to get a nasty surprise when you see the printed average... beware the integer division... Commented Oct 16, 2015 at 21:52
  • 1
    Also, it's giving you 6.0 because you're using an int to track sum, and when you do sum/size, it truncates to an integer and then puts it into avg. You need to use double. Commented Oct 16, 2015 at 21:52

1 Answer 1

0
System.out.printf("The average of  \n" + a );

You are print the array object, You should iterate over it and print the content individually. OR you can use the Arrays.toString to print the content of the array. Also cast one of the value (either sum or array length) to double got getting the avg. preciously. Use the System.out.format() for printing the decimal values.

int a[] = {2, 3, 5, 7, 11, 13};
System.out.print("The average of \n" + Arrays.toString(a));  // print the array

for(int i = 0; i < a.length; i++)
  sum = sum + a[i];

double avg = (double)sum / a.length;  // cast one of the value to double

System.out.format(" is %.2f", avg);   // print the output upto two decimal.

Output:

The average of 
[2, 3, 5, 7, 11, 13] is 6.83
Sign up to request clarification or add additional context in comments.

3 Comments

why down vote, please comment?
I am unsure. I upvoted for the help. So as far as I am concerned, thank you! :D
I will when it allows me. "Cannot accept answer within 5 minutes of posting".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.