1
Why the following program does not work?
package javaapplication1;
import java.util.Scanner;
public class Exemplo008 {
public static void main(String[] args){
Scanner teclado = new Scanner(System.in);
int soma =0;
do{
System.out.print("Digite um número (0 para sair):");
int valor = teclado.nextInt();
soma += valor;
} while(valor != 0); //Aqui está dando erro.
System.out.printf("\n A soma dos números digitados é: %d\n",soma);
}
}
On the line of while
, variable cannot be found. This example was used in my college and is copied correctly.
It is a question of scope. Imagine that the scope of the local variable within the method is valid until the "lock keys" of the block in which it was declared. Then the variable
valor
only goes to the linesoma += valor;
, because soon after it finds a "lock keys"; as thewhile
ofdo-while
is beyond this key, the variable is out of scope/no longer exists.– Jefferson Quesado
Far be it from me to say that you can’t choose the answer you want, but since you switched acceptance sometimes you may not have chosen the one you really want. If it is the one you want, you can leave it where it is, no problem, except for the fact that it is not exactly correct and gives wrong information to those who read here. See [tour]. You can only accept one answer and the one you accept last is the one you will be left with. Want to rethink which one you will accept? When you have 15 points you can vote on all answers to your question or website. You can leave this if you wish.
– Maniero