我只是不知道如何创建高分函数。我知道我必须有 2 个值并将它们与 if 语句进行比较并将它们保存在 SharedPreferences 中。我理解共享偏好。我不明白的是如何比较这两个值?
在我的程序中,我有一个名为 Score 的 int。每次我正确回答问题时,它就会像分数++一样增加,并在最后显示已回答的问题编号。假设我又玩了一次,现在得到了一个更大的数字。如果同名分数如何比较?我需要将分数分配给某个新变量吗?如何?我现在感到很愚蠢和尴尬..
代码: 我的分数存储在这里:
public static int scores = 0;
这就是我每次添加 +1 的方式:
if (type.get(count[0])) {
scores++; // Add +1 to the score; ...
我在这里保存我的分数:
protected void score() {
super.onDestroy();
SharedPreferences prefs = getSharedPreferences("level1", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
if(scores > highscore) {
highscore = scores;
prefsEditor.clear();
prefsEditor.putInt("score", scores);
prefsEditor.commit();
}
并在其他 Activity 中显示它,如下所示:
SharedPreferences prefs = getSharedPreferences("level1", Context.MODE_PRIVATE);
int userScore = prefs.getInt("score", 0);
mResult.setText("" + userScore);
最佳答案
每次获得高分时,只需将分数保存在 SharedPreferences
中,然后在启动应用程序时显示该分数:
// when starting the app
public static int userScore = 0;
SharedPreferences prefs = getSharedPreferences("level1", Context.MODE_PRIVATE);
userScore = prefs.getInt("score", 0);
mResult.setText("" + userScore);
public static int scores = 0;
if (type.get(count[0])) {
scores++;
}
if(scores > userScore)
{
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putInt("score", scores);
prefsEditor.commit();
}
关于java - 我无法弄清楚的基本java任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28407945/