簡體   English   中英

Java乘法測驗,如果答案錯誤,如何循環

[英]Java multiplication quiz, how to loop if the answer is wrong

我正在用Java編寫一個程序,向用戶詢問乘法問題,例如“什么是3 * 8”。 當前,無論用戶輸入的答案是對還是錯,程序都會在問一個新問題之后問我,我想知道如何制作它,這樣它會一直問同樣的問題,直到用戶輸入正確的答案為止:

import javax.swing.JOptionPane;

import java.util.Random;

public class Multi {

    public static void main(String[] args) {

        Random number = new Random();

        while (true) {

            int nmb1 = number.nextInt(10) + 1;
            int nmb2 = number.nextInt(10) + 1;
            int multi = nmb1 * nmb2;

            int question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

            if (question == multi) {
                JOptionPane.showMessageDialog(null, "Right");
            } else {
                JOptionPane.showMessageDialog(null, "Wrong, try again");
            }
        }
    }

}

我認為我需要在其他部分添加一些內容,但我不知道是什么。 我看過類似的問題,但是那些問題沒有使用JOptionPane,因此它並沒有真正的幫助。

只需添加do...while塊即可重復相同的問題/答案循環,直到用戶鍵入正確的答案為止:

import java.util.Random;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {

        Random number = new Random();

        while (true) {

            int nmb1 = number.nextInt(10) + 1;
            int nmb2 = number.nextInt(10) + 1;
            int multi = nmb1 * nmb2;
            int question;

            // read the user's input ...
            do {
                question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

                if (question != multi) {
                    JOptionPane.showMessageDialog(null, "Wrong, try again");
                }
            }
            while (question != multi);
            // .. and repeat until the user types the correct answer

            JOptionPane.showMessageDialog(null, "Right");
        }
    }
}

暫無
暫無

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

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