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

时间:2017-12-05 11:15:44

标签: java random

很抱歉再次打扰你,但我还有一个补充来加入这个程序。它工作正常,但它怎么能这样做,所以它不会连续两次问同一个乘法问题?例如,当它询问什么是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;

  }

}

1 个答案:

答案 0 :(得分:1)

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

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 ...

            ...
        }