gpt4 book ai didi

java - 如何防止连续两次询问相同的乘法数字

转载 作者:行者123 更新时间:2023-12-02 11:55:16 26 4
gpt4 key购买 nike

很抱歉再次打扰您,但我还有一个要添加到此程序的内容。它工作得很好,但是如何才能使它不会连续两次问相同的乘法问题呢?例如,当它询问 1*2 是多少时,它不应该立即再次询问(尽管可能性很小)。

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

public class Main{

public static void main(String[] args) {

boolean correctAnswer;
Random number = new Random();
int nmb1;
int nmb2;
int multi;


while (true) {
nmb1 = number.nextInt(10) + 1;
nmb2 = number.nextInt(10) + 1;
multi = nmb1 * nmb2;

// read the user's input ...
do {
correctAnswer = multiplication(nmb1,nmb2,multi);
}
while (correctAnswer != true);
// .. and repeat until the user types the correct answer

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


public static boolean multiplication(int number1,int number2,int answer)
{

int question;

question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));

if (question != answer) {
JOptionPane.showMessageDialog(null, "Wrong, try again");

return false;
}

return true;

}

}

最佳答案

有很多方法可以做到这一点,在这个例子中,它计算数字对的所有组合,然后对数字对进行混洗,最后询问每个数字对。

public class Main{

public static void main(String[] args) {

boolean correctAnswer;
int nmb1;
int nmb2;
int multi;

// It computes all combinations
List<int[]> asks = new ArrayList<>(100);
for (int i = 1; i < 11; i++) {
for (int j = 1; j < 11; j++) {
asks.add(new int[]{i,j});
}
}

// It shufles
Collections.shuffle(asks);

// It asks for every number pair
for (int[] numbers : asks){ // instead of while(true)
nmb1 = numbers[0];
nmb2 = numbers[1];
multi = nmb1 * nmb2;

// read the user's input ...

...
}

关于java - 如何防止连续两次询问相同的乘法数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com