Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Accept user input of a name string. Verify that the name string contains a

ID: 3774144 • Letter: J

Question

JAVA

Accept user input of a name string. Verify that the name string contains a first name and a last name and that both contain valid characters and are from 2 to 20 characters in length. The name string may optionally contain a middle name or middle initial. The name string may also y contain a leading salutation or title (Mr., Mrs., Miss, Dr.).

Also option to add (junior,senior,ll,..)

Determine whether a valid name string has been entered. If not, indicate why. In any case, the program should continue to ask the user for a name string until the user enters "end".

Explanation / Answer

import java.io.*;

import java.util.*;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class CheckName{

public static void main(String args[])

{

String name = "Mr Ganesh K More";

String error = "";

int i = 0;

int spaceCount = 0;

while( i < name.length() ){

if( name.charAt(i) == ' ' ) {

spaceCount++;

}

i++;

}

System.out.println("space count: "+spaceCount);

CharSequence inputStr = name;

Pattern pattern = Pattern.compile(new String ("^[a-zA-Z\s]*$"));

Matcher matcher = pattern.matcher(inputStr);

String[] splited = name.split("\s+");

String split_one=splited[0];

String split_second=splited[1];

String split_three=splited[2];

String split_four=splited[2];

if(spaceCount <= 3 ){

if(matcher.matches()){

if(split_one.equals("Mr") || split_one.equals("Mrs")){

// you can use array.eqauls method to compair the titles.

System.out.println("Name is validated: "+name);

}else{

error = "Wrong salutation or title";

}

}else{

error = "Only characters are allowed.";

}

}else{

error = "Wrong fullname";

}

System.out.println("Error: "+error);

}

}