-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMathQuestionGenerator.java
More file actions
52 lines (42 loc) · 1.25 KB
/
MathQuestionGenerator.java
File metadata and controls
52 lines (42 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Random;
import java.util.Scanner;
public class MathQuestionGenerator {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int firstNumber = random.nextInt(16) + 1;
int secondNumber = random.nextInt(16) + 1;
if (secondNumber == 0) {
secondNumber = 1;
}
char operator = getRandomOperator();
System.out.print(firstNumber + " " + operator + " " + secondNumber + " = ");
int userAnswer = scanner.nextInt();
int correctAnswer = calculateAnswer(firstNumber, secondNumber, operator);
if (userAnswer == correctAnswer) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect! Caorrect answer is " + correctAnswer);
}
scanner.close();
}
public static char getRandomOperator() {
char[] possibleOperators = {'+', '-', '*', '/'};
Random random = new Random();
int index = random.nextInt(4);
return possibleOperators[index];
}
public static int calculateAnswer(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return 0;
}
}