How can I access a variable from inside a do-while loop in Java?
The code below writes out a value until the value entered is not is between 0 and 10.
Here is my code :
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int total +=0;
}while (a>0 && a<10);
System.out.println("Loop Terminated");
System.out.println("The total is : "+total);
}
}
The loop continues to ask for input so long as the input is between 0 and 10. Once some other number is entered the loop terminates and displays the total of all inputted numbers.
try like (declare the variable a outside the loop):
try this
To access a variable beyond the loop, you need to declare/initialize it outside of the loop and then change it inside the loop. If the variable in question wasn't an int, I would suggest that you initialize it to null. However, since you can't initialize an int variable to null, you'll have to initialize it to some random value:
NOTE: If you simply declare the variable before the loop without initializing it (as per @Evginy's answer), you'll be able to access it outside the loop but your compiler will complain that it might not have been initialized.