gpt4 book ai didi

java - return 语句后出现意外输出

转载 作者:行者123 更新时间:2023-12-01 18:31:06 26 4
gpt4 key购买 nike

我有以下代码:

public class MainClass {

static int someStaticVariable = 0;

public static void main(String[] args) {

MainClass obj = new MainClass();
obj.someInstanceMethod();
System.out.println("Count in main method " + someStaticVariable);
}

public int someInstanceMethod() {

String someString = "line1\nline2\n";

System.out.println("Count in someInstanceMethod method "
+ (someStaticVariable + someString.split("\r\n|\r|\n").length));

return (someStaticVariable + someString.split("\r\n|\r|\n").length);

}
}

问题:为什么输出是:

Count in someInstanceMethod method 2
Count in main method 0

而不是

Count in someInstanceMethod method 2
Count in main method 2

以及为什么它打印出 Count in someInstanceMethod method 2在 someInstanceMethod 中并返回 0然后打印0在主方法中。

最佳答案

您没有为 someStaticVariable 分配任何内容;您忽略了 someInstanceMethod 的返回。尝试一下

someStaticVariable = obj.someInstanceMethod();

或者,您可以在方法本身中分配它。

someStaticVariable += someString.split("\r\n|\r|\n").length;
return (someStaticVariable + someString.split("\r\n|\r|\n").length);

关于java - return 语句后出现意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24188782/

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