簡體   English   中英

嘗試捕獲循環問題

[英]try catch loop issue

在下面的代碼中,我希望程序通過try catch進行循環,以允許用戶在輸入無效的情況下(例如,用字母代替int)重新輸入答案以進行首次加法。 當前,代碼顯示catch語句,但也繼續執行該程序,並顯示System.out.println("Sorry incorrect, please guess again"); 來自其他我不想要的陳述。 有人可以幫我解決這個問題嗎? 非常感謝!

    public static void add() {

        // Setting up random
        Random random = new Random();

        // Declaring Integers
        int num1;
        int num2;
        int result;
        int input;
        input = 0;
        // Declaring boolean for userAnswer (Defaulted to false)
        boolean correctAnswer = false;
        do {
            // Create two random numbers between 1 and 100
            num1 = random.nextInt(100);
            num1++;
            num2 = random.nextInt(100);
            num2++;

        do{ 
            // Displaying numbers for user and getting user input for answer
            System.out.println("Adding numbers...");
            System.out.printf("What is: %d + %d? Please enter answer below",
                    num1, num2);
            result = num1 + num2;

                try {
                    input = scanner.nextInt();
                } catch (Exception ex) {
                    // Print error message
                    System.out.println("Invalid number entered for addition...");
                    // flush scanner
                    scanner.next();
                    correctAnswer = false;
                }
        }while(correctAnswer=false);

            // Line break for code clarity
            System.out.println();

            // if else statement to determine if answer is correct
            if (result == input) {

                System.out.println("Well done, you guessed corectly!");
                correctAnswer = true;
            } else {

                System.out.println("Sorry incorrect, please guess again");
                correctAnswer=false;
            }
        } while (!correctAnswer);

錯誤在這里:

while(correctAnswer=false)

你需要

while(correctAnswer==false)

您所擁有的是將false分配給correctAnswer一個始終為false的表達式,因此循環永遠不會繼續。 更常見的寫a==false!a ,因此我將循環條件更正為

while(!correctAnswer)

讀起來更“流利”。

當然,現在您需要在循環的頂部設置correctAnswer = true ,以避免無限迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM