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 楼答案
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
}
# 1 楼答案
如果您想在输入后检查字符串的内容,那么可以检查它是否匹配regex
[* ]+
,这意味着:一个或多个(+
量词)字符的序列'*'
或' '
(空格)代码:
# 2 楼答案
matches
测试整个input
字符串是否与模式匹配。模式由字符类中的零个或多个字符序列匹配(第二个*
表示零个或多个出现),字符类由两个字符空间和*
组成如果需要输入至少一个字符,请将第二个
*
更改为+
,但也要更改错误消息。或者添加一个单独的input.isEmpty()
测试至于
Scanner
:使用scanner.nextLine()
输入整行。(其他Scanner
方法在看到空格字符时往往会停止,我想这不是您想要的。)# 3 楼答案
可以使用正则表达式字符集排除:
请注意,将传递一个空字符串作为有效字符串,这取决于您的用例是否额外验证字符串的长度