Is the new line after a function starts intended?
private static void largestNumbers(float[] numbers) {
This function could have a better name, functions should have a verb as name, not an adjective.
private static void printLargestNumbersIndex(float[] numbers)
This is more verbose, but you immediately know what the function does.
float largeNumber = numbers[0];
Very minor, but I'd call it largestNumber
.
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > largeNumber) {
largeNumber = numbers[i];
}
}
A foreach
loop would be more appropriate for this use case.
for (float number : numbers) {
if (number > largestNumber) {
largestNumber = number;
}
}
Generally always try to use foreach
loops instead of for
loops unless you need to know the index of the element (which would be the case in the second loop).
for (int j = 0; j < numbers.length; j++) {
For myself I try to avoid one-letter variables as hard as possible (only exception being coordinates, x
y
z
), and this opinion is for sure controversial and non-standard, but I think this loop would gain a lot of readability by simply using index
as variable.
for (int index = 0; index < numbers.length; index++) {
if(largeNumber == numbers[j]){
Always keep in mind that comparing floating point numbers with ==
can be problematic.
System.out.println("largest number index "+j);
Ideally, from a code structure and reuse point of view, your function would return an int[]
or Collection<Integer>
with all found indexes. That would make it easily reusable.
float[] elementList = new float[7];
elementList[0] = 8F;
elementList[1] = 5F;
elementList[2] = 4F;
elementList[3] = 3F;
elementList[4] = 0F;
elementList[5] = 8F;
elementList[6] = 6F;
You can initialize arrays directly with values.
float[] elementList = new float[] {8f, 5f, 4f, 3f, 0f, 8f, 6f};
Also, elementList
is not a great name for this.
Float.NaN
? \$\endgroup\$NullPointerException
ifnumbers
isnull
, 2) No output ifnumbers
is empty, 3) Ignore allFloat.NaN
. \$\endgroup\$