【问题标题】:Why result of the addition not captured in iteration?为什么在迭代中没有捕获加法的结果?
【发布时间】:2013-12-22 14:14:33
【问题描述】:

在给定的代码中,为什么 迭代中没有捕获加法?为什么 x 的值永远不会改变?

public class Fortran {
    static int bump(int i) { return i + 2; }
    public static void main(String[] args) {
        for(int x = 0; x < 5; bump(x))
        System.out.print(x + " ");
    } 
}

【问题讨论】:

  • 将 for 语句的最后一行更改为 x =bump(x)。你没有捕捉到结果。

标签: java for-loop iteration


【解决方案1】:
  1. Java 通过复制传递值,所以bump 只获得x 的副本

  2. bump 返回的值永远不会分配给x(也许你忘记了x =)。

不妨试试

for(int x = 0; x < 5; x = bump(x))

【讨论】:

    【解决方案2】:

    这只是因为从未分配过您的新值。 正确的做法是更多。

    for(int x=0;x<5;x+=2)
    {
        //do whatever you want
    }
    

    注意:x+=2 是 x=x+2 的简写

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2021-04-30
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      相关资源
      最近更新 更多