I would like to create public function, that will be used to calculate some value. I would like the value to be the output of the function, for example:
public void Calculation(...)
{
x = y+z/2 +i;
if(x >= 10)
{
calculation = 1;
}
else if(x < 10)
{
calculation = 0;
}
}
and than, to use it in some other place like:
int final = Calculation(...);
My calculation is a lot more bigger, so I don't like placing it on many places, I just want it to be on one place, and to return the value, because I need to use it more times. How can I make this? Thanks in advice.
Currently, you're assigning a value to a variable, and declaring that your method doesn't return anything. Instead, you should just make it return the result:
public int calculate(...)
{
int x = y+z/2 +i;
if(x >= 10)
{
return 1;
}
else if(x < 10)
{
return 0;
}
return 2; // Or whatever...
}
If the method doesn't need any state, you can make it a static method, so you can call it without an instance of the declaring class.
If you need the method just within the type itself; make it private. If you need it within the type hiearchy, make it protected. If you need it within the same package, give it the default access (no modifiers). If you need it everywhere, make it public.
See more on this question at Stackoverflow