有 Java 编程相关的问题?

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

Java:限制字符串中的字符

我如何通过扫描仪和字符串接受用户的特定字符

例如,如果我只想输入两个字符,“*”和“”(一个空格)。其他所有内容都将无效,并会提示用户该内容不足,并在不提交的情况下重做条目

干杯


共 (3) 个答案

  1. # 1 楼答案

    如果您想在输入后检查字符串的内容,那么可以检查它是否匹配regex [* ]+,这意味着:一个或多个(+量词)字符的序列'*'' '(空格)

    代码:

    System.out.print("Please provide string containing only spaces or * : ");
    String userInput = //read input from user
    while(!userInput.matches("[* ]+")){
        System.out.println("Your input was incorrect.");
        System.out.print("Please provide string containing only spaces or * : ");
        userInput = //read input from user
    }
    //here we know that data in userInput are correct
    doSomethingWithUserData(userInput);
    
  2. # 2 楼答案

    String input = scanner.nextLine();
    if (!(input.matches("[ *]*"))) {
        System.out.println("Please use only space and * characters");
        // do something that causes program to loop back and redo input
    }
    

    matches测试整个input字符串是否与模式匹配。模式由字符类中的零个或多个字符序列匹配(第二个*表示零个或多个出现),字符类由两个字符空间和*组成

    如果需要输入至少一个字符,请将第二个*更改为+,但也要更改错误消息。或者添加一个单独的input.isEmpty()测试

    至于Scanner:使用scanner.nextLine()输入整行。(其他Scanner方法在看到空格字符时往往会停止,我想这不是您想要的。)

  3. # 3 楼答案

    可以使用正则表达式字符集排除:

    if (input.matches(".*[^* ].*")) {
        //wrong input
    } else {
        //ok!
    }
    

    请注意,将传递一个空字符串作为有效字符串,这取决于您的用例是否额外验证字符串的长度