tl;dr
If you asking why your resulting array has one less element than expected, it is because of your initialization of i
variable in your for
loop.
? Change int i = 1
to int i = 0
.
An array does hold all values
You are returning all the values. That is what an array does: holds a series of values. Your code successfully returns an array full of float
primitive values.
Example code
I suggest using ThreadLocalRandom
rather than Math.random
because it offers some simple and handy methods. And it makes you future-proof if you ever do multi-threading.
You need to change your i = 1
to i = 0
to get the right number of elements in your results. Perhaps this is what your Question meant to ask, “Why am I getting one less element in my array than expected?”. Your initialization of i
would be the cause of that problem.
public static float[] generatePatientsTemperatures ( final int patientsCount )
{
float[] patientsTemperature = new float[ patientsCount ];
for ( int i = 0 ; i < patientsCount ; i++ )
{
patientsTemperature[ i ] = ThreadLocalRandom.current().nextInt(320,450) * 0.1F;
}
return patientsTemperature;
}
Try that code. To see all the values of the array as text, call the utility method Arrays.toString( yourArrayHere )
.
float[] temps = App.generatePatientsTemperatures( 3 );
String output = Arrays.toString( temps );
When run:
output = [35.5, 37.100002, 34.3]
Access each element in the array by annoying zero-based counting: zero for the first element, 1 for the second element, and so on.
float first = temps[ 0 ] ;
float second = temps[ 1 ] ;
float third = temps[ 2 ] ;
List
Working with List
is easier than array.
List
holds object references only, no primitive values allowed. Java has an auto-boxing feature to automatically turn your float
primitives into Float
objects. Just redefine your array to hold Float
rather than float
.
Tip: List.of
produces an unmodifiable collection.
public static List < Float > generatePatientsTemperatures ( final int patientsCount )
{
Float[] patientsTemperature = new Float[ patientsCount ];
for ( int i = 0 ; i < patientsCount ; i++ )
{
patientsTemperature[ i ] = ThreadLocalRandom.current().nextInt( 320 , 450 ) * 0.1F; // Auto-boxed from `float` primitive to `Float` object.
}
List < Float > results = List.of( patientsTemperature );
return results;
}
Some code to run it.
List < Float > temps = App.generatePatientsTemperatures( 3 );
String output = temps.toString();
output = [32.8, 43.600002, 35.5]