1
Even though the condition is false, he enters the if
, always assigning the last position in both cases.
However, when assigning the for
in the variable index notas
, works properly.
For this code to work, I added these lines marked with comment, but they are "useless" in the code, since only with the position would suit me. But without them it doesn’t work properly.
class Exer8 {
public static void main(String[] args) {
double maiorValor = 0; /* ESTA */
int indMaior = 0;
double menorValor = 10; /* ESTA */
int indMenor = 0;
double[] notas = {8, 5, 7, 2, 10, 3, 5};
for (int i = 0; i < notas.length; i++) {
if (maiorValor < notas[i]) {
maiorValor = notas[i]; /* ESTA */
indMaior = i;
}
if (menorValor > notas[i]) {
menorValor = notas[i]; /* ESTA */
indMenor = i;
}
}
System.out.println("A maior nota é " + notas[indMaior] + ", Posição: " + indMaior);
System.out.println("A menor nota é " + notas[indMenor] + ", Posição: " + indMenor);
}
}
First, you enter the
if
clearly is notfalse
, you think it is, but it’s not. Second, these lines are not useless, they are fundamental, if they didn’t exist the code is wrong, and if you just added them and didn’t do anything else the code nor compiled.– Maniero
A tip to check what the code is doing is to perform the table test
– hkotsubo