有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java条目验证

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

共 (2) 个答案

  1. # 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'));
    }
    
  2. # 2 楼答案

    另一方面,我的建议是使用一种模式来实现正则表达式,该模式允许您匹配第一个字符alpha(无论大小写),后跟一个数字, 两者都在从→ e和1→ 五,

        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));