String nameStr = "george raymond richard martin";
String formattedName = " ", firstName = " ", middleName = " ", lastName = " ", middleInitial = " ";
int index = 0;
if (nameStr.indexOf(" ") == -1) { //for one name case
formattedName = nameStr.substring(0, 1).toUpperCase().substring(1).toLowerCase();
}
if (nameStr.indexOf(" ") != -1) {
String nameParts[] = nameStr.split(" ");
int N = nameParts.length;
if (N == 2) { //if there are just two names
firstName = nameParts[0];
lastName = nameParts[N - 1];
firstName = firstName.substring(0, 1).toUpperCase().substring(1).toLowerCase();
lastName = lastName.substring(0, 1).toUpperCase().substring(1).toLowerCase();
formattedName = lastName + ", " + firstName;
} else { //for any amount of names
for (index = 1; index <= N - 2; index++) {
middleName = nameParts[index];
firstName = nameParts[0];
lastName = nameParts[N - 1];
middleInitial = middleName.substring(0, 1).toUpperCase() + ".";
formattedName = lastName + ", " + firstName + middleInitial;
}
}
}
System.out.println(formattedName);
this is what I have right now, and I feel like my logic is on the right track but it's not printing anything out properly. It doesn't print for the one word case, and for the two word case it just prints out the comma. The case for any amount of middle names works, but only for three words, and if there is more than one middle name it just truncates it to the last middle name. I have no idea what the issue is, I just feel like i need someone else to look at it. Thanks :)