Thus:
float[] floatArray = new float[]{1.0f, 2.2f, 3.4f};
vetorFloat(floatArray);
Then the method and class in static context would look like this:
class main {
public static void main(String[] args) {
float[] floatArray = new float[]{1.0f, 2.2f, 3.4f};
vetorFloat(floatArray );
}
private static float vetorFloat(float[] vetor) {
//algum código
return vetor[x];
}
}
Only that one X in the return vetor[x];
will give build problem. It needs to be solved. It can be like this:
class Main {
public static void main(String[] args) {
float[] floatArray = new float[]{1.0f, 2.2f, 3.4f};
vetorFloat(floatArray );
}
private static float vetorFloat(float[] vetor) {
int x = 0;
return vetor[x];
}
}
Now your method will return the first position of the past array.
As you did, you are passing an element of the array, not the whole array. In my example, I declare a new array and already fill it. Hence the variable floatArray
represents the whole array and if I do floatArray[0]
, i am accessing only the first element of the array, which in this case is 1.0.
That "F" right there in the number, it’s for Java to know that it’s a float
. When you fill in an arbitrary number in the code, java doesn’t know if it treats as int
, float
, long
... then you specify after declaring the number. Examples:
long 0L
float 0.0f
double 0.0d
See the official documentation on the primitive types. It can help a lot.
Complementing: call the method
vetorFloat()
in a static context also gives build error. One must declare the methodvetorFloat()
asstatic
or call it in instance context (a non-static method, for example).– Piovezan
@Piovezan, I noticed this. I used Ricardo Giaviti’s answer and gave such error in the compilation... "non-static method vetorFloat(float[]) cannot be referenced from a Static context".
– ptkato
Sorry guys. I didn’t notice. I edited my answer.
– humungs
I stopped to analyze the situation and I realized something... I don’t need all this, because everything is within the method
vetorFloat(float[] vetor)
, When I say everything, I mean data entry, data output, accounts, data processing and so on, what I meant is something that just tells the program: run this method. In this case, the main methodmain
would just be a method that executes other methods, nothing more.– ptkato