我有代码应该猜测用户的号码,它会根据用户输入缩小搜索范围。唯一的问题是,在 while 循环中,条件语句不适用于 .equals。相反,即使我输入“小于”,它也会跳到其他。这是我的代码,我是java新手,所以我可能犯了一个错误。
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
最佳答案
有两个地方有问题:
- 第一个 sc.nextInt() 方法 - 仅读取 int value by 将当前读取缓冲区保持在同一行。所以为了 忽略/跳过输入行中 int 之后的所有内容(即 可能是\n 或\r\n 如果你只输入数字)你必须 使用sc.nextLine()。
- 第二个是 sc.next() 方法 - 其中 只读取行中的第一个标记(或简单的单词)。那是 可能为什么你只得到分配给响应的“更少”值 并且永远不会.等于到“小于”。所以你会 必须将 sc.next() 替换为 sc.nextLine() 并删除 下一行中不必要的 sc.nextLine() 。
希望现在应该清楚了,并且您可以更好地理解调用这些函数时会发生什么。如果没有,那么我强烈建议您查看 Scanner 类,请阅读 JavaDocs围绕它编写多个测试,以更好地了解正在发生的事情。
如果我的解释仍然不清楚,请查看下面我为您修改的代码:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
关于java - Equals 函数在 While 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52896218/