2015-10-16 31 views
2

我有以下Java代码。根据返回值递增值

public class Test { 
    public static void main(String[] args) { 
     int i = 5; 
     int j = 0; 
     for (int k = 1; k <= i; k++) { 
      System.out.println("row count is " + j); 
      increment(j); 
      j += 1; 
     } 
    } 

    private static int increment(int j) { 
     if (j == 2) { 
      j += 1; 
      System.out.println("row count is " + j); 
     } 
     return j; 
    } 
} 

这里我想根据返回值增加j的值。

我得到的当前输出是。

row count is 0 
row count is 1 
row count is 2 
row count is 3 
row count is 3 
row count is 4 

我的预期输出是

row count is 0 
row count is 1 
row count is 2 
row count is 3 
row count is 4 
row count is 5 

这里我知道,把

if (j == 2) { 
    j += 1; 
    System.out.println("row count is " + j); 
} 

在我for块解决了这个问题,但是这是一个像我主要的翻版代码以我输入的形式提供。我必须遵循这种模式,我的意思是通过检查我的方法中的条件来增加值。

请让我知道如何得到这个。

谢谢

+2

你确实需要increment'的'的返回值赋给'j' – SomeJavaGuy

回答

4

Java与Pass-By-Value一起工作,您不能只更改方法increment中的参数j以更改main中的原始值。

您需要调用增量并将返回值再次存储到j中。

public static void main(String[] args) { 
    int i = 5; 
    int j = 0; 
    for (int k = 1; k <= i; k++) { 
     System.out.println("row count is " + j); 
     j = increment(j); // IT is important to store it in `j` again, otherwise j will still be 2 after the execution 
     j += 1; 
    } 
} 

private static int increment(int j) { 
    if (j == 2) { 
     j += 1; 
     System.out.println("row count is " + j); 
    } 
    return j; 
} 

如果你想知道为什么是这样的话我倒是推荐将经过this So question

+0

谢谢你,这个工作完美 – user3872094

0

如果你想比较返回值的东西,你首先需要它。

要么做这样的事情:

if (increment(j) == expectedValue) 

或做:

int test = increment(j); 
if(test == expectedValue) 
2

increment功能jj的副本,你的循环(即它是不一样的“对象” ,而且它是原始的),因此如果你在函数中修改了j,它不会在函数外被更新。