[英]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.