I'm trying to make a substring which lets me have up to 6 letters of a surname, however what I have here seems to throw an error when it finds a surname of less than 6 letters, I have been looking for hours for a solution with no sucess :/
id = firstName.substring (0,1).toLowerCase() + secondName.substring (0,6).toLowerCase();
System.out.print ("Here is your ID number: " + id);
It's the .substring(0,6)
. I need it to be up to 6 letters not exactly 6.
The error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.substring(Unknown Source)
at Test.main(Test.java:27)
The substring begins with the character at the specified index and extends to the end of this string. substring(int beginIndex, int endIndex) : The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is (endIndex - beginIndex).
Java 9 provides a codePoints() method to convert a String into a stream of code point values. Here, we used the limit() method to limit the Stream to the given length. Then we used the StringBuilder to build our truncated string.
Java String length() Method The length() method returns the length of a specified string.
The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. The length() method can also be used for StringBuilder and StringBuffer classes.
I prefer
secondName.length > 6 ? secondName.substring(0, 6) : secondName
Use
secondName.substring (0, Math.min(6, secondName.length()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With