Java 函数值变量

Java 函数值变量,java,Java,每当我调用函数测试并打印x时,它总是给出5。我需要声明变量x,以便它第一次打印5,然后打印10,然后打印5等什么?变量x是在方法的范围内定义的,因此始终是新创建的,然后被丢弃 public static void test() { int x = 5; x = x + 5; System.out.print(x); } 将变量置于更大的范围内(本例中最简单的方法是将其置于方法之前): 但是: 通常,方法和字段不应该是静态的,除非有充分的理由 您可以将x=x+5缩短为

每当我调用函数测试并打印
x
时,它总是给出
5
。我需要声明变量
x
,以便它第一次打印
5
,然后打印
10
,然后打印
5
等什么?

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

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

    x = x + 5;
    System.out.print(x);
}
将变量置于更大的范围内(本例中最简单的方法是将其置于方法之前):

但是:

  • 通常,方法和字段不应该是静态的,除非有充分的理由
  • 您可以将
    x=x+5
    缩短为
    x+=5
  • 如果您的方法更改了变量
    x
    (该方法的副作用),则至少要为该方法找到一个好的名称

这应该按照你的意愿工作,但是你应该总是考虑如果你真的需要一个可以修改的静态变量。

static int x = 5;

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

你能举个例子清楚地说明你想要什么吗?什么是
main test()
?我猜OP在寻找
静态变量?@UnholySheep,他说他需要输出为
5
10
5
,但不确定他实际上在问什么,实际的代码打印10。你应该结束这篇文章,花时间写一个新问题,好好解释你的问题。@sameerasy哦,我把它误读为
5
10
15
,。。。在这种情况下,真的不清楚问题是关于什么的
static int x = 5;

public static void test() {
    x = x + 5;
    System.out.print(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);
    }
}