Closed. This question is not reproducible or was caused by typos。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                    
                
        

我有以下代码:

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

最佳答案

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

someStaticVariable = obj.someInstanceMethod();


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

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

09-28 14:24