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).
Putting the variable out of the loop.
– user28595