Search code examples
javastringexceptionwordsbounds

Trying separate words in strings -- getting out of bounds exception on my index


I'm able to compile, but encountering runtime errors when it hits line 12 that reads char x = input.charAt(i); I don't understand why I'm getting this. Is it something to do with the position of charAt(x)?

Exception in thread "main" java.lang.StringIndexOutOfBoundsExceptio... String index out of range: 12 at java.lang.String.charAt(String.java:658) at HW12.main(HW12.java:12)

import java.util.Scanner;
public class HW12 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter a sentence in the following format: 'EnterASentenceInTheFollowingFormat.'");
        String input = keyboard.nextLine();
        StringBuilder token = new StringBuilder();

        for (int i = 0; i <= input.length(); i++) {
            char x = input.charAt(i);
            if (i == 0) {
                token.append(x);
            } else if (Character.isLowerCase(x)) {
                token.append(x);
            } else if (Character.isUpperCase(x) && i > 0) {
                token.append(" ");
            }
         }

         System.out.println(" " + token);
    }
} 

Solution

  • The index bounds of any string or array structure runs from 0 to length() - 1, such as

         input.charAt(0), ....., input.charAt(input.length() - 1) are valid
         input.charAt(input.length()) - is not valid
    

    change your for (...) loop condition to

         for(int i = 0; i < input.length(); i++){ // NOTE I have changed <= to <
             ...
         } 
    

    That should solve your issue.