Java全局变量未在新类中更新 [英] Java global variables not updating in new class
问题描述
我目前正在编写一个简单的Android应用,该应用会询问用户一系列问题,然后告诉他们有多少正确的答案.我有一类具有全局变量(称为分数")的私有类,并且具有该方法的getter和setter方法.当用户获得正确答案时,该类中的分数将(本地)增加并从0更新为1.但是,当我尝试使用创建的getScore()方法访问另一个类中的score值时,它说scores值为0,而不是1. 例如
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.
推荐答案
设置得分,获得得分之前.
public ClassB {
private ClassA eg = new ClassA();
eg.setScore(5);
private int score = eg.getScore();
System.out.println(score);
}
希望这会有所帮助.
这篇关于Java全局变量未在新类中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!