简体   繁体   中英

Java functions by passing parameters

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+" ");
    }
}

I get infinite loop of 0

Need output: 0 2 4 6

You are getting infinite loop because you called bump() without storing it

To fix this problem you need to replace x value with the returned value of bump() .

for(int x = 0 ; x < 5 ; x = bump(x))  
    System.out.print(x+" ");
}

If you want to get 0 2 4 6 as the output, this should do it.

for (int x = 0; x <= 6; x=bump(x))
            System.out.print(x + " ");

The last section of the for() loop is the step section. That's where you should update your loop variable. In your case, you should update the x variable like this:

static int bump(int i) { 
    return i+2; 
}

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

I am not sure where you got this idea of using a function to update the loop variable, but this is not very common. You may consider just getting rid of the bump() function and make the step section readable and clear, like this:

for (int x = 0; x < 5; x += 2)  
    System.out.print(x + " ");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM