我有下面的类(Java,我不是Java程序员...我是老PLC程序员!):
public class Valor {
public double variavel;
public Valor(double v1){
this.variavel=v1;
System.out.println("Test" + " " + this.variavel);
} }
此变量v1来自另一个类。.我现在想在另一个类中使用此(this.varavel)v1(用@@标记):
public class RandomWalk implements Runnable
{
public void run()
{
long currentTime = 0;
long nextTime = 0;
Random rand = new Random(50);
double series0 = 32;
double series1 = 63;
double upperLimit = 94;
double scaleFactor = Math.sqrt(interval * 0.1);
// Variables to keep track of the timing
long timer = System.nanoTime();
while (!stopThread)
{
// Compute the next data value
currentTime = (System.nanoTime() - timer) / 1000000;
double p = currentTime / 1000.0 * 4;
series0 = 20 + Math.cos(p * 2.2) * 10 + 1 / (Math.cos(p) * Math.cos(p) + 0.01);
series1 = **@@Valor.variavel;**
} }}
我不确定语法和结构是否正确... 在程序的此部分中(System.out.println(“ Test” +“” + this.variavel);) 我具有该变量的实际值,但是当我在另一个类/方法中调用该变量时(公共类RandomWalk实现Runnable {public void run())
我有series1 = 0(此变量始终为= 0)。 我真的不知道该如何访问此变量。。。如果您能帮助我,并且要具体一点,我会很无聊!
非常感谢!
答案 0 :(得分:0)
为了访问另一个类中的变量,您必须执行以下两项操作之一:创建新的Valor实例并将其存储为RandomWalk内的变量,或将variavel转换为静态变量。在您当前的Valor实现中,我建议将variavel转换为静态变量。
要将variavel变成静态变量,您只需要在variavel的声明中的public和double之间添加“ static”即可。但是,您将不再能够使用Valor的类构造函数来设置variavel,并且代码看起来像这样。
public class RandomWalk implements Runnable {
public void run() {
long currentTime = 0;
long nextTime = 0;
Random rand = new Random(50);
double series0 = 32;
double series1 = 63;
double upperLimit = 94;
double scaleFactor = Math.sqrt(interval * 0.1);
Valor valorVariavel = new Valor(0/*or whatever value you want variavel to be*/);
// Variables to keep track of the timing
long timer = System.nanoTime();
while (!stopThread) {
// Compute the next data value
currentTime = (System.nanoTime() - timer) / 1000000;
double p = currentTime / 1000.0 * 4;
series0 = 20 + Math.cos(p * 2.2) * 10 + 1 / (Math.cos(p) * Math.cos(p) + 0.01);
series1 = valorVariavel.variavel;
}
}
}
然后,您可以保持RandomWalk不变。
但是,如果您希望拥有Valor的多个实例,则可以将Valor保持其当前状态,而改为更改RandomWalk以创建Valor的实例,然后访问该实例内部的变量variavel,使RandomWalk看起来像这样< / p>
{{1}}