因此,我正在编写一个简单的游戏,其中计算机猜测您正在考虑的数字在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!");
}
}
有什么想法吗?
答案 0 :(得分:0)
更改是否检查字符串的值是否等于引用而不是引用:
"l".equals(userInput)