Question:
How do I go about generating a random math operator in Java?
Answer:
By using a random number generator and a switch statement:
Code:
import java.util.Random; public class SimpleMath { public static void main(String[] args) { Random r = new Random(); int A = 10; int B = 2; char operator ='?'; int value = 0; switch (r.nextInt(4)){ case 0: operator = '+'; value = A+B; break; case 1: operator = '-'; value = A-B;; break; case 2: operator = '*'; value = A*B;; break; case 3: operator = '/'; value = A/B;; break; default: operator = '?'; } System.out.print(A); System.out.print(" "); System.out.print(operator); System.out.print(" "); System.out.print(B); System.out.print(" = "); System.out.println(value); } }
Output:
$ java SimpleMath 10 * 2 = 20 $ java SimpleMath 10 - 2 = 8 $ java SimpleMath 10 + 2 = 12 $ java SimpleMath 10 * 2 = 20