java - 数字求解游戏不更新随机数上限和下限...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!");
}
}
有任何想法吗?
解决方案
更改您的 if 以检查字符串的值是否相等而不是引用:
"l".equals(userInput)
推荐阅读
- jsonpath - JsonPath:过滤后获取父元素
- google-chrome - 在未跨步骤共享的云构建步骤中安装 google-chrome(使用卷)
- c++ - gcc 对 abs 函数的奇怪行为
- typescript - PowerBi-Javascript 报告嵌入集群详细信息 403 错误
- android - 添加firebase-auth插件时cordova android构建失败
- getter-setter - Getter 和 Setter 的使用
- php - 对学说查询生成器的误解
- php - 在 Symfony 3.4 中使用这样的服务是否正确?
- java - Elasticsearch:按字母顺序排序,忽略数字和特殊字符
- python - 从另一个目录调用 python setup.py install