Why do you enter if even if it is false?

Asked

Viewed 117 times

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);
    }
}
  • 5

    First, you enter the if clearly is not false, 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.

  • A tip to check what the code is doing is to perform the table test

2 answers

2

Within the if you change only the value of indMaior without changing the value of maiorValor. I mean, WHENEVER YOU GET TO THIS if he does if(0 < notas[i]), since there is no value less than or equal to 0 in the array, it will always be true.

As @Maniero said in the comments, these lines are actually fundamental.

  • 1

    wow, vdd, I didn’t even notice it.

2


You can do the same thing by saving some variables and assignments.

Behold:

class Exer8 {

    public static void main(String[] args) {

        int indMaior = 0;
        int indMenor = 0;
        double[] notas = {8, 5, 7, 2, 10, 3, 5};

        for (int i = 0; i < notas.length; i++) {

            if (notas[indMaior] < notas[i]) {
                indMaior = i;
            }
            if (notas[indMenor] > notas[i]) {
                indMenor = i;
            }
        }
        System.out.println("A maior nota é " + notas[indMaior] + ", Posição: " + indMaior);
        System.out.println("A menor nota é " + notas[indMenor] + ", Posição: " + indMenor);
    }
}

In this case, I only used the element index in the array. When it is identified that element of the array meets the greater or lesser condition. The index is passed to the corresponding index indMaior or indMenor.

I hope I contributed.

  • Thank you. Really that way the code gets much better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.