Search code examples
javastringsubstringindexoutofboundsexception

How do I troubleshoot an OutOfBoundsException error when trying to get initials from a full name in Java?


University computer science major here. I'm using zyBooks for my Object-Oriented Programming class. I'm stuck on an error when I'm trying to work with substrings and whatnot when asked to derive initials from a full name. I'm asked to do the following

Write a public static method named getInitials that will take a single argument of type String and will return a String. When called, and passed a name, this method must compute and return a String value with the initials for the given name.

Below is my code so far. I've tried looking at other resources, but I'm not really allowed to use concepts outside of what we've learned and what's given as criteria for this assignment.

// Below this comment: import the Scanner
import java.util.Scanner;
public class Initials {
   public static void main(String[] args) {
      // Below this comment: declare and instantiate a Scanner
      Scanner scnr = new Scanner(System.in);
      
      // Below this comment: collect the required inputs
      System.out.println("Enter name : ");
        String name = scnr.next();
      
      
      // Below this comment: call your required method
      String initials = getInitials(name);
      
      
      // Below this comment: disply the required results
      System.out.println("Initials for " + name + " : " + initials);
      
   }
   
   // define your required method here below
   public static String getInitials(String name){
      String firstName = name.substring(0, name.indexOf(" "));
      String firstInit = firstName.substring(0, 1);
      String middleName = name.substring((name.indexOf(" ")+1), name.lastIndexOf(" "));
      String middleInit = middleName.substring(0, 1);
      String lastName = name.substring((name.lastIndexOf(" ")+1), name.length());
      String lastInit = lastName.substring(0, 1);
      String initials = (firstInit + ". " + middleInit + ". " + lastInit + ".");
      return initials;
   }
}

This is the error zyBooks displays:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 3
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
    at java.base/java.lang.String.substring(String.java:1874)
    at Initials.getInitials(Initials.java:24)
    at Initials.main(Initials.java:14)

I know it has something to do with the code trying to access stuff outside of my parameters, but I'm not sure what to tweak to make sure that doesn't happen. I think I need an if statement but I don't know. Any help is appreciated!

Sorry if this post isn't clarified that well. I've been working on this all day and I have a headache.


Solution

  • String middleName = name.substring((name.indexOf(" ") + 1), name.lastIndexOf(" "));
    

    This line is a problem when you name only has one space inside it (ex: "John Doe"). It will look for a substring between the index of the first space (4 in thsis case) in the name + 1 and the last space which is the same one! So in this case you are asking for a substring between 5 and the lesser 4 which will give an error.

    If you can, I recommend the split method. This will work with multiple names:

    StringBuilder initials = new StringBuilder(new String());
    String[] individualNames = name.split(" ");
    for (int i = 0; i < individualNames.length; i++) {
      initials.append(individualNames[i].substring(0, 1) + ". ");
    }
    System.out.println(initials);