Search code examples
javamathoperatorsgenerate

Math created x + y = z function generate answers


I have a project where I made an x + y = z or - , * operator generated function, but I do not get it how can I make another class where it will generate different answers and the user has to find the right one.

Exemple: 2*2 = z

A) 2

B) 5

C) 6

D) 4

Here's the code of what I did already:

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);


    }
    public static void main(String[] args) {
        Equation eq= new Equation();
        String param = null;




    }

}

Yet I do not ask for a code already made but indications.

Thank you.


Solution

  • You ask, "how I can make another class where it will generate different answers and the user has to find the right one." One way to do that is to take the correct value, z, and generate random values which are different, and then output all the values, correct and incorrect.

    Something like:

    incorrect = r.nextInt(2*z);
    

    which generates a value in the range from 0 to 2*z. You will need to ensure that the incorrect values are all different from each other, and all different from z.