【发布时间】:2021-04-22 10:34:26
【问题描述】:
我有以下代码:
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);
【问题讨论】:
-
循环后加
f_name = sc.next().toUpperCase();怎么样? -
感谢您回答@khelwood...如果输入有效,它会很好用。如果它无效(例如
123456)它将继续无限循环 -
我没有说从循环内部中删除
sc.next()。 -
哎呀!现在工作正常,非常感谢:D
标签: java string validation java.util.scanner