Search code examples
javastringcamelcasing

Java error about turning sentence into camelCase


I'm starting to code and trying to do a challenge of turning a sentence into camelCase. After some experimenting on my own, got to the following code:

package teste;

import java.util.Scanner;

public class Teste {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Insert the sentence to be turned into camelCase: ");
        String entry = keyboard.nextLine();
        System.out.print("Insert the character that is used as space: ");
        String space = keyboard.nextLine();
        char current;
        char next;
        String output = null;
        for (int i=0; i<=entry.length(); i++){
            current = entry.charAt(i);
            next = entry.charAt(i+1);
            if (i == entry.length()){
                output += Character.toLowerCase(current);
            } else if (entry.substring(i, i+1).equals(space)){
                output += Character.toUpperCase(next);
                i++;
            } else {
                output += Character.toLowerCase(current);
            }
        }
        
        System.out.println("This sentence in camelCase is: " + output);
    }

}

There is an error I can't seem to avoid with the last index of the input, even with the first if structure made especially for it, and I can't find out why. Could anyone explain to me what I did wrong?


Solution

  • you should avoid StringIndexOutOfBoundsException exception in line 15 "entry.charAt(i+1)", This code will fix your error.

    import java.util.Scanner;
    
    public class Teste {
    
    
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Insert the sentence to be turned into 
        camelCase: ");
        String entry = keyboard.nextLine();
        System.out.print("Insert the character that is used as 
        space: ");
        String space = keyboard.nextLine();
        char current;
        char next;
        String output = "";
        for (int i=0; i<entry.length()-1; i++){
            current = entry.charAt(i);
            next = entry.charAt(i+1);
            if (i == entry.length()-2){
                output += Character.toLowerCase(current);
            } else if (entry.substring(i, i+1).equals(space)){
                output += Character.toUpperCase(next);
                i++;
            } else {
                output += Character.toLowerCase(current);
            }
        }
        //here we test the last character
        int len=entry.length();
        current = entry.charAt(len-1);
        if(!entry.substring(len-1, len).equals(space)){
            output += Character.toLowerCase(current);
        }
    
        System.out.println("This sentence in camelCase is: " + 
        output);
        }
    }