JAVA:是否可以在循环外使用已在循环内初始化的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35885718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA: Is it possible to use a variable outside a loop that has been initialised inside a loop?
提问by max
I'm a new programmer trying to practice by making a game. I want the player to be able to set their own name, as well as answer yes or no as to whether that name is correct. I did this by using a while loop. However, since the name is initialized inside the loop, I cannot use it outside. I was wondering if there was anyway to do so.
我是一个新的程序员,试图通过制作游戏来练习。我希望玩家能够设置他们自己的名字,并就该名字是否正确回答是或否。我通过使用 while 循环来做到这一点。但是,由于名称是在循环内部初始化的,因此我无法在外部使用它。我想知道是否有办法这样做。
My code is probably very basic and messy. I apologize for that.
我的代码可能非常基本和凌乱。我为此道歉。
Scanner input = new Scanner(System.in);
String name;
int nameRight = 0;
while (nameRight == 0) {
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("So, your name is " + name + "?");
String yayNay = input.nextLine();
if (yayNay.equals("yes") || yayNay.equals("Yes")) {
System.out.println("Okay, " + name + "...");
nameRight++;
}
else if (yayNay.equals("no") || yayNay.equals("No")) {
System.out.println("Okay, then...");
}
else {
System.out.println("Invalid Response.");
}
}
So basically, I want String name to be initialized inside the loop, so I can use it outside the loop.
所以基本上,我希望在循环内初始化字符串名称,这样我就可以在循环外使用它。
采纳答案by Peter Lawrey
The scope of a variable, limits the use of that variable to the scope it is defined in. If you want it used in a broader scope, declare it outside the loop.
变量的范围,将该变量的使用限制在定义它的范围内。如果您希望它在更广泛的范围内使用,请在循环外声明它。
However, since the name is initialized inside the loop, I cannot use it outside.
但是,由于名称是在循环内部初始化的,因此我无法在外部使用它。
You have defined the variable outside the loop, so the only thing you need to do is to initialize it, as the error message you should get suggests.
您已经在循环外定义了变量,因此您唯一需要做的就是初始化它,正如您应该收到的错误消息所暗示的那样。
String name = "not set";
while(loop) {
name = ...
if (condition)
// do something to break the loop.
}
// can use name here.
The basic problem is that the compiler cannot work out that the variable will be set in all possible code paths. There is two ways you can fix this without using a dummy value. You can use a do/while
loop.
基本问题是编译器无法确定将在所有可能的代码路径中设置变量。有两种方法可以在不使用虚拟值的情况下解决此问题。您可以使用do/while
循环。
String name;
boolean flag = true;
do {
name = ...
// some code
if (test(name))
flag = false;
// some code
} while(flag);
or drop the condition, as you don't need a counter.
或删除条件,因为您不需要计数器。
String name;
for (;;) {
name = ...
// some code
if (test(name)) {
break;
// some code if test is false.
}
回答by Rishi
NO, it wouldn't be possible as the scope of the variable declared in the loop is limited to the loop. So the variable is not longer accessible.
不,这是不可能的,因为在循环中声明的变量的范围仅限于循环。因此该变量不再可访问。
while(i < 10){
int x = 2;
i++;
}
Now, the scope of x would be from the point at which it is defined to the end of the enclosing block. So the variable here would be created and destroyed 10 times if i starts from 0.
现在, x 的范围将从定义它的点到封闭块的末尾。所以如果 i 从 0 开始,这里的变量将被创建和销毁 10 次。
回答by Chexxor
First there's the "scope", this is the issue you're touching at the moment. The way you have done this so far seems to be a good way of doing it and you WILL be able to use/access the name variable from anywhere in the code after line 2 from what you have linked.
首先是“范围”,这是您目前正在接触的问题。到目前为止,您这样做的方式似乎是一种很好的方式,您将能够从您链接的第 2 行之后的代码中的任何位置使用/访问 name 变量。
The scope basically says, you can use the variable inside the curly brackets {} that you DECLARED it inside. I assume that you have your code inside some main method at the moment, thus you can access the name variable from anywhere after the line
范围基本上是说,您可以在大括号 {} 内使用您在其中声明它的变量。我假设您现在在某个 main 方法中有您的代码,因此您可以从该行之后的任何位置访问 name 变量
String name;
as long as you don't try to use it after the closing }, corresponding to a opening { that occurred before name is declared.
只要您不尝试在结束 } 之后使用它,对应于在声明 name 之前发生的开始 {。
SOLUTION:What you have to do to use a variable outside a loop, is to declareit before the loop begins, you don't have to initializethe variable before, butyou have to initialize it before you try to use it for anything. In general, if you need to access the variable in a wider area, you must declarethat variable before you enter the not-so-wide area.
解决方案:在循环外使用变量必须做的是在循环开始之前声明它,之前不必初始化变量,但必须在尝试将其用于任何事情之前初始化它。一般情况下,如果需要访问更广区域的变量,则必须在进入不那么宽的区域之前声明该变量。
Notice that by declaring I mean creating the variable reference by using "String" in front of "name". Don't confuse it with initializing it or assigning a value to it, that has nothing to do with the scope, only declaration sets the scope.
请注意,声明我的意思是通过在“名称”前面使用“字符串”来创建变量引用。不要将它与初始化或为其赋值混淆,这与作用域无关,只有声明设置了作用域。