【发布时间】:2019-03-12 17:58:18
【问题描述】:
所以我正在编写一个简单的游戏,计算机会在 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!");
}
}
有什么想法吗?
【问题讨论】: