我正在用Java编写一个程序,用户被问到乘法问题,例如&#34;什么是3 * 8&#34;。目前,无论用户输入正确还是错误的答案,程序都会在其后面询问一个新问题,我想知道如何制作它,以便在用户输入正确答案之前不断询问相同的问题:< / p>
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所以它并没有真正帮助。
答案 0 :(得分:0)
只需添加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");
}
}
}