a7omiton
a7omiton

Reputation: 1617

Using random operators

I'm making an android maths game which gives users the some questions to answer with random numbers, and just to make it perfect I want to try and use random operators i.e. add/sub/multi/divide

So far I have the semi-random equation method:

public void easyGame(){
    Random rand = new Random();
    final int a = (int) rand.nextInt(50)+1;
    final int b = (int) rand.nextInt(50)+1;
    final int c = (int) rand.nextInt(10)+1;
    String aString = Integer.toString(a);
    String bString = Integer.toString(b);
    String cString = Integer.toString(c);
    String display = aString + " + " + bString + " - " + cString + " =";
    questionLabel.setText(display);
    c1 = a + b - c;
}

This gives me random numbers, stored in c1 which is a static int, and compared with user input later on in the code.

I've seen how random operators are made using arrays and stuff, but I don't know/understand how to use them in the c1 = a + b - c; statement, i.e. how do you replace it with the + and - operations.

Please let me know if you know. Thank you

Upvotes: 0

Views: 2112

Answers (1)

zapl
zapl

Reputation: 63955

You can use random numbers to do anything you want with them. For example this (very incomplete) example should give you an idea how you can randomize the operators too.

int operator1 =  (int) rand.nextInt(4);
// ...
char op;
switch(operator1) {
   case 0: op = '+'; break;
   case 1: op = '-'; break;
   // ...
}
String display = aString + op + ...
c1 = a;
switch(operator1) {
   case 0: c1 += b; break;
   case 1: c1 -= b; break;
   // ...
 }

Upvotes: 1

Related Questions