An important concept in programming is called scope. In Java, it is defined by curly braces
, { }
, but we will call them block, ie each pair of { }
is a block and, as you may have noticed, you can have a block within another. If you did not notice, notice this typical structure of a Java class:
class Pessoa {
public void chamarPeloNome(String nome) {
if(nome != null) {
System.out.println("Olá, " + nome);
}
}
}
See that the class has a block, the method has a block and the if
inside the method has a block, the if of the block is the innermost and the one of the outermost 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.
Look at 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 block outside, and this is impossible in Java, because, as we said, a variable is accessible in the same block in which it is declared or in internal blocks to it, never in external blocks.
How to solve it then? Simple. Just declare this variable out of for
. As it stands today, it is only visible inside and any other block within the for
that you eventually create (a if
, for example).