我陷入了我一直在做的一个简短的程序中。我需要找到一种方法来存储用户多次运行游戏后的最佳分数(最低分数)。这是我的程序的代码-
import java.util.*;
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args){
Random rand = new Random();
Scanner prompt = new Scanner(System.in);
String play = "";
boolean playAgain = true;
int playTimes = 0;
int lowScore = 0;
int count = 0;
do{
int target = rand.nextInt(100) + 1;
System.out.print("\nEnter a number between 1 and 100: ");
int guess = prompt.nextInt();
while(guess != target){
if(target > guess){
System.out.println("The number is higher. Try again.");
count++;
}
else{
System.out.println("The number is lower. Try again.");
count++;
}
System.out.print("Enter a number between 1 and 100: ");
guess = prompt.nextInt();
}
System.out.println("You guessed correctly! Congratulations!");
count++;
System.out.println("Your score is: " + count);
System.out.print("\nWould you like to play again? Yes or no?: ");
play = prompt.next();
if(play.equalsIgnoreCase("no")){
playAgain = false;
}
else if(play.equalsIgnoreCase("yes")){
count = 0;
playAgain = true;
}
playTimes++;
if(count < lowScore){
lowScore = count;
}
}while(playAgain);
System.out.println("\nGame Summary");
System.out.print(" Games played: " + playTimes);
System.out.println("\n Best Score: " +lowScore);
问题是我一直在运行这个程序,并且“最佳分数”一直显示 0。我尝试将“if”语句放在 while 循环之外,但它继续显示 0。任何人都可以帮忙吗?我的逻辑?
最佳答案
count
初始化为0,并且只递增,所以除非发生溢出,否则不会为负数。
lowScore
初始化为0并且任何非负数不小于,所以count < lowScore
成真的机会太小了。
您应该初始化lowScore
至Integer.MAX_VALUE
或者引入一个变量来记住 if lowScore
有这样的有效分数:
int lowScore = 0;
int count = 0;
boolean isLowScoreValid = false; // the variable
if(!isLowScoreValid || count < lowScore){ // update if any value were't set
lowScore = count;
isLowScoreValid = true; // now a value is set
}
System.out.println("\n Best Score: " +(isLowScoreValid ? lowScore : "(none)"));
关于java - 在没有列表/数组的情况下跟踪猜谜游戏中的最低分数 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025864/