Max M
Max M

Reputation: 11

Dice Rolling Game

So in this dice rolling game, what the user inputs must follow the format of xdy, where "x" is the number of dice and "y" is the number of sides the dice has. If the input doesn't follow the format, the program should ask the user to put in another input.

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner user_input = new Scanner(System.in);

    String input;
    System.out.println("Please enter the number and type of dice to roll in the format <number>d<sides>.");
    input = user_input.nextLine();  

    while()
            {
            System.out.println("Input is not valid. Please enter a new input");
            input = user_input.nextLine();
            }

    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(5);

My question is, how do I make the while loop check for a character between two integers?

Upvotes: 1

Views: 387

Answers (2)

Mureinik
Mureinik

Reputation: 311528

One elegant way to do this would be with a Pattern:

Pattern p = Pattern.compile("\\d+d\\d+");
input = user_input.nextLine();  

while (!p.matcher(input).matches) {
    System.out.println("Input is not valid. Please enter a new input");
    input = user_input.nextLine();
}

Upvotes: 1

Sujal Mandal
Sujal Mandal

Reputation: 1039

Separate numberOfSides and number OfDice into two variables and then do whatever you want with them.

String input="6d3";
int numSides=Integer.parseInt(input.split("d")[0]);
int numDice=Integer.parseInt(input.split("d")[1]);

Upvotes: 0

Related Questions