I am trying to replace multiple characters with white-space characters from a user inputted string. The ultimate goal of the program is to count the words and count punctuation as white space. Such as hey...man counting as two words. However, only my last replacement works, I know that why, but I do not know how to remedy the issue without creating multiple variables to do so, and I do not want to use an array either. So here is my code.
import java.util.Scanner;
class CountWords
{
public static void main(String args[])
{
Scanner scn=new Scanner(System.in);
int wordCounter=0;
String sentence;
String tempPhrase = "";
System.out.print("Enter string >>> ");
sentence = scn.nextLine();
tempPhrase = sentence.replace('.' , ' ');
tempPhrase = sentence.replace(',' , ' ');
tempPhrase = sentence.replace('!' , ' ');
tempPhrase = sentence.replace('?' , ' ');
tempPhrase = sentence.replace(':' , ' ');
tempPhrase = sentence.replace(';' , ' ');
for(int x=0; x < tempPhrase.length()-1; ++x)
{
char tempChar = tempPhrase.charAt(x);
char tempChar1 = tempPhrase.charAt(x+1);
if(Character.isWhitespace(tempChar) &&
Character.isLetter(tempChar1))
++wordCounter;
}
++wordCounter;
if (wordCounter > 1)
{
System.out.println("There are " + wordCounter + " words in the
string.");
}
else
{
System.out.println("There is " + wordCounter + " word in the
string.");
}
}
}