【问题标题】:variable scope related to while loop showing an error while accesing it after the while loop it is showing an err与while循环相关的变量范围在while循环之后访问它时显示错误,它显示错误
【发布时间】:2021-09-10 22:53:14
【问题描述】:
import java.util.*;

public class gcd {
                
    public static void main(String[] args){
        Scanner scn = new Scanner(System.in);
                 
        int n1 = scn.nextInt();
        int n2 = scn.nextInt();
        int rem;
        while(n1 % n2 != 0 ){
            r = n1 % n2;
            n1 = n2;
            n2 = rem;
        }
        System.out.println("gcd is :"+divisor);
        System.out.println(rem);
    }
}

我在循环外声明rem 变量,在while 循环中对其进行初始化,并在while 循环之后再次访问它。它显示此错误:

代码有什么问题?

【问题讨论】:

  • 如果while条件立即为假,则rem = dividend % divisor;不会被执行,所以rem不会被初始化;
  • 现在你的代码混淆了rrem,没有意义。
  • 从不声明加除数。您问题的代码应直接从您的代码中复制。

标签: java loops scope initialization declaration


【解决方案1】:

原因是 while 循环可能永远不会被执行。所以循环内的初始化可能永远不会发生。

此外,编译器无法计算条件的结果,因为它依赖于未知的用户输入。

在声明处初始化您的变量rem

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2014-03-29
    相关资源
    最近更新 更多