i have been given an problem to solve in class where i need to take in a string and then print out how many numbers are in the string. A word is defined as only containing the characters a-z and A-Z. I cannot use split().
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String sentence;
String currentWord;
int wordCount;
int spacePos;
int validChar;
System.out.print("Please enter a sentence: \n");
sentence = input.nextLine() + " ";
spacePos = sentence.indexOf(" ");
wordCount = 0;
currentWord = sentence.substring(0, spacePos);
validChar = 0;
while(spacePos > -1)
{
for(int i = 0; i < currentWord.length(); i++)
{
int j = currentWord.charAt(i);
if( j >= 'a' && j <= 'z' || j >= 'A' && j <= 'Z')
{
validChar++;
}
}
if( validChar == currentWord.length() )
{
wordCount++;
}
currentWord = currentWord.substring(spacePos);
}
System.out.println("The number of words in this string is " + wordCount + "\n\n");
input.close();
}
}
}
this is what i have so far but i am getting an error saying that currentWord = currentWord.substring(spacePos);
is
java.lang.StringIndexOutOfBoundsException: String index out of range: -5
EDIT: My problem wasnt just with the error but with the logic too, but i spent a good couple hours on paper and rewrote it from scratch and solved it. Here is my updated code without using .split()
.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String currentWord;
String sentence;
int spacePos;
int wordCount;
int validChar;
System.out.print("Please enter a sentence: \n");
sentence = input.nextLine() + " ";
spacePos = sentence.indexOf(" ");
currentWord = sentence.substring(0, spacePos);
wordCount = 0;
validChar = 0;
if( spacePos == 0 )
{
spacePos = 1;
}//end of if
for( int i = 0; i < sentence.length(); i++ )
{
// VALIDATES IF A WORD IS A WORD
for(int j = 0; j < currentWord.length(); j++)
{
if( currentWord.charAt(j) > 'a' && currentWord.charAt(j) < 'z'
|| currentWord.charAt(j) > 'A' && currentWord.charAt(j) < 'Z')
{
validChar++;
}//end of if
if( validChar == currentWord.length() )
{
validChar = 0;
wordCount++;
}//end of if
}//end of for
// ROMOVES PREVIOUS WORD
sentence = sentence.replace(currentWord + " ", "");
currentWord = sentence.substring(0, spacePos);
spacePos = sentence.indexOf(" ") + 1;
} //end of for
System.out.println("\n\n FINAL WORD COUNT --->\t\t" + wordCount + "\n");
input.close();
}