0

I am doing a coding project for a basic non recursive, non GUI form of Minesweeper. One of the requirements is that input commands must be strictly formatted like so:

For marking commands (reveal, guess, mark): ["reveal"/"r"] [int] [int]

For help and quit: just ["help"/"h"] or ["quit"/"q"]

Any inputs outside of these restrictions must be considered ill-formatted. My code for reveal looks something like this:

case "reveal":
case "r":
    roundsCompleted ++;
    if(input.hasNextInt()){
        par1 = input.nextInt();
    }
    else{
        commandIn = null;
    }
    if(input.hasNextInt()){
        par2 = input.nextInt();
        correctInput = true;
    }
    else{
        commandIn = null;
    }


    if(correctInput && isInBounds(par1, par2)){
        reveal(par1, par2);

where this is all inside a switch statement of course. The commandIn = null statements are designed to throw the default case which prints "command not recognized". I realize part of my issue here is that these are in two separate if-else statements. Another problem is that input.hasNextInt() doesn't seem to evaluating to false when there is not an int after the first one.

The essence of this problem is in completely restricting these commands to the formats I listed above. Can anyone give me some insight into this issue? Thanks.

  • Or could you avoid the need for `hasNextInt` by using a regex? Something like `/^[a-z]+\d{2}$/`? Apologies if that's wrong, my regex is rusty. – Josie McClellan Feb 05 '15 at 20:11

1 Answers1

1

I'd use regex to first see if something is either a good input or not just cause it'd be easier

    String input = "r 3 4";
    if (input.matches("^(help|h|quit|q|((r|reveal) \\d \\d))$"))
        //switch case
        System.out.println("match");

    else
        //null string
        System.out.println("no match");

then after you've got a match you can use your switch case like what you're doing, if it's a "reveal" or "r", I would just use split() and turn it into an array to get the different x and y coordinates

Community
  • 1
  • 1
drop27
  • 143
  • 2
  • 11
  • Wow okay I didn't know you could do that. I am new to regex, I was trying to implement a pure java solution but this is much better, thank you. – user3522016 Feb 05 '15 at 21:35
  • anytime, good luck sounds like a cool project. I used http://rubular.com/ to quickly check what inputs the regex would match, it might be useful. – drop27 Feb 05 '15 at 21:39