【问题标题】:Capture the value of a variable that changes through time捕获随时间变化的变量的值
【发布时间】:2017-03-19 15:53:52
【问题描述】:

假设我有一个变量 x 在代码运行时会发生变化。我想将 x 的实际值分配给另一个变量 y。如果我像往常一样分配它(int y = x),y 的值也会随着时间而变化。 我还希望能够随时刷新 y 的值。

int y = x; //let's assume this actually works
System.out.println("y="+y+" x="+x);
Thread.sleep(2000);
System.out.println("later");
System.out.println("y="+y+" x="+x);
y = x;
System.out.println("refresh");
System.out.println("y="+y+" x="+x);

这将是理想的输出。

y=20 x=20
later
y=20 x=423
refresh
y=423 x=423

【问题讨论】:

  • 我不完全确定您在寻找什么。也许是观察者模式?
  • y = x 捕获它,因此,如果您只执行一次,在 x 具有您想要捕获的值的时间点,您就完成了。

标签: java variables


【解决方案1】:

创建方法如下:

int storePrev(int x) {
     return x;
}

只需在更改 x 的值之前调用此方法。这将复制 x 而不分配。

【讨论】:

    【解决方案2】:

    您所写的内容实际上是有效的(至少对于原始的)。只需尝试运行以下命令:

    public static void main(String[] args) throws IOException, InterruptedException {
        int x = 20;
        int y = x; //let's just see if it actually works
        System.out.println("y="+y+" x="+x);
        Thread.sleep(2000);
        x += 403;
        System.out.println("later");
        System.out.println("y="+y+" x="+x);
        y = x;
        System.out.println("refresh");
        System.out.println("y="+y+" x="+x);
    }
    

    这打印了我:

    y=20 x=20
    later
    y=20 x=423
    refresh
    y=423 x=423
    

    这不是你想要的吗?

    【讨论】:

    • 我认为我的问题是我试图比较这两个变量。在我的代码中某处有这样的:if(y==x) { //do something } 它从不进入 if,我知道这是因为 y 获取 x 的值来检查条件,就像写 if(x==x)。我试图将 x 的值复制到 y。
    【解决方案3】:

    如果您想记录分配给 y 的所有值,那么您可以简单地创建一个数组。 示例:

    i=0;
    i++; 
    int y[i] = x; 
    System.out.println("y="+y+" x="+x);// here you can simply print the y[i] you want
    Thread.sleep(2000);
    System.out.println("later");
    System.out.println("y="+y+" x="+x);// here you can simply print the y[i] you want
    i++
    y[i] = x;
    System.out.println("refresh"); 
    System.out.println("y="+y+" x="+x);// here you can simply print the y[i] you want
    

    如果您只想保留之前的 x,那么您只需在 y=x 语句之后更改 x 的值即可。示例:

    int x=20; 
    int y = x; // y becomes 20
    System.out.println("y="+y+" x="+x);
    Thread.sleep(2000); //suppose x becomes 423
    System.out.println("later"); 
    System.out.println("y="+y+" x="+x);
    y = x; // y also becomes 423
    System.out.println("refresh");
    System.out.println("y="+y+" x="+x);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多