【问题标题】:Method level scope of variables变量的方法级别范围
【发布时间】:2013-03-10 06:30:50
【问题描述】:

我是Java的初学者,在练习时遇到了这些错误,所以我想澄清它们,而不是试图记住错误来避免它们。

public static int gcd(int a, int b) {
  if(a > b) {
    int result = a % b;
  }
  return result;
}

这会生成我a cannot find symbol,但我认为我在if 循环中将结果初始化为int

public static int gcd(int a, int b) {
  if(a > b) {
    int result = a % b;
    return result;
  }
}

为此,如果我在if循环中返回结果,是不是因为它继续循环而出错?

public static int gcd(int a, int b) {
  int result = 0;
  if(a > b) {
    result = a % b;
  }
  return result;
}

if 循环之外声明结果时错误消失。这是为什么呢?

【问题讨论】:

  • 如果不是循环。这是一个条件。循环是一种结构,它允许您将操作重复多次或所需次数...

标签: java variables methods scope


【解决方案1】:

这与变量result 的作用域有关。当它在 if 内时,当您离开 if})时,它就不再存在了。

public static int gcd(int a, int b){
    int result = 0;
    if (a > b) {
        result = a % b;
    }
    return result;
} // result exists until here

public static int gcd(int a, int b){
    if (a > b) {
        int result = a % b;
    } // result exists until here
    return result; // result doesn't exist in this scope
} 

基本上,您只能访问定义它们的代码块中的变量,代码块由花括号{ ... } 定义。

您的函数的替代实现可以完全不使用该变量。

public static int gcd(int a, int b){
    if (a > b) {
        return a % b;
    }
    return 0;
} 

【讨论】:

  • @user2148463 没问题,请确保通过打勾关闭问题。
  • @Tyriar,在stackoverflow中不叫closure,而是accepting an answer。该问题在得到接受的答案后仍处于未决状态。
【解决方案2】:

局部变量被称为local,因为它们只能在创建它们的中看到。

块是{ ... } 中的任何代码。

让我们看看您在第一个版本中拥有的块:

public static int gcd(int a, int b) { // first block starts here
  if(a>b) { // second block, an inner block, starts here
      int result=a%b;
  } // second block ends here
  return result;
} // first block ends here

因此,您在 second 块中创建一个局部变量,并尝试在该块外部 使用它,即在 first堵塞。这就是编译器所抱怨的。在 second 块完成后,变量 result 消失了。

【讨论】:

  • 但是我正在创建这个变量结果,我只希望它们在 if 循环内。所以我在 if 循环内创建。
  • @user2148463 如果您在 if 循环中创建变量。在该循环之外将无法访问它。
  • 实际上,您确实想要if 块之外,因为您是从if 块之外返回它。换句话说,您从外部块访问它,外部块需要知道变量。
【解决方案3】:

第一个错误的原因是if 语句为变量建立了新的上下文。 result 的声明在 if 的主体之外不可见。

在第二种情况下,if 条件可能无法满足,这种情况下函数将不会执行return 语句。这也是一个错误,因为函数需要为每个执行路径返回一个int(或抛出异常)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2015-08-21
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多