Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Having problems with String out of bounds errors

  1. #1
    Junior Member
    Join Date
    Oct 2009
    Posts
    26
    Thanks
    5
    Thanked 2 Times in 2 Posts

    Default Having problems with String out of bounds errors

    Ok, well I am making a program which takes input, changes all multiple blanks into a single blank space, and creates a new line after a sentence is declared. A sentence will be declared by finding where the String has a "! . or ?" character followed by a blank space. It will also capitalize the first letter of the sentences.

    For example, if the user entered:

    this is an. example of desired?input! hurray.

    The output would be:

    This is an.
    Example of desired?input!
    Hurray.

    So, I created a parseSentence() method to do the conversions required for me, but I keep running into an out of bounds error.

    First, here is the method:

    public String parseSentence(String sent) {
        	String temp;
        	for (int x = 0; x <= sent.length(); x ++) {
        		if ((sent.indexOf(sent.charAt(x)) + 1) != sent.length()){
        			if ((sent.charAt(x) & sent.charAt(x + 1)) == ' ') {
        				temp = sent.charAt(x + 1) + "";
        				sent = sent.replaceFirst(temp, "");
        			}
        			if (((sent.charAt(x) == '.') || (sent.charAt(x) == '!') || (sent.charAt(x) == '?')) & (sent.charAt(x + 1) == ' ')) {
        				temp = sent.charAt(x + 1) + "";
        				sent = sent.replaceFirst(temp, "\n");
        				sent = sent.replace(sent.charAt(x + 2), Character.toUpperCase(sent.charAt(x + 2)));
        			}
        		}
        	}
        	return sent;
        }

    And this is the error after the input:

    Please enter a sentence:
    this    program    processes.     text files and creates! a  new  file?with * the       following.
    [B]Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 75
        at java.lang.String.charAt(String.java:686)
        at TextFileProcessorDemo.parseSentence(TextFileProcessorDemo.java:31)
        at TextFileProcessor.main(TextFileProcessor.java:36[/B])

    I thought it might have something to do with the loop executing towards the end of the String, and when charAt(x + 1) is trying to be found, there is nothing in that index so it would give the error. I tried to solve this by adding the first if statement, which I meant to make the loop essentially stop if the current value of x is equal to the length of the String. Though I know this would only be a partial fix for the (x + 1) parameters, and not the (x + 2) later on, but at least I was trying to make headway.

    However, that fix still didn't solve my problem.

    Any ideas?

    Thanks!


  2. #2
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Having problems with String out of bounds errors

    Hello, the thing is that when you are playing with the individual characters of a string you need to remember that the charAt position is a zero based index.

    Therefore this wont really work.

    x <= sent.length()

    Because you are looping up until the length of the string. Lets say we have a string with a length of 5 characters and you loop from 0 to 5 inclusively and the charAt is a zero based index, when you reach x = 5 and you try to get charAt(5) you will get a StringOutofBoundsException because there is no index 5 because the fifth character is actually in index 4.

    Example:

    test
    0123

    The string above is of length 4 but the indexes only go to 3. To fix this you need to change your loop to only loop while x is lower than the length.

    for (int x = 0; x < sent.length(); x ++) {

    Now that will solve the immediate problem, however I've also noticed somewhere in your code where you do this.

    sent.charAt(x + 1)

    This will also give you a StringOutofBoundsException if x is the last index in the string because x + 1 will be outside of the scope or bounds.

    I hope this gives you a clue on what you need to do to sort out your issues. If you still need to use the x + 1 check just do a check first to make sure that x isnt the last index.

    // Json

  3. #3
    Junior Member
    Join Date
    Oct 2009
    Posts
    26
    Thanks
    5
    Thanked 2 Times in 2 Posts

    Default Re: Having problems with String out of bounds errors

    Sorry for the delay, and thanks for the advice. I was able to get it to work, for the most part.

    Now I have the problem that when multiple spaces are detected within the array, it seems to leave an extra space when changing one of them to a return character. For example when I type "test. sent." (with two spaces after the first period) I want it to put:

    Test.
    Sent.

    But instead, I'm getting:

    Test.
     sent.

    Here is my revised method, if anyone can help, that would be much appreciated. Thanks!

        public char[] parseSentence(char[] sent) {
        	sent[0] = Character.toUpperCase(sent[0]);
        	for (int x = 0; x < sent.length; x ++) {
        		if (x != (sent.length - 1)){
        			if (((sent[x] == '.') || (sent[x] == '!') || (sent[x] == '?')) && (sent[x + 1] == ' ')) {
        				sent[x + 1] = '\n';
    					if (sent[x + 2] == ' ')                // SEE NOTE
    						sent[x + 2] = '\u0000';     // SEE NOTE
    					sent[x + 2] = Character.toUpperCase(sent[x + 2]);
        			}
        			if ((sent[x] == ' ') && (sent[x + 1] == ' ')) {
        				sent[x] = '\u0000';
        			}
        		}
        	}
        	return sent;
        }

    NOTE: The portion of code:

    if (sent[x + 2] == ' ')
         sent[x + 2] = '\u0000';

    is just something I threw in the try. It doesn't appear to have any effect on the program, but I was trying something at least. Thanks!

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Having problems with String out of bounds errors

    A simple solution is to convert to a String, then use the .trim() method.

Similar Threads

  1. GuessWhat- same errors repeated 4 times?
    By iank in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 5th, 2009, 08:32 PM
  2. Replies: 2
    Last Post: November 3rd, 2009, 06:28 AM
  3. Errors with LispList
    By Newoor in forum Collections and Generics
    Replies: 10
    Last Post: October 25th, 2009, 05:25 PM
  4. [SOLVED] Error of "cannot find symbol"
    By big_c in forum File I/O & Other I/O Streams
    Replies: 31
    Last Post: April 9th, 2009, 12:20 PM
  5. Ambiguity and non-static variable reference error in java
    By jenseits in forum AWT / Java Swing
    Replies: 5
    Last Post: December 8th, 2008, 07:04 PM