首页 > 解决方案 > 数字求解游戏不更新随机数上限和下限...Java

问题描述

所以我正在编写一个简单的游戏,计算机会在 1 到 1000 之间猜测你想的一个数字。代码如下,无论我何时运行它,无论我告诉计算机我说的是高还是低,它都不会更新缩小答案的最小值和最大值,你的逻辑对我来说是正确的。:

package com.company;
import java.util.*;



public class Main {

    public static void main(String[] args) {
        //set and initialize variables
        int currentGuess;
        int min = 0;
        int max = 1000;
        boolean guessedCorrectly = false;
        String userInput;
        Random rand = new Random();

        //Create user input object
        Scanner user_input = new Scanner(System.in);

        //Explain Game Rules to User
        System.out.println("Please think of a number and I will try to guess it.");
        System.out.println("You can respond h for higher, l for lower, and c for correct: ");

        //Main Game Loop
        while (guessedCorrectly == false){
            currentGuess = min + rand.nextInt(max - min + 1);
            System.out.print("Is your number " + currentGuess);
            userInput = user_input.next();
            if (userInput == "h"){
                min = currentGuess;
            }else if (userInput =="l"){
                max = currentGuess;
            }else if (userInput == "c"){
                guessedCorrectly = true;
            }else{
                System.out.println("Please enter an h for higher, l for lower, or c for correct ");
            }


        }
        System.out.println("Congratulations to MEEEEEE, I guessed it correctly!");
    }
}

有任何想法吗?

标签: javarandomint

解决方案


更改您的 if 以检查字符串的值是否相等而不是引用:

"l".equals(userInput)

推荐阅读