java - 在没有列表/数组的情况下跟踪猜谜游戏中的最低分数 (Java)

标签 java

我陷入了我一直在做的一个简短的程序中。我需要找到一种方法来存储用户多次运行游戏后的最佳分数(最低分数)。这是我的程序的代码-

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成真的机会太小了。

您应该初始化lowScoreInteger.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/

相关文章:

java - 使用 Parse.com 从数据库获取数据以显示在 ListView 中

java - Java 中 PHP 的 gzuncompress 函数?

java - 如何将批处理文件的处理量转换为百分比

java - 中断线程时出现 IllegalMonitorStateException

java - 如何在 Intellij 中运行单个 cucumber 场景?

java - 在 Java 中编译或输出调试代码

java - 在 jdk 1.6 中监视单个捕获中的多个异常

java - 在 Java 中将用户定义的对象添加到 ArrayList

java - 接口(interface)方法引用的注释信息

java - 如何向JComponent添加多个对象?