有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法从布尔值中获得正确显示的结果

我的程序要求用户输入一个数字,然后决定该数字是在两个随机生成的数字范围内还是超出范围。一切正常,只是程序不断给出猜测的数字超出范围的结果,即使在范围内也是如此。不确定如何正确显示答案。布尔结果=true存在,因为如果不存在,则会出现“找不到符号”错误

代码:

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;
         boolean result = true;

         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){
             result = true;
            System.out.println("\nThe 2 random numbers are " + start +
                    " and " + end);
            System.out.println("Good Guess!");
        } //if end
        if(num < start || num > end){
            result = false;
            System.out.println("\nThe 2 random numbers are " + start +
                    " and " + end);
            System.out.println("Outside range.");
         } //if end



        return result;


    } // displayGuessResults end

    public static void main(String[] args) {
        // start code here
       int start = 0, end = 0, num = 0, input;
       Scanner scan = new Scanner(System.in);
       String doAgain = "Yes";


        while (doAgain.equalsIgnoreCase("YES")) {
            // call method
            input = getValidGuess(scan); 
            displayGuessResults(start, end, num);
            System.out.print("\nEnter YES to repeat --> ");
            doAgain = scan.next();
        } //end while loop

    } //main end

共 (1) 个答案

  1. # 1 楼答案

    你的displayGuessResult应该改进:

    public static boolean displayGuessResults(int num) {
        boolean result = true;
    
        Random gen = new Random();
    
        int n1 = gen.nextInt(99) + 1;
        int n2 = gen.nextInt(99) + 1;
        int start = Math.min(n1, n2);
        int end   = Math.max(n1, n2);
    
        System.out.println("\nThe 2 random numbers are " + start + " and " + end);
        if(num >= start && num <= end){
            result = true;
            System.out.println("Good Guess!");
        } else {
            result = false;
            System.out.println("Outside range.");
        }
        return result;
    } // displayGuessResults end
    

    你必须使用input从扫描仪读取来调用它:

        input = getValidGuess(scan); 
        displayGuessResults(input);