Mak
Mak

Reputation: 35

Getting "Exception in thread "main" java.lang.StringIndexOutOfBoundsException" in Java

The output is supposed to be each word of the array printed backwards with their own lines

public class Main
{
    public static void main(String[] args)
    {
         String [] list = {"every", "nearing", "checking", "food", "stand", "value"};
         String reverse = "";
         int length = list.length;
         for(int j=0; j<list.length; j++)
         {
            String word = list[j];
            for ( int i = length - 1 ; i >= 0 ; i-- )
            {
                reverse = reverse + word.charAt(i);
            }
            System.out.println(reverse);
         }

    }
}

but I keep getting this message

   Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String 
    index out of range: 5
    at java.lang.String.charAt(String.java:658)
    enter code here`at Main.main(Main.java:13)

Upvotes: 2

Views: 92

Answers (4)

Kostas Tsiligkiris
Kostas Tsiligkiris

Reputation: 57

In line 11, change

int i = length-1;

to

int i = word.length()-1;

and the exception will go away.

Upvotes: 0

user10569156
user10569156

Reputation:

Verify that the provided arguments are valid in Main.java:13. Check that the provided offset points to a valid index and that the count argument does not point to indices greater than the size of the string itself.

An alternate:

public  String[]  reverseString(String[] words)
{
    String[] reverse=new String[words.length];

    for(int i=0;i<words.length;i++)
    {   
        //added for setting element as emptyString instead of null
        reverse[i] = "";
        for(int j=words[i].length()-1;j>=0;j--)
        {
            reverse[i]+=words[i].substring(j,j+1);
        }
    }
    System.out.println(Arrays.toString(reverse));
    return reverse;

}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201467

I cleaned up your code a tiny bit. Don't rely on temporary variables that do not improve the readability of your code. Do try and use for-each loops (they improve readability). Applying those two points, gives us

String[] list = { "every", "nearing", "checking", "food", "stand", "value" };
for (String word : list) {
    for (int i = word.length() - 1; i >= 0; i--) {
        System.out.print(word.charAt(i));
    }
    System.out.println();
}

which is based on your original code. Personally, I would prefer to use StringBuilder and its' reverse() method. Like,

for (String word : list) {
    System.out.println(new StringBuilder(word).reverse());
}

or in Java 8+, with a map like

Arrays.stream(list).map(s -> new StringBuilder(s).reverse())
        .forEachOrdered(System.out::println);

Upvotes: 2

Kushagra Goyal
Kushagra Goyal

Reputation: 272

for ( int i = length - 1 ; i >= 0 ; i-- )

The length value you are using above is the length of the list array, not the word.

Remember to empty reverse word after each loop:

        System.out.println(reverse);
        reverse = "";

if you don't flush you'll get:

yrev
yrevgnirae
yrevgniraegnikceh
yrevgniraegnikcehdoo
yrevgniraegnikcehdoodnat
yrevgniraegnikcehdoodnateula

instead of:

yrev
gnirae
gnikceh
doo
dnat
eula

Upvotes: 0

Related Questions