【问题标题】:Is there a way to get the value out from for loops like this [duplicate]有没有办法从这样的for循环中获取价值[重复]
【发布时间】:2021-02-28 20:52:33
【问题描述】:

如果我正在运行这个 for 循环:

Method[] methods = someClass.getDeclaredMethods();
for(Method method: methods){
         /*code*/
   }

有没有办法让我知道我目前正在进行什么迭代。我需要知道是否找到了某个方法,然后将位置保存在该方法的数组中。

谢谢

【问题讨论】:

  • 找到您想要的变量后,您打算如何处理Method 变量?
  • 如果发现名为setUp的方法应该在程序执行的所有其他调用之前调用该方法。我假设如果我找到它,我可能能够保存该方法?

标签: java swing for-loop


【解决方案1】:

你可以像这样使用计数器:

int counter = 0;
Method[] methods = someClass.getDeclaredMethods();
for(Method method: methods){
    i++;
    /*code*/
}

或者只是使用常规的 for 循环:

Method[] methods = someClass.getDeclaredMethods();
for(int i = 0; i < methods.length; i++) {
    /*code*/
}

在这两个例子中,i 让你知道你是什么迭代。

【讨论】:

    【解决方案2】:

    您可以使用常规循环:

    Method[] methods = someClass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i ++) {
        Method method = methods[i];
        // i contains your position
    }
    

    或者,单独跟踪i

    Method[] methods = someClass.getDeclaredMethods();
    int i = 0;
    for (Method method: methods) {
        // i contains your position
        i ++;
    }
    

    【讨论】:

      【解决方案3】:

      如下更新您的代码,以使用数组长度进行迭代。你会得到索引。

      Method[] methods = someClass.getDeclaredMethods();
      int index = -1;
      for(int i =0; i< methods.length; i++){
          Method currentMethod = methods[i];
          index = i;
               /*code*/
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多