Java global variables not updating in new class

2019-09-01 21:10发布

问题:

I am currently programming a simple Android app that asks the user a series of questions and then tells them how many they got correct. I have one class that has a global variable (called "score") that is private and I have getter and setter methods for it. When the user gets the answer correct, the score is incremented (locally) and updates from 0 to 1 in that class. However, when I try to use the getScore() method I have created, to access the value of score in another class, it says scores value is 0, and not 1. E.g.

    public ClassA {
        private int score =  0;

        public void setScore(int s) {
           this.score = s;
        }
        public int getScore() {
           return score;
        }
    }

    public ClassB {
        private ClassA eg = new ClassA();
        private int score = eg.getScore();
    }

I've been stuck on this for a while and really don't know why this isn't working. Help is much appreciated. Thanks.

回答1:

Set the Score, before getting the Score.

public ClassB {
        private ClassA eg = new ClassA();

        eg.setScore(5);
        private int score = eg.getScore();
        System.out.println(score);
    }

Hope this helps.



回答2:

Make sure to actually increment the score in ClassB. Also make score a static variable.



回答3:

Edit your code like this :

   public ClassA {
    private static int score =  0;

    public void setScore(int s) {
       this.score = s;
    }
    public int getScore() {
       return score;
    }
}

public ClassB {
    private ClassA eg = new ClassA();
    int score = 0;
    if(answerCorrect())
    {
         score++;
         eg.setScore(score);
    }
    private int realScore = eg.getScore();
    System.out.print("Final Score : "+realScore);
}

And, create a method answerCorrect() to check whether answer is correct or not, this method will return boolean.



标签: java global