我想验证名称是否包含特殊字符。请告诉我这段代码有什么问题?我的代码是:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Name {
static Scanner in = new Scanner(System.in);
public static String verifyName() {
System.out.print("Enter your name: ");
String name = in.nextLine();
Pattern p = Pattern.compile("[a-zA-Z0-9]*");
Matcher m = p.matcher(name);
if(!m.matches()) {
System.out.println("Invalid Name");
verifyName();
}
return name;
}
public static void main(String args[]) {
String result = verifyName();
System.out.print(result);
}
}
输出:
Enter your name: @li
Invalid Name
Enter your name: #sd
Invalid Name
Enter your name: Zain
@li
必填项:
Enter your name: @li
Invalid Name
Enter your name: #sd
Invalid Name
Enter your name: Zain
Zain
提前致谢!
答案 0 :(得分:1)
您的整个代码应该像
extension String {
func fromUTCToLocalDateTime() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
var formattedString = self.replacingOccurrences(of: "Z", with: "")
if let lowerBound = formattedString.range(of: ".")?.lowerBound {
formattedString = "\(formattedString[..<lowerBound])"
}
guard let date = dateFormatter.date(from: formattedString) else {
return self
}
dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"
dateFormatter.timeZone = TimeZone.current
return dateFormatter.string(from: date)
}
}
为了提高效率,您可以使用迭代循环。
答案 1 :(得分:0)
您的方法需要从子函数调用中返回名称的值
if(!m.matches()) {
System.out.println("Invalid Name");
return verifyName();
}
而不是
if(!m.matches()) {
System.out.println("Invalid Name");
verifyName();
}
然而,使用循环而不是递归调用可能更好:
public static String verifyName() {
while (true)
{
System.out.print("Enter your name: ");
String name = in.nextLine();
Pattern p = Pattern.compile("[a-zA-Z0-9]*");
Matcher m = p.matcher(name);
if(m.matches()) {
return name;
}
}
}