I’m writing a program for class which counts words in a string and, if the inputted string has more than 3 words, prints the sentence again, but with each word on its own line.
So I’m trying to replace spaces with \n. When I input a sentence that has more than 3 words, I get:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1937)
at lab3.main(lab3.java:32)
Here’s my code:
import java.util.Scanner;
public class lab3 {
public static void main(String [] args) {
Scanner scan = new Scanner (System.in);
int wordCount = 1;
char aChar;
System.out.println("Enter a sentence.");
String sentence = scan.nextLine();
int charCount = sentence.length();
for (int i=0; i < sentence.length(); i++){
if (sentence.charAt(i) != ' '){
continue;
} else {
wordCount++;
}
}
System.out.println("Number of words = " + wordCount);
if (wordCount >= 4){
for (int i = 0; i <= charCount; i++){
int space = sentence.indexOf(" ");
int endSpace = space + 1;
sentence = sentence.substring(0, space)
+ "\n"
+ sentence.substring(endSpace, sentence.length());
}
System.out.println(sentence);
} else {
System.out.println(sentence);
}
}
}
The problem seems to be coming from the for loop at line 31, but I don’t understand how it’s returning -1 when I input a sentence longer than 3 words. Am I using substring wrong?
Any help would be appreciated.
If you want to keep your code then you would have to do a check when doing sentence.index(” “) if it return -1. if it returns you breakout of the loop as below.
however, this isnt a good style of coding. i’d rather do with regex or other simpler methods from String API.