函数值变量

问题描述:

public static void test() { 
    int x = 5; 

    x = x + 5; 
    System.out.print(x); 
} 

每当我打电话功能测试和打印x它总是给5。我需要申报变量x,以便第一次打印5,然后10,然后5等?函数值变量

+1

你能举一个例子来清楚地说明你想要什么吗?什么是'主测试()'? –

+0

这段代码不会编译'public static void main test()' – developer

+1

我的猜测是OP会寻找'static'变量吗? – UnholySheep

变量x在该方法的范围内定义,因此将始终是新创建的,随后将被丢弃。

public static void test() { 
    int x = 5; 

    x = x + 5; 
    System.out.print(x); 
} 

把变量在一个更大的范围内(最简单的在这个例子中是把它的方法之前):

static int x = 5; 

public static void test() { 
    x = x + 5; 
    System.out.print(x); 
} 

BUT:

  • 一般方法和字段不应该static,除非有充分的理由。
  • 可以缩短x = x + 5x += 5
  • 如果你的方法改变了可变x(一侧的方法的效果),至少比找到一个方法,一个好名字。

这应该像你打算的那样工作,但是你应该总是考虑如果你真的需要需要一个可以修改的静态变量。

public class DemoClass { 
    // this variable exists only once, all objects of this class share it 
    // keep that in mind when creating multiple objects of this class and calling test() on them! 
    static int x = 5; 

    public static void test() { 
     // check if we need to add to or subtract from x 
     if (x > 5) { 
      x -= 5; 
     } else { 
      x += 5; 
     } 

     System.out.println(x); 
    } 
}