What would be the best way to change my validation for my first name and last na
ID: 3557958 • Letter: W
Question
What would be the best way to change my validation for my first name and last name so that it will not accept anything other than letters AND spaces AND " ' ". I need it to accept names such as O'Conners, Murray III, Murray JR. Etc. Would Regular Expression be best? If so how would I do it?
do {
error = 0;
System.out.print(" Enter the first name: ");
first = input.nextLine();
first = first.trim();
if (first.length() < 3) {
System.out.println("First name must have at least 3 characters");
error = 1;
}
if (!first.matches("[a-zA-Z]+")) {
System.out.println("Name should contain letters only");
error = 1;
}
}
while (error == 1);
do {
error = 0;
System.out.print("Enter the last name: ");
last = input.nextLine();
last = last.trim();
if (last.length() < 3) {
System.out.println("Last name must have at least 3 characters.");
error = 1;
}
if (!last.matches("[a-zA-Z]+")) {
System.out.println("Name should contain letters only");
error = 1;
}
}
while (error == 1);
Explanation / Answer
do {
error = 0;
System.out.print(" Enter the first name: ");
first = input.nextLine();
first = first.trim();
if (first.length() < 3) {
System.out.println("First name must have at least 3 characters");
error = 1;
}
for(int i=0; i<first.length(); i++)
{
if(first.charAt(i)>='A' && first.charAt(i)<='Z')
continue;
else if(first.charAt(i)>='a' && first.charAt(i)<='z')
continue;
else if(first.charAt(i) == '.')
continue;
else if(first.charAt(i) == ''')
continue;
else
{
error = 1;
break;
}
}
}while (error == 1);
do {
error = 0;
System.out.print("Enter the last name: ");
last = input.nextLine();
last = last.trim();
if (last.length() < 3) {
System.out.println("Last name must have at least 3 characters.");
error = 1;
}
for(int i=0; i<last.length(); i++)
{
if(last.charAt(i)>='A' && last.charAt(i)<='Z')
continue;
else if(last.charAt(i)>='a' && last.charAt(i)<='z')
continue;
else if(last.charAt(i) == '.')
continue;
else if(last.charAt(i) == ''')
continue;
else
{
error = 1;
break;
}
}
}while (error == 1);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.