【问题标题】:Can't get results from boolean to appear correctly无法从布尔值中获得正确显示的结果
【发布时间】:2020-08-07 08:46:20
【问题描述】:

我的程序要求用户输入一个数字,然后决定该数字是在两个随机生成的数字的范围之间还是在它之外。一切正常,除了程序不断给出猜测数字超出范围的结果,即使它在范围内也是如此。不知道如何让答案正确显示。 Boolean result = 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

【问题讨论】:

  • 似乎你没有处理 num==start 或 num == end; 的情况那你悄悄回true

标签: java methods boolean


【解决方案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);

【讨论】:

    猜你喜欢
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 2012-03-24
    • 1970-01-01
    • 2011-04-25
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多