javastringsubstringlastindexofstring-function

String index out of range on space bar character


For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.

package test;

import javax.swing.JOptionPane;

public class Usernamesubstring {

    public static void main(String[] args) {
        String fullname = JOptionPane.showInputDialog("What is your full name");
        int breakbetween = fullname.lastIndexOf(" ");
        String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
        int length = fullname.length();
        String lastnamess = fullname.substring(length - 3, length);
        String firstnamec = firstnamess.substring(0, 0);
        String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
        firstnamec = firstnamec.toUpperCase();
        lastnamec = lastnamec.toUpperCase();
        String firstname = firstnamess.substring(1,3);
        String lastname = firstnamess.substring(1,3);
        firstname = firstnamec + firstname;
        lastname = lastnamec + lastname;
        System.out.println(firstname + lastname);
}
}

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7 at java.lang.String.substring(String.java:1963) at test.Usernamesubstring.main(Usernamesubstring.java:14)


Solution

  • tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).

    Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.

    Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:

        String name = "Mario Peach Bowser";
        name = name.trim();
        String[] parts = name.split(" ");
        String lastname = parts[parts.length-1];
        String firstname = name.replace(lastname, "").trim();
        System.out.println("Hello "+firstname+", your last name is: "+lastname);
    

    In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.

    If you really want a substring approach, the following would work:

        String lastname = name.substring(name.lastIndexOf(" ")).trim();
        String firstname = name.substring(0,name.lastIndexOf(" ")).trim();
    

    You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.