[英]How can I access a variable from another method in Java?
所以,我试图从计时器任务访问我的变量,但我似乎无法让它工作。 我阅读了有关全局变量的信息,但不太确定如何使用它。 我是 Java 的新手,所以任何建议都会非常有帮助,谢谢!
public boolean verifyAnswer(String userAnswer) {
String correctAnswer = this.questions.get(currentQuestionIndex).correctAnswerText;
if(userAnswer.equals(correctAnswer)) {
timer.pauseTimer();
Timer t = new Timer();
TimerTask tt = new TimerTask() {
//This is the variable I want to use
int score = 0;
@Override
public void run() {
System.out.println(++score);
if (score == 30) {
t.cancel();
}
};
};
t.scheduleAtFixedRate(tt, 0, 1000);
TimerPanel timer2 = new TimerPanel();
long total = 0;
//Here is where I try to use it
long equation = TimerTask.score / 30000;
全局变量可能确实有帮助。 它只是一个在方法外部但在class 内部声明的变量。然后它在整个 class 中可见 - 如果您将其设为public
,则从外部也可见。
你们是在多线程环境中,请以同步方式访问它,像这样
public class Test {
public volatile int global_variable = 42;
public synchronized int getGlobal_variable() {
return global_variable;
}
public synchronized void setGlobal_variable(int global_variable) {
this.global_variable = global_variable;
}
public void update() {
setGlobal_variable(getGlobal_variable() + 150);
}
public Test() {
try {
while (true) {
System.out.println(getGlobal_variable());
update();
Thread.sleep(1000);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
new Test();
}
}
请注意,为了安全起见,我添加了volatile
。 这取决于您的应用程序是否真的需要它。
如果您不关心多线程,只需将score
的声明移到您的方法之外就可以了:-)
最简单的解决方法是使用单元素数组或 holder object 来存储分数,因为匿名内部类无法修改外部变量的值。
int[] score = {0};
TimerTask tt = new TimerTask() {
@Override
public void run() {
System.out.println(++score[0]);
if (score[0] == 30) {
t.cancel();
}
};
};
//...
long equation = score[0] / 30000;
所以,我试图从计时器任务中访问我的变量,但是我似乎无法让它工作。 我阅读了有关全局变量的信息,但不太确定如何使用它。 我是 Java 的新手,所以任何建议都会非常有帮助,谢谢!
public boolean verifyAnswer(String userAnswer) {
String correctAnswer = this.questions.get(currentQuestionIndex).correctAnswerText;
if(userAnswer.equals(correctAnswer)) {
timer.pauseTimer();
Timer t = new Timer();
TimerTask tt = new TimerTask() {
//This is the variable I want to use
int score = 0;
@Override
public void run() {
System.out.println(++score);
if (score == 30) {
t.cancel();
}
};
};
t.scheduleAtFixedRate(tt, 0, 1000);
TimerPanel timer2 = new TimerPanel();
long total = 0;
//Here is where I try to use it
long equation = TimerTask.score / 30000;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.