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!