【发布时间】:2021-05-24 00:32:58
【问题描述】:
我正在创建一个主机游戏。我希望玩家能够选择自己的用户名。拥有像 .-|\12b-}| 这样的用户名真的很奇怪。我希望能够检查用户名中是否包含“特殊字符”。如果玩家的用户名中有特殊字符,我希望系统打印出一条消息(例如:请更改您的用户名)。我不希望代码只是replace 字母。
这是一个示例(如果您有答案,请按照此操作):
import java.util.Scanner;
class StackOverflowExample {
public static void main(String[] args) {
System.out.println("Welcome New Player! What will your name be?");
Scanner userInteraction = new Scanner(System.in);
String userInput = userInteraction.nextLine();
System.out.println("Welcome " + userInput + "!");
}
}
输出:
你可以明白为什么这会非常奇怪..
我希望能够扫描:
String userInput = userInteraction.nextLine();
对于任何奇怪的字符。 我将如何扫描字符串?
【问题讨论】:
-
我相信扫描器可以接受正则表达式作为参数来验证 next() 输入。 "a-zA-Z0-9_" 将过滤带有下划线等的字母数字字符。
-
这里的独特性似乎不是一个因素......
-
@VLAZ 唯一字符是“/”或“%”之类的字符
-
那些被称为“特殊字符”。术语“唯一”几乎完全意味着编程中的“不重复”。因此,字符串
"abc"包含唯一字符,但"abca"不包含,因为"a"出现了两次。 -
@VLAZ 谢谢,现在改了。
标签: java string console java.util.scanner user-input