我正在使用套接字处理服务器/客户端战舰游戏。项目的一部分需要在客户端进行输入验证以输入磁贴位置。用户应该输入一个字母A-E和一个数字1-5,而现在如果你输入一些无效的东西,它似乎会冻结。任何帮助将非常感谢,提前感谢!
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);
答案 0 :(得分:1)
我建议您分别使用charAt
分析每个字符,然后请尊重变量命名约定。像
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'));
}
答案 1 :(得分:0)
另一方面,我的建议是建议使用一种模式来实现正则表达式,该模式允许您匹配第一个char alpha(无论大小写)后跟一个数字, 两者都在a→e和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));