假设我有一个变量x,在代码运行时会发生变化。我想将x的实际值分配给另一个变量y。如果我只是一直指定它(<form id="customer"><div class="form-group">
<label class="control-label">Full name</label>
<input name="name" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">E-mail</label>
<input name="email" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Mobile</label>
<input name="mobile" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Country</label>
<select id="country" name="country" class="form-control" type="text"><!-- countries ... --></select>
</div></form>
),y的值也会随时间变化。
我也希望能够随时刷新y的值。
int y = x
这将是理想的输出。
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);
答案 0 :(得分:0)
按如下方式创建方法:
int storePrev(int x) {
return x;
}
在更改x的值之前,只需调用此方法即可。这将复制x而不进行分配。
答案 1 :(得分:0)
你所写的实际上是有效的(至少对于原始的)。试着运行以下内容:
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
这不是你想要的吗?
答案 2 :(得分:0)
如果要保留分配给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);