I've got stuck in a problem about local variables.
The following is not my original code but I use a simple example to present my question:
import java.util.Scanner;
public static void main(String[] args) {
Scanner userScan=new Scanner(System.in);
do{
int input1=userScan.nextInt();
}while(input1>10);
}
My purpose is to let a user type in an integer which is in my intended range. If the typed number does not meet the rule, I hope the user can type again until it does. However, the "input1" is a local variable, so it will not be valid in the expression of while. But I do not want the user to re-type the integer again. Using only one variable would be better. Does anyone have advices about it or other ways which can implement this idea? Thank you!
public static void main(String[] args)
{
Scanner userScan=new Scanner(System.in);
int input1;
do{
input1=userScan.nextInt();
}while(input1>10);
}
just declare input1 outside of the scope of do while loop
Why don't you just do this? :D Delcare the input1 outside the do...while loop, then it can be used in while statement.
import java.util.Scanner;
public static void main(String[] args) {
Scanner userScan=new Scanner(System.in);
int input1 = 0;
do{
input1=userScan.nextInt();
}while(input1>10);
}
The problem is with your input1
variable scope i.e., the scope of your input1
variable is limited to do
while
block (i.e., { }
code), so just declare the variable outside the loop.
int input1 = 0;//scope is now wider, not just limited to the loop
do {
input1=userScan.nextInt();
} while(input1>10);
来源:https://stackoverflow.com/questions/43016946/can-a-local-variable-be-used-out-of-a-method