我正在尝试扫描字符串(用户键入的用户名),以获取特殊字符(!@#$%^& * _ |?)。但是我相信indexOf会扫描所有这些字符,而不是仅查找一个字符。继承我的代码:
System.out.println("Please choose a user name, it must contain a special charcter and can include spaces");
String user;
String spe = "[^!@#$%^&*(){}><?~*]"; //Chars i want to be accepted
user = input.nextLine();
int signin3 = user.indexOf(spe);
if (signin3 != 0) { //If there there is a chararacter
System.out.println("Correct");
} else //If there is no character
System.out.print("Thats not correct, maybe try one of these at the end: " + user + "123! or" + user + "abc? or" + user "Honda$" );
我遇到的问题是,当我输入一个特殊字符时,它仍会输出其他内容,只有当我输入所有那些不是我希望它工作的字符时它才有效,任何人都知道如何修复这个?谢谢!
答案 0 :(得分:0)
首先如评论中所述,indexOf在找不到它寻找的内容时返回-1,而不是0。
我毫不怀疑你在问这个问题之前并没有真正在线搜索解决方案......但无论如何,我推荐的解决方案是使用匹配器。
System.out.println("insert username");
String user;
Pattern p = Pattern.compile("[^a-z0-9 ]"); //Chars to look for
Scanner scan = new Scanner(System.in);
user =scan.nextLine();
Matcher m = p.matcher(user); //Matching the pattern(what you wanna look for) and the username
boolean b = m.find();
if (b==true) { //If there there is a chararacter
System.out.println("Correct");
} else //If there is no character
System.out.print("Thats not correct, maybe try one of these at the end: " + user + "123! or" + user + "abc? or" + user+"Honda$" );