Skip to content

Commit d07532b

Browse files
committed
refactor: adding an exception
1 parent 4798fad commit d07532b

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

app/src/main/java/hexlet/code/games/Calc.java

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,35 +6,31 @@
66
public class Calc {
77
private static final int MIN = 0;
88
private static final int MAX = 100;
9+
910
public static void startGame() {
1011
String[][] roundsData = new String[Engine.ROUNDS][2];
1112
String description = "What is the result of the expression?";
1213

1314
for (int i = 0; i < Engine.ROUNDS; i++) {
1415
int num1 = Utils.generateNumber(MIN, MAX);
1516
int num2 = Utils.generateNumber(MIN, MAX);
16-
char mathSymbol = getRandomMathSymbol();
17+
char[] mathSymbols = {'+', '-', '*'};
18+
int index = Utils.generateNumber(0, 2);
1719

18-
String question = num1 + " " + mathSymbol + " " + num2;
20+
String question = num1 + " " + mathSymbols[index] + " " + num2;
1921

2022
roundsData[i][0] = question;
21-
roundsData[i][1] = String.valueOf(getExpressionResult(mathSymbol, num1, num2));
23+
roundsData[i][1] = String.valueOf(calculate(mathSymbols[index], num1, num2));
2224
}
2325
Engine.run(description, roundsData);
2426
}
2527

26-
private static char getRandomMathSymbol() {
27-
char[] mathSymbols = {'+', '-', '*'};
28-
int index = Utils.generateNumber(0, 2);
29-
return mathSymbols[index];
30-
}
31-
32-
private static int getExpressionResult(char mathSymbol, int numOne, int numTwo) {
33-
return switch (mathSymbol) {
34-
case '+' -> numOne + numTwo;
35-
case '-' -> numOne - numTwo;
36-
case '*' -> numOne * numTwo;
37-
default -> 0;
28+
private static int calculate(char operator, int num1, int num2) {
29+
return switch (operator) {
30+
case '+' -> num1 + num2;
31+
case '-' -> num1 - num2;
32+
case '*' -> num1 * num2;
33+
default -> throw new RuntimeException("Unknown operator: " + operator);
3834
};
3935
}
4036
}

0 commit comments

Comments
 (0)