java - 如何修复 boolean 方法中的返回错误

标签 java methods boolean

我正在创建一个程序,要求用户猜测数字。然后程序确定猜测的数字是否在两个随机数的范围内。我有一个公共(public)静态 boolean 值,即使我有返回值(在 if 和 else if 内),它也会显示错误。刚接触方法,不确定如何解决,我该如何解决这个问题?请注意,我无法创建第二个 boolean 值,两个验证都必须保留在 displayGuessResults 中,因为这是程序所需要的。另外,代码不完整,因为我还没有完成对 main 的调用,我只是想在继续之前解决这个问题,谢谢!

代码(不包括 main,因为我还没有任何内容):

public static int getValidGuess(Scanner get)
    {
       int num;

        System.out.print("Guess a number: --> ");
        num = get.nextInt();

        return num;
    } // getValidGuess end

    public static boolean displayGuessResults(int start, int end, int num)
    {
         int n1, n2;
         Random gen = new Random();

        n1 = gen.nextInt(99) + 1;
        n2 = gen.nextInt(99) + 1;



        if(n1 < n2)
        {
            start = n1;
            end = n2;
        } // if end
        else
        {
            start = n2;
            end = n1;
        } //else end

        if(num > start && num < end)
        {
            System.out.println("\nThe 2 random numbers are " + start +
                    " and " + end);
            System.out.println("Good Guess!");

            return true;
        }
        else if (num < start || num > end)
        {
            System.out.println("\nThe 2 random numbers are " + start +
                    " and " + end);
            System.out.println("Outside range.");

            return false;
        }


    } // displayGuessResults end

最佳答案

如果 num == start || 会怎样?数==结束?你还没有考虑过它,因此对于这种情况,它不会进入 if/else if 。因此你也需要处理它

关于java - 如何修复 boolean 方法中的返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61380209/

相关文章:

运算符中的 Python 不工作

java - Spring 安全与我自己的 table

Java,java.lang.reflect.InvocationTargetException 与 Digester 解析器

java - 使用 Chef 安装 Tomcat-8

java - HTTPS 连接错误

java - Java方法如何使用谁将它们传递给它们

c# - 在另一个函数中调用返回 boolean 值的函数

boolean - TCL中的求反运算

c++ - 在C++中,(void)在参数中有什么作用?

c# - 如何在 C# 中访问 protected 方法