Reputation:
I'm working on a server/client battleship game using sockets. Part of the project requires entry validation on the client side for entering tile locations. A user is supposed to enter a letter A-E and a number 1-5, and right now if you type in something invalid, it seems to freeze. Any help would be much appreciated, thanks in advance!
do{
System.out.println("------------------------------------------------------------------------------------------------");
System.out.println("Please type in a board position in the format of a letter followed by number, such as 'A1'. ");
Scanner sc = new Scanner(System.in);
String BoardChoice = sc.next();
if(BoardChoice.equals("A1" ) || BoardChoice.equals("B1" ) || BoardChoice.equals("C1" ) || BoardChoice.equals("D1" ) || BoardChoice.equals("E1" ) ||
BoardChoice.equals("A2" ) || BoardChoice.equals("B2" ) || BoardChoice.equals("C2" ) || BoardChoice.equals("D2" ) || BoardChoice.equals("E2" ) ||
BoardChoice.equals("A3" ) || BoardChoice.equals("B3" ) || BoardChoice.equals("C3" ) || BoardChoice.equals("D3" ) || BoardChoice.equals("E3" ) ||
BoardChoice.equals("A4" ) || BoardChoice.equals("B4" ) || BoardChoice.equals("C4" ) || BoardChoice.equals("D4" ) || BoardChoice.equals("E4" ) ||
BoardChoice.equals("A5" ) || BoardChoice.equals("B5" ) || BoardChoice.equals("C5" ) || BoardChoice.equals("D5" ) || BoardChoice.equals("E5" ))
{
flagtoo = false;
writer.writeUTF(BoardChoice);
}
else
{
System.out.println("Invalid Input Please re-enter!");
}
}while(flagtoo);
Upvotes: 0
Views: 35
Reputation: 48258
My suggestion on the other hand will suggest to implement regex with a pattern that allows you to match 1st char alpha(no matter capitalization) followed by a number, both in a range from a → e and 1 → 5
Scanner sc = new Scanner(System.in);
System.out.println("Please type in a ....y number, such as 'A1'. ");
do {
inp = sc.nextLine();
if (inp.matches("^[a-eA-E1-5]{0,2}")) {
inpArr[k++] = inp;
} else {
System.out.println("invalid input");
}
} while (k < numberOfElements);
System.out.println(Arrays.toString(inpArr));
Upvotes: 0
Reputation: 201429
I would suggest you test each character separately by breaking them out with charAt
, and please respect variable naming conventions. Something like
boolean valid = false;
String boardChoice = sc.nextLine(); // <-- not next
if (boardChoice.length() == 2) {
char col = boardChoice.charAt(0);
char row = boardChoice.charAt(1);
// The parenthesis here are just for clarity.
valid = ((col >= 'A' && col <= 'E') && (row >= '1' && row <= '5'));
}
Upvotes: 1