1

I have the following Java method that is supposed to calculate the average of the array:

public class Kata{
    public static double find_average(int[] array){

    int avr = 0;

  for(int a = 0; a < array.length; a++) {
     avr = avr + array[a];
  }
      System.out.println("hello");
      double average = avr / array.length;
      return average;
  }
}

I am confused because I get a stack trace error: expected:<2.5> but was:<2.0> when I use this method. Additionally, printing out "hello" prints 3 times. However, when I return just the number 3, "hello" only prints once. Why does System.out.println("hello") print out multiple times depending on the return value and how can I return the correct array average?

This is particularly confusing to me because one of the answers on this thread indicates that this approach should work for average. How to manipulate arrays. Find the average. Beginner Java

Dog
  • 2,120
  • 3
  • 18
  • 50
  • Please include the code which calls this utility method. Are you running some unit tests testing the method? – sn42 Jul 11 '18 at 00:31
  • it's from a codewars challenge, so it just automatically runs it in the IDE – Dog Jul 11 '18 at 00:31
  • 2
    I can't reproduce the `hello` printing multiple times – GBlodgett Jul 11 '18 at 00:32
  • maybe it's just some kink of codewars – Dog Jul 11 '18 at 00:32
  • The question linked should provide enough information to fix the error. Your other question is why your method gets called multiple times. I assume there are some unit tests written to test if your implementation of the method is correct. They invoke your method multiple times with different inputs and test the output. Just some guess, I'm not familiar with codewars – sn42 Jul 11 '18 at 00:35
  • that doesn't make sense though because the unit tests would run the same amount of times if a number was returned – Dog Jul 11 '18 at 00:36
  • 2
    _This is particularly confusing to me because one of the answers on this thread [...]_, read Marko's answer again. – Sotirios Delimanolis Jul 11 '18 at 00:39
  • 1
    @Dog depends on the unit tests, if for example one test has multiple assertions testing the output of your function and the first assertion fails, the second would never call your function because the first would throw an exception. But again: This is just in theory – sn42 Jul 11 '18 at 17:25

0 Answers0