Java global variables not updating in new class

牧云@^-^@ 提交于 2019-12-12 04:35:32

问题


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.



来源:https://stackoverflow.com/questions/18239476/java-global-variables-not-updating-in-new-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!