Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
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):
int a = -1;
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
}while (a>0 && a<10);
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:
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
int a = 0; //create it here
do {
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
} while (a>0 && a<10);
System.out.println("Loop Terminated");
// do something with a
}
}
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.
try this
Scanner in = new Scanner(System.in);
int a;
do {
System.out.println("Enter a number between 0 an 10");
a = in.nextInt();
} while (a > 0 && a < 10);
System.out.println("Loop Terminated");