0

Hey everyone, I am trying to write a code which would read a file and print the number of words and sentences in each of them. I want to take everything step by step; so I am making sure that all my methods work perfectly before proceeding. In the code below, all the methods work fine except the getNumberOfWords one. Judge it yourself.

public class TextReader {
    
    private String theText;
    
    private int numberOfWords, numberOfSentences;

	// the constructor(still incomplete)
	public TextReader()
	{
		theText = null;
	}
	
	public void theText(String file)
	{
		theText = file;
	}
	
	/* Calculates the number of words in the text
	 *@return numberOfWords the number of words
	 */
	public int getNumberOfWords()
	{
		
		for (int i = 0; i < theText.length(); i++)
		{
			if (theText.charAt(i) == ' ') 
			{
				numberOfWords += 1; 
			}		
		}
		
		for (int i = 0; i == theText.length(); i++) 
		{
			if (theText.charAt(i) == '.' || theText.charAt(i) == ':' || theText.charAt(i) == ';' || theText.charAt(i) == '?' || theText.charAt(i) == '!')  
			{
				numberOfWords += 1;
			}
		}
		return numberOfWords;
	}
	
	/* Calculates the number of sentences in the text
	 *@return numberOfSentences the number of sentences
	 */
	public int getNumberOfSentences()
	{
		for (int n = 0; n < theText.length(); n++)
		{
			if (theText.charAt(n) == '.' || theText.charAt(n) == ':' || theText.charAt(n) == ';' || theText.charAt(n) == '?' || theText.charAt(n) == '!')
			{
				numberOfSentences += 1; 
			}
		}
	return numberOfSentences;
	}
}

the main class:

public class TextRunner {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
		TextReader myReader = new TextReader();
		
		String justTesting = "I am trying this. Does it work? No, it doesn't.";
		myReader.theText(justTesting);
		System.out.println("The string is       : " + justTesting);
		System.out.println("Number of words     : " + myReader.getNumberOfWords());
		System.out.println("Number of sentences : " + myReader.getNumberOfSentences());
    }
}

the output:

The string is       : I am trying this. Does it work? No, it doesn't.
Number of words     : 9 [It is 10 not 9]
Number of sentences : 3

could anyone help me? thanks in advance.

1
Contributor
1
Reply
5
Views
7 Years
Discussion Span
Last Post by theStruggler
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.