简体   繁体   中英

How can I access a variable from another method in Java?

So, I am trying to access my variable from timer task, however I can't seem to make it work. I read about global variables but wasn't quite sure on how to use it. I am new to Java so any suggestion would be extremely helpful, thank you!

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;

a global variable might indeed help. It is just a variable declared outside the methods but inside the class. Then it is visible in the entire class - and also from outside if you make it public .

of you are in a multithreading environment, please access it in a synchronized way, like so

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();
    }
}

note that I have added the volatile just to be on the safe side. it depends upon your application whether you really need that.

if you are not concerned with multithreading, just move the declaration of score outside your method and you will be fine:-)

The simplest workaround would be to use a single-element array or holder object to store the score as anonymous inner classes cannot modify the value of outer variables.

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;

So, I am trying to access my variable from timer task, however I can't seem to make it work. I read about global variables but wasn't quite sure on how to use it. I am new to Java so any suggestion would be extremely helpful, thank you!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM