Не могу получить результаты от логического, чтобы появиться правильно - PullRequest
0 голосов
/ 24 апреля 2020

Моя программа запрашивает у пользователя число, а затем решает, находится ли число в диапазоне двух случайно сгенерированных чисел или вне его. Все работает нормально, за исключением того, что программа продолжает выдавать результат, что предполагаемое число находится за пределами диапазона, даже если оно находится внутри диапазона. Не уверен, как получить ответ, чтобы показать правильно. Логический результат = 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 Ответ

0 голосов
/ 24 апреля 2020

Ваш 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);
...