Tafadzwa Chikudo
Tafadzwa Chikudo

Reputation: 53

An array out of bounds error

I want to write code that splits a string into separate substrings each with 3 characters and assign them to a string array for example the string "abcdefg" can be spit to "abc", "bcd", "cde", "efg" and these are assigned to a string array. I have the following code which is getting an error:

String[] words = new String[] {};
String sequence = "abcdefg";
int i;

for(i = 0; i <= sequence.length()-3; i++) {          

    words[i] = sequence.substring(i, 3+i);
    System.out.println(words[i]);
}

Upvotes: 1

Views: 91

Answers (3)

Mujtaba Hasan
Mujtaba Hasan

Reputation: 112

Use the following code instead:

      String sequence="abcdefg";
      String[] words=new String[sequence.length()-2];
      int i;

      for(i=0;i<=(sequence.length()-3);i++){        
         words[i]=sequence.substring(i,3+i);
         System.out.println(words[i]);
    }

Or you could use arraylist of strings

Upvotes: 1

Vla
Vla

Reputation: 25

You could get the length from the sequence string divided by the number of characters you want to store in order to know how big should your array be. For instance

String sequence="abcdefg";
int myLength = sequence.length/3;
String[] words=new String[myLength];

And then you could use that length to populate the array

 for(i=0;i<=myLength;i++){          

               words[i]=sequence.substring(i,3+i);

               System.out.println(words[i]);
    }

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

String[] words=new String[] {}; // empty array

you have empty array.

words[i] // when i=0

there is no index in empty array match with 0th index.

Solution.

You can define the size of array at the moment you are define the array. The best way is get the length from sequence

String sequence="abcdefg";
String[] words=new String[sequence.length()];

Upvotes: 6

Related Questions