如何使用 java 扫描器进行字符串验证?

How to use java scanner with string validation?

我有以下代码:

String f_name = "";
System.out.println(ANSI_PURPLE + "What is your first name?");
System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");

while(!sc.hasNext("[A-Za-z]*")) {
    System.out.println(ANSI_RED + " ERROR: Invalid option! ");
    System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");
    f_name = sc.next().toUpperCase();
}


System.out.println("First Name = " + f_name);

以上代码的问题是它会存储之前添加的内容。

例如:

What is your first name?
 Type your name here (use only latin characters) > 123
 ERROR: Invalid option! 
 Type your name here (use only latin characters) > c
First Name = 123

如何修复以便拉丁字符的验证仍然有效,如果有错误则将用户重定向到相同的问题并存储正确的值?


我的问题的正确答案:

...
while(!sc.hasNext("[A-Za-z]*")) {
    System.out.println(ANSI_RED + " ERROR: Invalid option! ");
    System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");
    sc.next();
}

f_name = sc.next().toUpperCase();
System.out.println("First Name = " + f_name);

sc.hasNext("[A-Za-z]*") returns 为真时,这意味着您阅读的 下一个 输入将是您想要的。所以你需要在循环结束后阅读f_name

您仍然需要 sc.next() 进入循环以克服错误的输入;否则你将有一个无限循环。

顺便说一句,也许您想在正则表达式中使用 + 而不是 ** 表示“零个或多个”,+ 表示“一个或多个”。我假设您要输入一个或多个字符。

while (!sc.hasNext("[A-Za-z]+")) {
    System.out.println(ANSI_RED + " ERROR: Invalid option!");
    System.out.print(ANSI_RESET + " Type your name here (use only latin characters) > ");
    sc.next();
}

String f_name = sc.next().toUpperCase();