我被困在一个我一直在努力的短期课程中。我需要找到一种方法来存储用户多次运行游戏后的最高分(最低分)。这是我的程序的代码 -
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);
问题在于我一直在运行这个程序并且得分最高&#34;继续显示0.我试图带我的&#34;如果&#34;在while循环之外的语句,但它继续显示0.任何人都可以帮助我的逻辑?
答案 0 :(得分:1)
count
初始化为0且仅递增,因此除非发生溢出,否则它不会为负。
lowScore
初始化为0且任何非负数都不小于,因此count < lowScore
实现的机会太少。
您应该将lowScore
初始化为Integer.MAX_VALUE
或引入变量以记住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)"));
答案 1 :(得分:1)
您需要将lowScore
初始化为可能的最高整数。尝试
int lowScore = Integer.MAX_VALUE;
然后运行您的程序。干杯!