substring StringIndexOutOfBoundsException
Hi guys,
I am trying to count the number of words in a sentence. My method of doing this is as follows;
1.Accept a sentence from the user using System.in
2.Scan the user input and store as a String.
3.Scan the String.
4.Enter while loop that is entered as long as the sentence has another String.
Within while loop;
5.Next word in sentence is stored as a String.
6.Get length of that word.
7.Create a substring minus the previous word.
8.Increment an int variable to count the words.
Hers's my code;
import java.util.Scanner;//Imports Scanner class
public class Test//Start of public class
{
public static void main(String[] args)//Start of main method
{
Scanner input = new Scanner(System.in);//Sets up new Scanner object. Reads from system
System.out.print("user: Tell me about yourself"); //Creates input from system
String Sentence = input.nextLine();//Store input as a String
Scanner sentence = new Scanner(Sentence);//Scan that String
int wordcount = 0;
int length;
int fullLength;
while(sentence.hasNext())
{
String word = sentence.next();//Store next word in sentence as a String
length = word.length();//Get length of that word
fullLength = Sentence.length();//Length of full sentence
Sentence = Sentence.substring(length+1, fullLength);//Create new sentence minus the previous word
wordcount++;//Increment int variable
}
System.out.println("This sentence has "+wordcount+" words");
System.exit(0);
}
}
My problem is I get an outOfBounds exception when creating the substring. I can't see how this is as the begin and end index are within the length of the String.
Any help would be much appreciated.
Kind Regards,
DD.
Re: substring StringIndexOutOfBoundsException
problem solved.
When i changed length+1 where the substring is created to just length it works. Not too sure why. If anyone could enlighten, it would be helpful
Re: substring StringIndexOutOfBoundsException
If the index goes past the end of the String, the method will throw the exception. If the index stays within the bounds of the characters in the String, there is no exception thrown.
Remember that indexes start at 0 and go to the length-1