Java 生成随机答案的随机数学方程式

Java random math equation generating random answers

我正在编写一个问题,它将是 x(+ 或 - 或 *)y =z,它将为用户生成 4 个可能的答案,其中有 1 个正确答案和 3 个错误答案。我编写了大部分代码,但我不知道如何为 Reponse() 再次使用相同的公式,因为现在当我执行代码时,Equation() 自己创建一个,而 Reponse() 执行另一个不同的公式。此外,我还需要知道如何通过添加一个显示 5 +5 = 这样的公式的系统来确保代码正常工作。 并且代码将显示 4 个答案,其中有一个是好的。

代码如下:

    public class Equation {

    int x, y, z;


    public Equation() {
        Random r = new Random();
        x = r.nextInt(50) + 1;
        y = r.nextInt(50) + 1;
        z = 0;
        char operator = '?';

        switch (r.nextInt(3)) {
            case 0:
                operator = '+';
                z = x + y;
                break;
            case 1:
                operator = '-';
                z = x - y;
                ;
                break;
            case 2:
                operator = '*';
                z = x * y;
                ;
                break;
            default:
                operator = '?';
        }

        System.out.print(x);
        System.out.print(" ");
        System.out.print(operator);
        System.out.print(" ");
        System.out.print(y);
        System.out.print(" = ");
        System.out.println(z);

    }

}

对于 Reponse() 生成答案的那个:

    public class Reponse {
    Equation equ = new Equation();
    int a, b, c, d;
    char operator = '?';

    public Reponse() {
        Random r = new Random();
        switch (r.nextInt(4)) {

            case 0:
                a = r.nextInt(2 * equ.z);
                break;

            case 1:
                b = r.nextInt(2 * equ.z);
                break;

            case 2:
                c = r.nextInt(2 * equ.z);
                break;
            case 3:
                d = equ.z;
                break;
            default:
                operator = '?';
        }
    }
}

这是因为您正在 Response class 中初始化 Equation class 的新实例。

Equation equ = new Equation();

每当你做类似的事情时,

Response r = new Response();

Equation 的新实例将被实例化。

你应该做的如下,

  1. 修改Responseclass如下:

    public class Response {
        int a, b, c, d;
        char operator = '?';
    
        public Response(Equation equ) {
            Random r = new Random();
            switch (r.nextInt(4)) {
    
                case 0:
                    a = r.nextInt(2 * equ.z);
                    break;
    
                case 1:
                    b = r.nextInt(2 * equ.z);
                    break;
    
                case 2:
                    c = r.nextInt(2 * equ.z);
                    break;
                case 3:
                    d = equ.z;
                    break;
                default:
                    operator = '?';
            }
        }
    }
    

注意: 我已经从 class 中删除了 Equation 的实例,并将其传递给构造函数。

  1. 创建Equation的新实例,

    Equation equ = new Equation();
    
  2. 通过传递上面的 Equation 实例,创建 Response 的新实例,

    Response r = new Response(equ);
    

现在,您可以使用实例化的 Equation class 的同一个实例创建 Response class 的多个实例。