-5

I am a new student in Java (I study myself at home), I tried to solve this exercise starting from this code I could not, the question says:

"Given that you have five input values and "average" method, calculate the average value for the five input values inside the average method and return it" and this is the code:

public class MyCalculator { 

 int input1 = 10; 
 int input2 = 20; 
 int input3 = 30; 
 int input4 = 40; 
 int input5 = 50;

 public float average() {

  // TODO: write java code to calculate the average for all input variables 

   return 0; 
 }
}
vs97
  • 5,765
  • 3
  • 28
  • 41
malik
  • 11
  • 1
  • 1
  • Inputs are generally given as parameters to the method, e.g. `average(int[] inputs)` or `average(int... inputs)`. – RaminS Mar 13 '19 at 23:17
  • 1
    Seems pretty simple. Do you know how to compute the average of five numbers? – FredK Mar 13 '19 at 23:20
  • **Welcome to Stack Overflow!** Did you find the solution? Do you need any more help with this? If any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/a/5235). This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. – lcnicolau Mar 15 '19 at 14:06

1 Answers1

1

Here you have an example in the traditional way:

public float average(int... inputs) {
    long sum = 0;
    for (int i : inputs) {
        sum += i;
    }
    if (inputs.length == 0) {
        return 0;
    } else {
        return (float) sum / inputs.length;
    }
    //return inputs.length == 0 ? 0 : (float) sum / inputs.length;
}

Note the importance of casting to (float) as explained here: Integer division to float result.


And here in most elegant Java 8 way:

public float average(int... inputs) {
    return (float) Arrays.stream(inputs).average().orElse(0);
}

You can see Java 8 Stream and operation on arrays for a better explanation and other examples.


Finally, you can use it like this:

float result = average(input1, input2, input3, input4, input5);

Also, you may want to take a look at this post: Java, 3 dots in parameters.

lcnicolau
  • 3,252
  • 4
  • 36
  • 53
  • The specs say 5 inputs. This does not answer the question in the way expected by the specifications. Additionally, as him being a beginner in java, it is highly unlikely his task will be dealing with a) varargs and b) stream. – gmanrocks Mar 14 '19 at 02:08
  • 1
    Thanks @gmanrocks. I improved the answer with an explanation about _how to use it_ and _where to find more information_. I think it's always good to know that there is something beyond. **As software developers, we never stop being beginners**. – lcnicolau Mar 14 '19 at 03:30