gpt4 book ai didi

java - 随机数猜谜游戏的逻辑错误

转载 作者:行者123 更新时间:2023-12-02 05:57:37 26 4
gpt4 key购买 nike

在此程序中,计算机生成一个随机数(1-100 之间),然后用户尝试猜测它。运行直到用户正确猜出数字。需要打印出在正确猜出数字之前所进行的总尝试次数。程序运行正常,但存在逻辑错误。当我正确猜出数字时,什么也没有打印出来;程序只是停止了。

import java.util.*;
public class Problem3 {


public static void main(String[] args) {

Random rand = new Random();
Scanner console = new Scanner(System.in);

int num = rand.nextInt(100)+1;
System.out.println(num); //prints out the random number so I know test works correctly
int count = 0;
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
console = new Scanner(System.in);
int guess = console.nextInt();
while(guess != num){ //while guess is not = to number
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else if( guess > num){ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{
count++;
System.out.println("You guessed correctly after " + count + " tries!");
}
}
}

}

最佳答案

实际上你永远不会进入else阶段,因为当猜出数字时,while代码不会执行,因此else代码永远不会执行。因此,在猜测数字之后,条件为 false,退出 while 循环和 System.out.print Congrats 消息

将其放在 while 循环之外“最后”:

 System.out.println("You guessed correctly after " + count + " tries!");

您的代码应如下所示:

while(guess != num){  //while guess is not = to number  
if(guess < num){ //if less than num
System.out.println("Your guess is too low");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}else{ //if greater than num
System.out.println("Your guess is too high");
System.out.println("Guess the random number. The number is between 1 and 100. Enter it below");
guess = console.nextInt();
count++;
}
}

System.out.println("You guessed correctly after " + ++count + " tries!");

关于java - 随机数猜谜游戏的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22950351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com