1

I am trying to accept an input and then turn that input into Camel Case in a method using recursion, but for some reason, it keeps saying that line starting with "String a" has an error and can't output the data. Can you tell me what I did wrong?

    public static String toCamelCase(String toCamel) {
        String[] arr = toCamel.toLowerCase().trim().split(" ");
        int i=arr.length-1;
        if(i==0) {
            return arr[i];
        }else if(i>0) {
            String a = arr[i].toUpperCase().substring(0, 1);
            arr[i]= a + arr[i].substring(1);
            return toCamelCase(arr[i-1])+arr[i];
        }
        return Arrays.toString(arr);

And this is the error message/output.

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
Mineo
  • 19
  • 3
  • `i` is the length of your array and then you're using to index it. Of course it will return `IndexOutOfBoundsException`. You've messed up with your entire logic! Also, it's a good practice to put the exception log as well when you ask questions so that people can find the bug easier :) – Nagabhushan S N Feb 10 '19 at 02:26
  • So what should I do instead? – Mineo Feb 10 '19 at 02:27
  • Please check the answer referred. There are a couple of libraries functions to achieve this. If you want to implement it yourself, check this answer: https://stackoverflow.com/a/1143979/3337089 – Nagabhushan S N Feb 10 '19 at 02:29

0 Answers0