Print variable inside a repeat structure

Asked

Viewed 430 times

4

Not recognizing the variable soma because she’s inside the loop. What do I do to fix it?

public static void main(String[] args) {

    int tipo;

    int restante = 0;
    int bim = 4;
    //double soma= 0;

    double[] nota = new double[bim];

    Scanner x = new Scanner(System.in);

    System.out.println("inisira a quatidade de bimestres");
    bim = x.nextInt();

    for (int i = 0; i < bim; i++) {
        System.out.println("Insira a nota do " + (i + 1) + "º Bimestre");
        nota[i] = x.nextDouble();
        double soma = 0;
        soma = soma + nota[i];

    }

    double media = soma / bim;
    System.out.println(media);
}
  • 3

    Putting the variable out of the loop.

4 answers

6


Get used to declaring the variable where it will be needed. And understand what is happening with your code. If you do a table test you will see that you are already wrong because every step of the loop the variable will be zeroed and that is not what you want, it does not make any sense in using so, and you had started doing right, then screwed :(. And don’t use unnecessary variables. Here’s how it gets simpler:

import java.util.*;

class Ideone {
    public static void main(String[] args) {
        Scanner x = new Scanner(System.in);
        System.out.println("inisira a quatidade de bimestres");
        int bim = x.nextInt();
        double soma = 0;
        for (int i = 0; i < bim; i++) {
            System.out.println("Insira a nota do " + (i + 1) + "º Bimestre");
            soma += x.nextDouble();
        }
        System.out.println(soma / bim);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

4

An important concept in programming is called scope. In Java, it is defined by curly braces, the { }, but let’s call them block, ie each pair of { } is a block and, as you may have noticed, you may have a block inside another one. If you haven’t noticed, notice this typical structure of a class in Java:

class Pessoa {

   public void chamarPeloNome(String nome) {

      if(nome != null) {
         System.out.println("Olá, " + nome);
      }
   }
}

Note that the class has a block, the method has a block and the if within the method has a block, if is the innermost block and the most external class.

That said, the general rule in Java says that variables defined within a block are only visible within that block or in blocks that are internal to it.

Observe your code:

(...)
for (int i = 0; i < bim; i++) {
        System.out.println("Insira a nota do " + (i + 1) + "º Bimestre");
        nota[i] = x.nextDouble();
        double soma = 0;
        soma = soma + nota[i];

    }

    double media = soma / bim;

The variable soma is defined in a block, but you are trying to access it in a more external block, and that is impossible in Java, because, as we said, a variable is accessible in the same block where it is declared or in internal blocks to it, never in external blocks.

How to solve then? Simple. Just declare this variable outside the for. The way it is today, it’s only visible inside and any other block inside the for that you eventually created (a if, for example).

0

Put the sum variable declaration outside the repeat loop for.

double soma = 0;
for (int i = 0; i < bim; i++) {
     System.out.println("Insira a nota do " + (i + 1) + "º Bimestre");
     nota[i] = x.nextDouble();        
     soma = soma + nota[i];
}
  • 3

    "It is not good practice to declare variables within loops of repetition" - I’d say it depends. If the variable is only going to be used inside the loop, there is no problem (and depending on the case is even better, because there limits the scope of it). If it is used outside the loop (as is the case with this question), then it is not even a matter of "good practice", it is because it does not make sense at all :-)

  • 2

    I disagree with this final statement, there is no "good practice", there is what makes logical sense and what does not. As explained by @hkotsubo, there are situations where this makes perfect sense.

  • 2

    The text line before the code is right. The one that is after, totally wrong.

  • 1

    Luan, why do you think it’s bad practice?

  • I had read that making this statement within the loop always causes a new variable to be created in memory at each iteration. Enter the loop, create the variable by allocating space in memory to it, use the variable according to the logic within the loop, at the end of the loop this variable "is played out", in the next interaction of the loop it would create a "new" variable of the same type and name. Then it would be "destroying and creating" a variable at each iteration, in which it could be reused.

  • That would be my justification: https://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop

  • The answers in this link say that it is better to declare the variable in the smallest possible scope. That is, if it is only used inside the loop, declare it inside. If it is used outside, declare it outside. At no time did they say that "It is not good practice to declare variables within loops of repetition" (actually suggest otherwise, if applicable). Moreover, one of the answers saw that it makes no difference in the bytecode and the supposed performance gain (by avoiding the "create-destroy" cycle you mentioned) is irrelevant.

  • 1

    True, it makes sense, I get it, thank you =)

Show 3 more comments

-2

In Java there is a strong typing, its variable soma was declared internally in the loop for, ie, it is visible only inside the loop. If you want to use it outside the loop for, I advise to declare her out of the loop:

public static void main(String[] args) {

    int tipo;

    int restante = 0;
    int bim = 4;
    double soma = 0;


    double[] nota = new double[bim];

    Scanner x = new Scanner(System.in);

    System.out.println("inisira a quatidade de bimestres");
    bim = x.nextInt();

    for (int i = 0; i < bim; i++) {
        System.out.println("Insira a nota do " + (i + 1) + "º Bimestre");
        nota[i] = x.nextDouble();
        soma = soma + nota[i];

    }

    double media = soma / bim;
    System.out.println(media);
}

Browser other questions tagged

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