gpt4 book ai didi

java - 根据返回值增加一个值

转载 作者:行者123 更新时间:2023-12-01 22:10:39 25 4
gpt4 key购买 nike

我有以下 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 block 中解决了问题,但这就像我的主代码的副本,以我提供的输入的形式出现。我必须遵循这种模式,我的意思是通过检查我的方法中的条件来增加值。

请告诉我如何获得这个。

谢谢

最佳答案

Java 使用按值传递,您不能仅更改方法increment 中的参数j 来更改原始值main 中的值。

需要再次调用increment并将返回值存入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

关于java - 根据返回值增加一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33164715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com