在Java中,我可以将变量从一个方法保留到下一个方法,并且跨类吗?
在Java中,我可以将变量从一个方法保留到下一个方法,并且跨类吗?
我试图从命令中获取一个变量,在 QandA 中修改它,并期望它持续存在,直到我再次修改它。
public class Commands
{
int torch = 1;
}
_____________
public class QandA
{
Dostuff d = new Dostuff
Commands a = new Commands();
public void torch
{
System.out.println("Torch = " + torch);
a.torch = 2;
System.out.println("Torch = " + torch);
d.dostuff();
}
public class dostuff
{
public void dostuff()
{
// User imput is gathered here etc etc.
QandA();
}
所以
我期望输出是(一个循环)
Torch = 1
Torch = 2
Torch = 2
Torch = 2
Torch = 2
Torch = 2
经过3个周期。 但它的作用是。
火炬 = 1
火炬 = 2
火炬 = 1
火炬 = 2
火炬 = 1
火炬 = 2
三个周期后。
请帮忙。
In Java can I keep a variable from one method to a next, and across Classes?
I am trying to get a variable from Commands, modify it in QandA and expect it to persist until i modify it again.
public class Commands
{
int torch = 1;
}
_____________
public class QandA
{
Dostuff d = new Dostuff
Commands a = new Commands();
public void torch
{
System.out.println("Torch = " + torch);
a.torch = 2;
System.out.println("Torch = " + torch);
d.dostuff();
}
public class dostuff
{
public void dostuff()
{
// User imput is gathered here etc etc.
QandA();
}
}
So I would expect output to be (a loop of)
Torch = 1
Torch = 2
Torch = 2
Torch = 2
Torch = 2
Torch = 2
After 3 Cycles.
But what it does is.
Torch = 1
Torch = 2
Torch = 1
Torch = 2
Torch = 1
Torch = 2
After three cycles.
Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
持久化数据没有问题,但是您必须注意创建和保存数据的位置。
在您的情况下,您在 Command 类范围内声明“torch”,作为初始化为“1”的 Command 成员(我认为 - 语法有点有趣)。因此,每次声明“new Command()”时,您都会从一个新的“torch”变量 == 1 开始。
您可以将“torch”声明为静态,这意味着它为所有 Command 实例共享,然后它将表现为你想要的,因为每次调用构造函数时它都不会被重置(前提是你没有在构造函数内将其设置为 1)。
There's no problem with persisting data, however you have to be conscious of where you create and save it.
In your case you are declaring "torch" inside the Command class scope, as a member of Command initialized to "1" ( I think - the syntax is a bit funny). Therefore every time you declare "new Command()" you're starting with a new "torch" variable == 1.
You can declare the "torch" as static, meaning it's shared for all Command instances, and then it will behave as you want, as it won't be getting reset every time the constructor is called (provided you're not setting it to 1 inside the constructor).
我不确定您如何引用像
dostuff();
和QandA();
这样的类[这些必须存在编译错误],但请记住仅创建一个 Command 实例并传递相同的实例。在您的情况下,每次创建 QandA 实例时,都会创建一个Command
实例,并将其torch
字段设置为 1I'm not sure how you refer to a class like
dostuff();
andQandA();
[there has to be compilation errors for those] but just keep in mind to create just one Command instance and pass the same instance around. In your case, every time you create an instance of QandA, aCommand
instance is created with it'storch
field set to 1