【问题标题】:Using declared f variable in a for cycle outside the cycle. Java在循环外的 for 循环中使用声明的 f 变量。爪哇
【发布时间】:2015-08-20 18:17:29
【问题描述】:

问题很简单,答案也可能很简单。假设我开始了一个 for 循环。

for(int yourCont = 0; yourCont < myCont; yourCont++){}

我可以使用整数 yourCount 在 for 循环中执行一些任务。

int theForTask = 2;
for(int yourCont = 0; yourCont < myCont; yourCont++){

    theForTask + yourCont;
}

但如果我在 for 循环键之外使用它...

for(int yourCont = 0; yourCont < myCont; yourCont++){
      //YOUR BEATIFUL CODE
}
    theForTask + yourCont;

它会说没有名为“yourCont”的变量。为什么会这样,我的意思是在 for 循环之外使用 counter 变量是没有意义的,但是在严格的规则中你可以,除非 for 循环被认为是一个类或方法并且你声明的变量是私有的,但我不认为就是这样。所以在简历中:

为什么不能在循环外使用for的计数器变量?

【问题讨论】:

  • 变量是在循环中声明的,因此它的作用域只有循环。你想在循环外使用它吗?在循环外声明它。

标签: java variables for-loop


【解决方案1】:

for 循环中声明的变量的范围仅限于该循环。如果你想在之后使用它,请在循环之外声明它:

int yourCont = 0;
for (; yourCont < myCont; yourCont++) {
    // ...
}

System.out.println(yourCont);

【讨论】:

    【解决方案2】:

    因为您定义变量的方式在 for 循环范围内是本地的。所以一旦你脱离了那个循环,你就什么也得不到了

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多