user3872094
user3872094

Reputation: 3351

Increment a value based on return value

I've the below Java code.

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;
    }
}

Here I want to increment the j value based on the return value.

The current output I'm getting is.

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

My expected output is

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

Here I'm aware that putting

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

in my for block solves the problem, but this is a like a replica of my main code which in in the form of my input provided. And I've to follow this pattern, i mean increment the value by checking for the condition in my method.

please let me know how can i get this.

Thanks

Upvotes: 2

Views: 95

Answers (3)

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

Java works with Pass-By-Value, you can´t just change the parameter j in your method increment to change the original value in your main.

you need to call increment and store the return value into j again.

    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;
}

If you want to understand why this was the case i´d recomend to go through this So question

Upvotes: 4

Ga&#235;l J
Ga&#235;l J

Reputation: 15090

The j in your increment function is a copy of the j in your loop (i.e. it's not the same "object", moreover it's a primitive), therefore if you modify j in the function, it does not get updated outside the function.

Upvotes: 2

Stultuske
Stultuske

Reputation: 9437

If you want to compare the returned value to something, you first need to have it.

Either do something like:

if ( increment(j) == expectedValue)

or do:

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

Upvotes: 0

Related Questions