Java 将用户的字符串输入限制为字母和数字值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3090795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restrict string input from user to alphabetic and numerical values
提问by Sachin
Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.
基本上,我的情况要求我检查由用户从键盘输入定义的字符串在一种情况下是否仅是字母字符,在另一种情况下是否仅是数字。这是用Java编写的。
my current code:
我目前的代码:
switch (studentMenu) {
case 1: // Change all four fields
System.out.println("Please enter in a first name: ");
String firstNameIntermediate = scan.next();
firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);
System.out.println("Please enter in a middle name");
middleName = scan.next();
System.out.println("Please enter in a last name");
lastName = scan.next();
System.out.println("Please enter in an eight digit student ID number");
changeID();
break;
case 2: // Change first name
System.out.println("Please enter in a first name: ");
firstName = scan.next();
break;
case 3: // Change middle name
System.out.println("Please enter in a middle name");
middleName = scan.next();
break;
case 4: // Change last name
System.out.println("Please enter in a last name");
lastName = scan.next();
case 5: // Change student ID:
changeID();
break;
case 6: // Exit to main menu
menuExit = true;
default:
System.out.println("Please enter a number from 1 to 6");
break;
}
}
}
public void changeID() {
studentID = scan.next();
}
I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.
我需要确保 StudentID 只是数字,并且每个名称段都是按字母顺序排列的。
采纳答案by polygenelubricants
java.util.Scanner
can already check if the next token is of a given pattern/type with the hasNextXXX
methods.
java.util.Scanner
已经可以使用方法检查下一个标记是否属于给定的模式/类型hasNextXXX
。
Here's an example of using boolean hasNext(String pattern)
to validate that the next token consists of only letters, using the regular expression [A-Za-z]+
:
这是boolean hasNext(String pattern)
使用正则表达式验证下一个标记是否仅包含字母的示例[A-Za-z]+
:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter letters:");
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
String word = sc.next();
System.out.println("Thank you! Got " + word);
Here's an example session:
这是一个示例会话:
Please enter letters:
&#@#$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james
Please enter letters:
&#@#$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james
To validate that the next token is a number that you can convert to int
, use hasNextInt()
and then nextInt()
.
要验证下一个标记是可以转换为的数字,请int
使用hasNextInt()
,然后使用nextInt()
。
Related questions
相关问题
- Validating input using java.util.Scanner- has many examples!
- 使用 java.util.Scanner 验证输入- 有很多例子!
回答by InsertNickHere
Im not sure this is the best way to do, but you could use Character.isDigit() and Character.IsLiteral() mabybe like this:
我不确定这是最好的方法,但你可以像这样使用 Character.isDigit() 和 Character.IsLiteral() mabybe:
for( char c : myString.toCharArray() ) {
if( !Character.isLiteral(c) ) {
//
}
}
回答by Lauri Lehtinen
I don't think you can prevent the users from entering invalid values, but you have the option of validating the data you receive. I'm a fan of regular expressions. Real quick, something like this maybe (all values initialized to empty Strings):
我认为您无法阻止用户输入无效值,但您可以选择验证收到的数据。我是正则表达式的粉丝。真的很快,可能是这样的(所有值都初始化为空字符串):
while (!firstName.matches("^[a-zA-Z]+$")) {
System.out.println("Please enter in a first name");
firstName = scan.next();
}
...
while (!studentID.matches("^\d{8}$")) {
System.out.println("Please enter in an eight digit student ID number");
changeID();
}
If you go this route, you might as well categorize the different cases you need to validate and create a few helper methods to deal with each.
如果你走这条路,你不妨对需要验证的不同情况进行分类,并创建一些帮助方法来处理每个情况。
"Regex" tends to seem overwhelming in the beginning, but learning it has great value and there's no shortage of tutorials for it.
“Regex”一开始看起来似乎势不可挡,但学习它具有很大的价值,而且不乏教程。
回答by Alex Zharnasek
try regexp: \d+ -- numerical, [A-Za-z]+ -- alphabetical
尝试正则表达式:\d+ -- 数字,[A-Za-z]+ -- 字母
回答by Jon Skeet
It's probably easiest to do this with a regular expression. Here's some sample code:
使用正则表达式可能最容易做到这一点。这是一些示例代码:
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
System.out.println(isNumeric("123"));
System.out.println(isNumeric("abc"));
System.out.println(isNumeric("abc123"));
System.out.println(isAlpha("123"));
System.out.println(isAlpha("abc"));
System.out.println(isAlpha("abc123"));
}
private static final Pattern NUMBERS = Pattern.compile("\d+");
private static final Pattern LETTERS = Pattern.compile("\p{Alpha}+");
public static final boolean isNumeric(String text)
{
return NUMBERS.matcher(text).matches();
}
public static final boolean isAlpha(String text)
{
return LETTERS.matcher(text).matches();
}
}
You should probably write methods of "getAlphaInput" and "getNumericInput" which perform the appropriate loop of prompt/fetch/check until the input is correct. Or possibly just getInput(Pattern)
to avoid writing similar code for different patterns.
您可能应该编写“getAlphaInput”和“getNumericInput”方法,它们执行适当的提示/获取/检查循环,直到输入正确为止。或者可能只是getInput(Pattern)
为了避免为不同的模式编写类似的代码。
You should also work out requirements around what counts as a "letter" - the above only does a-z and A-Z... if you need to cope with accents etc as well, you should look more closely at the Pattern
docs and adapt appropriately.
您还应该制定关于什么算作“字母”的要求 - 以上仅适用于 az 和 AZ ......如果您还需要处理口音等问题,您应该更仔细地查看Pattern
文档并进行适当的调整。
Note that you can use a regex to validate things like the length of the string as well. They're very flexible.
请注意,您也可以使用正则表达式来验证字符串长度等内容。他们非常灵活。
回答by KralBey
That is the code
那是代码
public class InputLetters {
String InputWords;
Scanner reader;
boolean [] TF;
boolean FT;
public InputLetters() {
FT=false;
while(!FT){
System.out.println("Enter that you want to: ");
reader = new Scanner(System.in);
InputWords = reader.nextLine();
Control(InputWords);
}
}
public void Control(String s){
String [] b = s.split(" ");
TF = new boolean[b.length];
for(int i =0;i<b.length;i++){
if(b[i].matches("^[a-zA-Z]+$")){
TF[i]=true;
}else
{
TF[i]=false;
}
}
for(int j=0;j<TF.length;j++){
if(!TF[j]){
FT=false;
System.out.println("Enter only English Characters!");
break;
}else{
FT=true;
}
}
}