【问题标题】:How can I access a variable from another method in Java?如何从 Java 中的另一种方法访问变量?
【发布时间】:2020-08-01 22:30:04
【问题描述】:

所以,我试图从计时器任务中访问我的变量,但是我似乎无法让它工作。我阅读了有关全局变量的信息,但不太确定如何使用它。我是 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;

【问题讨论】:

    标签: java variables global-variables local-variables


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      全局变量可能确实有帮助。它只是一个在方法外部但在类内部声明的变量。然后它在整个班级都可见 - 如果您将其设为 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 的声明移出您的方法就可以了 :-)

      【讨论】:

        猜你喜欢
        • 2019-07-31
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        • 2021-08-11
        • 1970-01-01
        • 2015-12-20
        • 1970-01-01
        • 2014-09-14
        相关资源
        最近更新 更多