0
Good evening, a teacher sent to class some exercises in Java to do, but as we are at the beginning of the course and I had no basis before, I’m having trouble solving it. Someone could guide me?
The code is this:
public class MathUtils {
public static double average(int a, int b) {
return a + b / 2;
}
public static void main(String[] args) {
System.out.println(average(2,1));
}
}
He asks to fix it in a way that works.
It worked, but I didn’t understand this program structure. Could you explain it to me line by line? In this case I would consider deleting everything and doing so: public class Mathutils { public Static void main(String[] args) { int a, b; avarege = (a+b)/2; System.out.println(avarege); } };}
– game-extreme
Yes, it is totally correct to write like this. However, with the function
average()
, you don’t have to worry, for example, about creating variables (ex:a
,b
) every time that you want to average two values. If the goal of this program is only to average between 2 and 1, I would say that your idea is simpler and more direct. However, when you are creating a larger program, and need to calculate various averages, in various parts of the code, it is good to have functions like these, which can be used several times without having to be rewritten every time.– g-otn
Thank you very much ;)
– game-extreme