gpt4 book ai didi

Java 条目验证

转载 作者:行者123 更新时间:2023-12-02 13:20:46 25 4
gpt4 key购买 nike

我正在使用套接字开发服务器/客户端战舰游戏。该项目的一部分需要在客户端进行输入验证以输入图 block 位置。用户应该输入字母 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);

最佳答案

我建议您使用 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'));
}

关于Java 条目验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43580117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com