如何传递循环中声明的变量的值? [英] How do pass the value of the variable which is declared in the loop?

查看:93
本文介绍了如何传递循环中声明的变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Solution {


  public static int findDifference(int[] input){


      int e=0; int es=0;
          for(int i=0;i<input.length;i+=2)
                {

                   e+=input[i];
                   es=e; // But now after the loop gets terminated the value of es will gets vanishes and the value will get changed to 0. How can i pass the value after the loop?
               }

          int o=0; int os;
          for(int j=1; j<input.length;j+=2)
            {
              os=0;
              o+=input[j];
              os=o; // But now after the loop gets terminated the value of os will gets vanishes and the value will get changed to 0. How can i pass the value after the loop?
            }
      return(es-os);

  }





我的尝试:



输出鞋0作为es和os在循环外声明为0。



What I have tried:

The output shoes 0 as es and os are declared to be 0 outside the loop.

推荐答案

如果变量在循环外定义。我想你的意思是

The value is retained if the variable is defined outside the loop. I suppose you meant
public class Solution
{
  public static int findDifference(int[] input)
  {
      int even_sum = 0;
      int odd_sum = 0;
      for(int i=0;i<input.length;i+=2)
      {
        even_sum +=input[i];
        if ( i+1 >= input.length ) break;
        odd_sum += input[i+1];
      }
      return (even_sum - odd_sum);
  }

  public static void main(String[] args)
  {
    int [] a = new int []{ 1,2,3,4 };
    System.out.printf("The difference is %d\n", findDifference(a));
  }
}


这篇关于如何传递循环中声明的变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆