我有以下代码:
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
以及为什么它会在someInstanceMethod中打印到Count in someInstanceMethod method 2
并返回0
然后在main方法中打印0
。
答案 0 :(得分:2)
您没有为someStaticVariable
分配任何内容;你忽略了someInstanceMethod
的回归。尝试
someStaticVariable = obj.someInstanceMethod();
或者,您可以在方法本身中分配它。
someStaticVariable += someString.split("\r\n|\r|\n").length;
return (someStaticVariable + someString.split("\r\n|\r|\n").length);
答案 1 :(得分:2)
问题在于您不会篡改someStaticVariable
。
您只需打印出someStaticVariable
(即0)和someString.split("\r\n|\r|\n").length
您需要做的是分配:
someStaticVariable = obj.someInstanceMethod();