gpt4 book ai didi

java - 在java递归中返回变量的更新值

转载 作者:行者123 更新时间:2023-12-02 11:51:33 24 4
gpt4 key购买 nike

我想验证名称是否包含特殊字符。请让我知道这段代码有什么问题?我的代码是:

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

提前致谢!

最佳答案

你的整个代码应该是这样的

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");
return verifyName();
}
return name;
}

public static void main(String args[]) {
String result = verifyName();
System.out.print(result);
}
}

为了提高效率,您可以使用迭代循环。

关于java - 在java递归中返回变量的更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47843997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com