Abhinav
Abhinav

Reputation: 25

Index out of bound unexpectedly

I was trying to make a program which would read a string and put complete words into an array of string. This has been done by avoiding space. Here is my code:

String s ="Hello how are you";
String str = "";
int i=0;

String strArr[] = new String[100];
int j=0;


    while(j<=s.length()-1)              
    {       
        if(s.charAt(j)!=' ')
        {
            while(s.charAt(j)!=' ')
            {
                str = str+s.charAt(j);
                j++;
            }           
        }

        j++;
        if(!str.equals(null))
        {
            strArr[i++] = str;
            str=null;
        }
    }

The array of strings should contain Hello,how,are,you. But it is showing String index out of range: 17 but I can't find why it is behaving like this?

Upvotes: 0

Views: 80

Answers (5)

arcadeblast77
arcadeblast77

Reputation: 570

Your main issue is the condition in the inner while loop. You need to make sure you do not go out of bounds there.

Also, your str=null; line needs to be changed to str="";, otherwise you get the String "null" in your result.

Your original solution, fixed with minor changes:

String s ="Hello how are you";
String str = "";
int i=0;

String strArr[] = new String[100];
int j=0;


while(j<=s.length()-1)
{
  if(s.charAt(j)!=' ')
  {
    while(j<=s.length()-1 && s.charAt(j)!=' ') // Added a check here
    {
      str = str+s.charAt(j);
      j++;
    }
  }

  j++;
  if(!str.equals(null))
  {
    strArr[i++] = str;
    str=""; // Changed this line
  }
}

Note: I would rather not refactor your code for you, but I do agree with the other commenters; you could have handled this with a way more readable and bug-resistant algorithm. I will leave it to you to figure that out, since it isn't what you were asking for.

Upvotes: 0

Dhiogo Boza
Dhiogo Boza

Reputation: 309

Hello I make some adaptations in your initial code and I believe that here is a simpliest solution:

String s ="Hello how are you";
String str = "";
int i = 0;

String strArr[] = new String[100];
int j = 0;

while(j < s.length()) {
    if(s.charAt(j) == ' ') {
        if (!str.isEmpty()) {
            strArr[i++] = str;
        }
        str = "";
    } else {
        str += s.charAt(j);
    }

    j++;
}
if (!str.isEmpty()) {
    strArr[i++] = str;
}

Here it is necessary only one loop to split the string.

Upvotes: 1

xtratic
xtratic

Reputation: 4699

This code is all manner of bugged up.. if you just want an array of the words separated by spaces then you can use this:

String s = "Hello how are you";
String[] words = s.split(" +");
System.out.println(String.join(", ", words));

If you really don't want to use split, then this will do the same thing. It may have a nested loop but it's still linear time since they're incrementing the same counter:

String s = "Hello how are you";

List<String> words = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
    // increment until you find the start of a word, a non-space
    if (s.charAt(i) != ' ') {
        int wordStart = i;
        // increment to the end of the word, a non-space or end of string
        while ((i < s.length()) && (s.charAt(i) != ' ')) { i++; }
        // add the word to your list
        words.add(s.substring(wordStart, i));
    }
}

System.out.println(words);

// if you really need it as an array
String[] wordsArray = words.toArray(new String[0]);

Upvotes: 1

Andronicus
Andronicus

Reputation: 26066

I this loop:

while(s.charAt(j)!=' ')
{
    str = str+s.charAt(j);
    j++;
} 

you're incrementing j without any control. You should add a check to while loop: while(j < s.length() && s.charAt(j) != ' ').

P.S.: You have 2 ifs and whiles with same conditions, I'd refactor.

P.S.2: str.equals(null) will always be false if str is not null.

P.S.3: you can use String#split for this - much more error prone.

Upvotes: 0

Joshua Burt
Joshua Burt

Reputation: 76

I will start this by saying I'm not an expert, but I believe I know what is going wrong here.

while(j<=s.length()-1)              
{       
    if(s.charAt(j)!=' ')
    {
        while(s.charAt(j)!=' ') //Will constantly be true as long as the previous if statement is true
        {
            str = str+s.charAt(j);
            j++; //
        }           
    }

    j++;
    if(!str.equals(null))
    {
        strArr[i++] = str;
        str=null;
    }
}

Essentially you're continuously increasing j on your second while loop. I suggest using a for loop instead:

for(j = 0; j < s.length(); j++) {
    if(s.charAt(j)!=' ') {
            str = str+s.charAt(j);
        }
    if(!str.equals(null) {
        strArr[i++] = str;
        str=null;
    }
}

If anyone sees an issue in this, please let me know and I will correct it.

Upvotes: 0

Related Questions