This program is supposed to take a string e.g "apples are green and apples are red as well" and return the length of the shortest word in that string in the case mentioned above it would return int 2. howver the value that is returns is not correct.
public static int findShort(String s) {
String newStrings[] = s.split(" ");
int shortest_word_length = 10000;
int temporary_length;
for(int i=0;i<=(newStrings.length);i ){
temporary_length = (newStrings[i].split("")).length;
if (temporary_length<=shortest_word_length){
shortest_word_length = temporary_length;
}
}
return shortest_word_length;
}
I have gone over the code several times and cannot seem to find out what is wrong with it.
CodePudding user response:
I've tried your code and this line throws an IndexOutOfBoundsException
for(int i=0; i <= (newStrings.length); i ){
It should be
for(int i=0; i < (newStrings.length); i ){
CodePudding user response:
Change the For loop to this:
for(int i=0;i<(newStrings.length);i )
When you give "<=" it's checking the out-of-bound position.