2013-08-16 63 views
-3

我认为这可能是一个直截了当的问题,但我有一个类有一个私人静态int变量,在类中增加,我想显示在一个值第二课。但是,即使它已经增加,它仍然保持打印输出0。从不同的类调用java中的私有静态变量

相同的代码将是

public class Test{ 

     private static int toIncrement; 

     public static int returnValue{ 
      return toIncrement; 
     } 

     public void test{ 
     for(int i = 0; i < 4; i++){ 
       toIncrement++; 
     } 
     } 
} 

所以上面的代码运行,然后从另一个类我请Test.returnValue(); 和这个返回0

+0

@HovercraftFullOfEels这一切都在那里。 – hexafraction

+2

@hexafraction:啊上面的代码甚至没有编译。对原始海报:请不要浪费时间发布“垃圾”代码供我们审阅。如果您遇到严重问题并希望获得认真帮助,请仅发布* real *代码。 –

+0

你的班级如何编译。 – Jayamohan

回答

0

所以上面的代码运行,然后从另一个类我请 Test.returnValue();并返回0

当你说上面的代码运行,并不意味着你的test方法将自动执行,而不从任何地方调用。如果您先拨打test方法,然后尝试获取Test.returnValue(),则该值不应为0.

0

感叹。我从哪开始呢?

public void test{ 
    for(int i = 0; i < 4; i++){ 
     toIncrement++; 
    } 
} 

这不是一个构造函数。这将需要void删除。由于缺乏括号,这甚至不适用。

public static int returnValue{ 
    return toIncrement; 
} 

再次括号。

private static int toIncrement; 

public static int returnValue{ 
    return toIncrement; 
} 

这是真的意味着是静态的吗?请将其设置为静态,并调用Test.test()或使其成为非静态并正确调用构造函数。

+0

*“即使是这样,它将是无用的,因为'增量'是静态的,它会破坏。”*它不会中断。静态变量可以用在非静态的上下文中(只有反过来是不真实的)。 – arshajii

+0

@arshajii谢谢,我总是很困惑2,尽管现在看起来很直观。 – hexafraction

0

您忘记了方法中的参数括号。 应该是:

public class Test{ 

    private static int toIncrement; 

    public static int returnValue(){ 
    return toIncrement; 
    } 

    public void test(){ 
    for(int i = 0; i < 4; i++){ 
     toIncrement++; 
    } 
} 

但看到你不()任何地方调用测试中,我假设你认为这是一个构造函数。为了使构造删除“作废” 所以它只是:

public test() 
{ 
    code here 
} 

当你做到这一点,因为你运行程序(只要这是你的主类的代码会自动运行,如果不是你需要为构造函数创建一个实例来运行。)

0

使用静态块!

public class Test{ 

     private static int toIncrement; 

     public static int returnValue(){ 
      return toIncrement; 
     } 

     static { 
     for(int i = 0; i < 4; i++){ 
       toIncrement++; 
     } 
     } 
}