Priyanshu
Priyanshu

Reputation: 13

Java Strings initials

Can anybody guide me how my output is going out of bounds? What can I do to my method Letters to prevent that out of bound thing? thanks in advance

//Something is to be done here to prevent out of bound thing
public class B
{

public String Letter(String List)
{
    StringBuilder sb = new StringBuilder();
for(String s : list.split(" "))
{
    sb.append(s.charAt(0));         
}
return sb.toString();
}

Main Method

   public static void main(String[] args) 
  {
    Undesired Code Here
  }

Upvotes: 0

Views: 174

Answers (1)

Zircon
Zircon

Reputation: 4707

The issue is here:

for(String s : name.split(" "))
{
    sb.append(s.charAt(0));         
}

You've been fooled by the example "thislooks good to me", which contains two spaces in a row. The resulting String between them has a length of 0, which causes an exception at charAt(0).

Easiest fix is to check for !s.isEmpty() before appending.

Upvotes: 5

Related Questions