Validating a string in Java
I have a question about validation in Java, I have looked at previous topic and none seem to answer my little problem.
What I am trying to do is validate what is put into开发者_C百科 a string variable in the constructor but also when a set method is used.
What I need to is If Mr Miss Mrs or Ms is entered, then to set that in a Variable (title) if not then to set title as ''Not set'' and print an error, now I know how to the the last part, its the the validation of what the user is entering into the variable I am stuck in... I have tried using an array but couldn't get it to work and tried if statements, again couldn't get it to function
public void setTitle(final String title)
{
if (title.matches("^Mrs|Mr|Miss|Ms$"))
{
this.title = title;
}
else
{
this.title = "Not Set";
System.err.format("%s is not a valid title, expecting Mrs,Mr,Miss,Ms\n", title);
}
}
if you want to do case insensitive then change the regular expression to:
"(?i)^Mrs|Mr|Miss|Ms$"
then you can just lowercase the entire thing and uppercase just the first letter to re-normalize your input to what you really want. Google for "java proper case" to find some pre-written snippets of code.
A more concise one liner, again case sensitive:
public void setTitle(final String title)
{
title.matches("^Mrs|Mr|Miss|Ms$")) ? this.title= title: this.title= "Not Set";
}
why not just call a small method that does the validation and then sets the value?
private void validateString(String) {
if string is valid
call setter
}
Use this
String title = textBoxTitle.getText();
if(!title.equals("Mr") && !title.equals("Miss") && !title.equals("Mrs") && !title.equals("Ms"))
{
// Text is invalid
}
else
{
// Text is valid
}
Create a set of the words that you care about (capitalize them), and then see if the title falls into the set:
Set allowedTitles = new HashSet();
allowedTitles.add("MR");
allowedTitles.add("MRS");
allowedTitles.add("MS");
allowedTitles.add("MISS");
if (! allowedTitles.contains(textBoxTitle.getText().trim().toUpperCase()) {
//print exception
}
else { title = textBoxTitle.getText().trim());
i'm pretty sure u did something like --
if(title =="Mr."){ blah.. } // this will check the address
do this instead ..
if(title.equals("Mr."){blah..} // this will check the values..
精彩评论