为什么在do while循环中定义的变量无法解析为变量。

huangapple go评论91阅读模式
英文:

why an variable defined in a do while loop Cannot be resolved to a variable

问题

这是简单的代码示例:

package first;

public class DowhileLoops {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        do {
            int i = 1;
            i++;
            System.out.println("我的循环正在工作");
            
        } while (5 > i);
    }
}

这是错误信息:

Exception in thread "main" java.lang.Error: 无法解析的编译问题
i 无法解析为变量
at todowhileloops/first.DowhileLoops.main(DowhileLoops.java:15)

我知道变量必须在循环外部定义,而不是在循环内部,但我想知道为什么... 请帮忙解答并投票支持这个问题。

英文:

Here is the simple code

package first;

public class DowhileLoops {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		do {
			int i = 1;
			i++;
			System.out.println("my loop is working ");
			
		}while(5 > i);
	}
}

Here is the Error

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
i cannot be resolved to a variable
at todowhileloops/first.DowhileLoops.main(DowhileLoops.java:15)

I khow that the variable must be defined outside instead of inside the loop but i want to know whyyyyy... please help and vote the question.

答案1

得分: 2

do 语句之外定义变量 i。根据您当前的代码,变量 i 的作用范围仅限于 do{} 内部。它是 do 语句的局部变量。它无法在 while() 内部访问。

英文:

Define i outside do statement. From your current code the scope of i is only inside do{}. It is a local variable for do. It's not accessible to while().

答案2

得分: 1

while 循环条件仅能访问“当前”变量作用域。
do 块创建一个“子”变量作用域。在“子”变量作用域中声明的任何变量都无法在“父”作用域中访问。

请参阅 https://www.java-made-easy.com/variable-scope.html 中的“循环作用域”以获取更详细的解释。

英文:

The while conditional only has access to "current" variable scope.
The do block creates a "child" variable scope. Any variables declared in a "child" variable scopes are not accessible in "parent" scopes.

See "Loop Scope" in https://www.java-made-easy.com/variable-scope.html for a more detailed explanation.

答案3

得分: 1

int i = 0;
do {
    i++;
    System.out.println(i);
} while (i < 5);
英文:
do {
    int i = 1;
    i++;
    System.out.println(&quot;my loop is working &quot;);
} while(5 &gt; i);

Ok, so first off, you have to initialize the variable outside of the loop itself. so before you write "do {". right now you're setting i to 1 every iteration, meaning this loop will never terminate. Here you go:

int i = 0;
do {
    i++
    System.out.println(i);
} while (i &lt; 5);

huangapple
  • 本文由 发表于 2020年4月11日 04:54:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/61148548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定