简体   繁体   中英

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 ie 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, ie how do you replace it with the + and - operations.

Please let me know if you know. Thank you

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;
   // ...
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM