我正在尝试制作一个程序,让用户猜测一个随机的#1 - 100,它会告诉他们更高或更低,直到得到它。
这是我到目前为止所拥有的。我不知道该怎么做。 公共课HighLow {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random log = new Random();
//1 - 100
int number = (log.nextInt(100) + 1);
System.out.println("Guess?");
int guess = keyboard.nextInt();
if (guess == number)
{
System.out.println("Congratulations!");
}
while (guess != number)
{
if (guess > number)
{
System.out.println("The number is lower than that.");
guess = keyboard.nextInt();
}
if (guess < number)
{
System.out.println("The number is higher than that.");
guess = keyboard.nextInt();
}
if (guess == number)
{
System.out.println("Congratulations!");
}
}
}//end of main
}//end of class
}//end of class
答案 0 :(得分:0)
您需要一个主循环来检查当前猜测是否正确,以及if语句决定更高位还是更低位。目前,您的两个单独的while循环将无法完成这项工作。
答案 1 :(得分:0)
你不应该有两个循环,而只是一个循环。当猜测等于时,您希望您的游戏停止,因此请将其作为结束条件:
while (guess != number)
然后,在循环中,测试猜测是大于还是小于数字,打印相应的消息,并阅读下一个猜测。如果循环结束,则表示用户找到了该号码。
编辑:为避免重复:
System.out.println("Guess?");
int guess = keyboard.nextInt();
while (guess != number) {
if (guess > number) {
System.out.println("The number is lower than that.");
}
else {
System.out.println("The number is higher than that.");
}
guess = keyboard.nextInt();
}
System.out.println("Congratulations!");