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

标签 java loops infinite

对于我的 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/

相关文章:

ios - UIScrollView - 识别弹跳,改为扩展 contentSize

java - 陷入循环

java - HashMap 和类

python - 我可以重写这段代码以使其运行得更快吗?

java - Java 中的哨兵值

ruby - 为什么我的 ruby 循环没有结束?

c++ - 寻找质数的有效方法

java - 如何使用 get() 方法访问 arrayList 中的元素?

java - 如何使用maven构建一个jar,忽略测试结果?

java - 从 Java 获取当前 AWS Data Pipeline 状态