在java中存储数字猜谜游戏的高分问题

4nkexdtk  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(100)

我在存储多个玩家的游戏的最高分时遇到了问题,每个玩家都有不同的名字和分数。不管玩家的分数如何代码输出他们击败了最高分。最大回合数是15。问题似乎是当再次进行完整循环时,high score变量重置,并且不为新玩家保留先前的高分。整个游戏函数在dowhile循环内。

String highScorer = " ";
                int highScore = 15;
                if (score < highScore) {
                    highScorer = name;
                    highScore = score;
                    System.out.println("Congrats! You beat the high score!");
                }
                //output person with high score
                System.out.println("The high score belongs to " + highScorer + " at " + highScore + " tries!");

在循环多个玩家的do while循环时,代码不会一致地存储最高得分

eaf3rand

eaf3rand1#

看起来你在循环中将highScore变量重新初始化为15,这意味着它总是在每次迭代开始时重置为该值。要解决这个问题,你应该在循环之前初始化highScore,然后只有在达到新的高分时才更新它。下面是如何修改代码的一个例子:

int highScore = 15; // Initialize high score outside the loop
String highScorer = " ";

do {
    // Code for playing the game and getting the player's name and score

    if (score < highScore) {
        highScorer = name;
        highScore = score;
        System.out.println("Congrats! You beat the high score!");
    }
} while (/* condition for playing another round */);

// Output person with high score after the loop
System.out.println("The high score belongs to " + highScorer + " at " + highScore + " tries!");

相关问题