Vickie
Vickie

Reputation: 67

Beginner Java - Changing String from First Middle Last to Last, First Middle

Trying to work out a homework problem that demands: Changes a name so that the last name comes first. Example: "Mary Jane Lee" will return "Lee, Mary Jane". If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

java.lang.StringIndexOutOfBoundsException: String index out of range: -7

and

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

when the name is Sarah

This is my code, but I'm not sure how to fix it:

public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}     

Thanks in advance!!

Upvotes: 1

Views: 5727

Answers (4)

Andy Turner
Andy Turner

Reputation: 140319

A more robust way is to use lastIndexOf to find the last space:

int lastSpace = name.lastIndexOf(' ');
if (lastSpace != -1) {
  String lastName = name.substring(lastSpace + 1);
  String partBeforeLastName = name.substring(0, lastSpace);
  return lastName + ", " + partBeforeLastName;
} else {
  return name;
}

You don't actually really care about the other space (if it's there at all), since the first and middle names stay in the same relative order.

(Generally, there are lots of falsehoods that programmers believe about names; but let's put those aside for the purpose of the exercise.)

Upvotes: 2

Usagi Miyamoto
Usagi Miyamoto

Reputation: 6289

The problem is that your code excepts that there are 3 names. It does not handle when there are less names.

public static String lastNameFirst(String name)
{
  int firstIndex = name.indexOf(" ");
  if ( firstIndex >= 0 )
  {
    int secondIndex = name.indexOf(" ", firstIndex + 1 );
    String firstName = name.substring(0, firstIndex);
    if ( secondIndex >= 0 ) // we have 3 names
    {
      String middleName = name.substring(firstIndex + 1, secondIndex);
      String lastName = name.substring(secondIndex + 1);
      return lastName + ", " + firstName + " " + middleName; 
    }
    else // we have 2 names
    {
      String lastName = name.substring(firstIndex + 1);
      return lastName + ", " + firstName;
    }
  }
  else // have only one name
    return name;
}

Should worth trying lastIndexOf(), too:

public static String lastNameFirst(String name)
{
  int lastIndex = name.lastIndexOf(" ");
  if ( lastIndex >= 0 ) // have at least 2 names
  {
      String firstNames = name.substring(0,lastIndex);
      String lastName = name.substring(lastIndex + 1);
      return lastName + ", " + firstNames;
    }
  }
  else // have only one name
    return name;
}

Also, could try a different approach, split the name into an array, something like this:

public static String lastNameFirst(String name)
{
  String[] parts = name.split(" ");
  switch ( parts.length )
  {
    case 1:
      return name;
    case 2:
      return parts[1] + ", " + parts[0];
    case 3:
      return parts[2] + ", " + parts[0] + " " + parts[1];
  }
}

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44834

using split and a switch would be a lot easier

    String name = "Mary Jane Lee";
    String arr[] = name.split (" ");

    switch (arr.length) {
        case 1:
            System.out.println(name);
            break;
        case 2:
            System.out.println(arr[1] + ", " + arr[0]);
            break;
        default:
            System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);  
    }

Upvotes: 4

Eran
Eran

Reputation: 393791

Your code assumes that the input String contains at least two spaces. When that assumption is wrong (as in the inputs "Harry Smith" and "Sarah"), you get an exception.

You must check whether firstIndex and secondIndex are positive before using their values.

Upvotes: 1

Related Questions