你如何在Java中从另一个方法中访问一个变量?

huangapple go评论97阅读模式
英文:

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

问题

Sure, here's the translated code:

所以,我试图从定时器任务中访问我的变量,但似乎无法使其工作。我阅读了关于全局变量的资料,但不太确定如何使用它。我是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() {

            // 这是我想要使用的变量
            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;

        // 这里是我尝试使用它的地方
        long equation = tt.score / 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;

答案1

得分: 1

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.

If 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.

英文:

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 你如何在Java中从另一个方法中访问一个变量?

答案2

得分: 1

最简单的解决方法是使用单元素数组或持有对象来存储分数,因为匿名内部类无法修改外部变量的值。

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;
英文:

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;

huangapple
  • 本文由 发表于 2020年8月2日 06:30:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63210654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定