Question

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);
    }
} 
Was it helpful?

Solution 2

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.

OTHER TIPS

Java starts indexes from 0, so that means that the last character in the string will be at length() - 1. Therefore, if you have a string with 12 characters, the last character will be at index 11. So you have to replace the less than equals sign here:

for (int i = 0; i <= input.length(); i++) {

to a less than sign like this:

for (int i = 0; i < input.length(); i++) {

So you only get all of the characters up to input.length() - 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top