-6
public class Stringreverser {
    public char[] reverse(String a){
        char[] arre = a.toCharArray() ;
        char[] result = {} ;
        int count = 0 ;
        for(int inarre = arre.length -1 ; inarre >= 0 ; inarre = inarre -1 ){
            result[count] = arre[inarre] ;

            count+= 1 ;
        }
        return result ;
    }
    public static void main(String argv[]){
        System.out.println(new Stringreverser().reverse("hello")) ;
    }
}

This keeps giving me an - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 error. The program is supposed to take in a string and reverse and return a char array . The problem seems to be in result[count] = arre[inarre] ; . What is the problem ?

Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34
anirudh
  • 424
  • 1
  • 4
  • 12

2 Answers2

5
char[] result = {} ;

That's an empty array, so result[i] for any i will throw an exception.

You should give the output array the same length as the input array :

char[] result = new char[arre.length];
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Noticed you are trying to reverse a String, the answer above answers your question, but maybe you didn't know there is a solution without writing your own:

new StringBuilder(yourString).reverse().toString()
Shadov
  • 5,421
  • 2
  • 19
  • 38