0

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.

2
  • Myself, I'd use String#split(...) method and would be able to solve this in just a few lines of code. Commented Sep 27, 2012 at 22:09
  • sentence.indexOf() will return -1 if " " is not found and space is passed into sentence.substring(): check space. Commented Sep 27, 2012 at 22:10

4 Answers 4

2

You need to check that the index of space here. String.indexOf() will return -1 if the search string is not found.

int space = sentence.indexOf(" ");
int endSpace = space + 1;
if (space != -1) {
    sentence = sentence.substring(0, space) + "\n"
            + sentence.substring(endSpace, sentence.length());
}
Sign up to request clarification or add additional context in comments.

3 Comments

For clarification, indexOf() will return -1 if it can not find the string.
Thanks guys! I guess it's a little late to ask, but is there anything wrong with the way I posted this? I understand I should've pointed out the line I was referring to..
Ideally yes its good to point out the line that the app fails on but you did post a sccee which helps a lot. :)
1

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.

 if (wordCount >= 4){
            for (int i = 0; i <charCount-3; i++){
                    int space = sentence.indexOf(" ");
                    if(space==-1){// check if space is -1
                        break;
                    }   
                    System.out.println(i+ " " + space);
                    int endSpace = space + 1;
                    sentence = sentence.substring(0, space)
                            + "\n"
                         + sentence.substring(endSpace, sentence.length()-1);
                    }
                    System.out.println(sentence);

Comments

0
  • Myself, I'd use String#split(...) method and would be able to solve this in just a few lines of code.
  • But if you must do it this way, don't do a for loop or loop charCount number of times since charCount is the size of the String and you certainly don't want to loop this many times. It just doesn't make sense. Rather, you want to loop the number of spaces, not the number of characters, which brings me to the next recommendation:
  • Use a while loop, not a for loop and loop until -1 is returned by the indexOf(...) method. In other words, let Java do the hard work of figuring out when the String has run out of spaces rather than you guess.

Comments

0

My solution does not check for words that are not actually words,

import java.util.Scanner;

public class SentenceWordCount {
    Scanner s = new Scanner (System.in);
    int wordCount;

    public SentenceWordCount() {
        System.out.println("Enter a sentence");

        String sentenceEntered = s.nextLine();
        String[] brokenSentence = sentenceEntered.split(" ");

        wordCount = brokenSentence.length;

        if(wordCount > 3){
        for(String s : brokenSentence){
                System.out.println(s);
            }
        }

        System.out.println("Number of words equals : " + wordCount);
    }
}

Cheers,

Jamie

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.