gpt4 book ai didi

java - 随机#猜谜游戏无限循环

转载 作者:行者123 更新时间:2023-12-01 18:08:20 27 4
gpt4 key购买 nike

对于我的 Java 类(class),我应该制作一个随机猜数字游戏。我一直陷入过去几天创建的循环中。程序的输出总是无限循环,我不明白为什么。非常感谢任何帮助。

/*
This program will generate a random number.
It will ask the user to guess what number was generated and say
if the guess is too high or low.

*/

import java.util.Scanner;

import java.util.Random;

public class RandomNumGame {
public static void main(String[] args) {


Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();

while(success == 0)
{

if(userGuess > randNum){
System.out.println("Too high");
}
else if(userGuess < randNum){
System.out.println("Too high");
}
else{
System.out.println("Something is very wrong.");
}

}
if(userGuess == randNum){
success++;
System.out.println("You got it! Play again?");
}

}
}

最佳答案

您将检查输入是否等于 while 之外的数字的 if 放在一起,因此循环永远不会结束。

这是修复的代码:

import java.util.Scanner;
import java.util.Random;

public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();

while(success == 0) {
if(userGuess > randNum) {
System.out.println("Too high");
} else if(userGuess < randNum) {
System.out.println("Too high");
} else if(userGuess == randNum) {
success++;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}

关于java - 随机#猜谜游戏无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60515771/

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