-
Notifications
You must be signed in to change notification settings - Fork 8
/
DiceRoller.java
29 lines (27 loc) · 1.08 KB
/
DiceRoller.java
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
import java.util.Scanner;
public class DiceRoller {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
do {
input = getDiceExpression(scanner);
if (!input.equalsIgnoreCase("exit")) {
DiceExpression expression = new DiceExpression(input);
expression.evaluate();
}
} while (!input.equalsIgnoreCase("exit"));
}
public static String getDiceExpression(Scanner scanner) {
System.out.print("Enter a dice roll expression (e.g., 2d6!): ");
String expression = scanner.nextLine();
// Check for exit command before validating the input
if (expression.equalsIgnoreCase("exit")) {
return "exit";
}
if (!expression.matches("(\\d*d\\d+(!)?|\\d+)(\\s*[+\\-*/]\\s*(\\d*d\\d+(!)?|\\d+))*")) {
System.out.println("Error! Invalid dice format. Try again.");
return getDiceExpression(scanner); // Recursively call to get a valid input
}
return expression;
}
}