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.

Dani AI

Generated

Quick diagnosis and what to change

The core problem is twofold: a logic bug in the loop condition (the second loop never runs), and an inherently brittle counting strategy (increment on spaces and punctuation). Counting spaces alone breaks on multiple spaces, tabs/newlines, leading/trailing whitespace, and it mishandles contractions and punctuation attached to words. Also avoid using a class field as an accumulator unless you explicitly reset it each call — use a local variable inside the counting method.

A reliable approach (recommended)

Use Java's BreakIterator which is designed for word/sentence boundaries and handles many edge cases (contractions, punctuation attached to words, locale issues). Example word-count routine:

import java.text.BreakIterator;
import java.util.Locale;

public static int countWords(String text) {
    if (text == null || text.isEmpty()) return 0;
    BreakIterator boundary = BreakIterator.getWordInstance(Locale.US);
    boundary.setText(text);
    int start = boundary.first();
    int words = 0;
    for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
        String token = text.substring(start, end);
        for (int i = 0; i < token.length(); i++) {
            if (Character.isLetterOrDigit(token.charAt(i))) {
                words++;
                break;
            }
        }
    }
    return words;
}

If you prefer a simpler method

Split on whitespace, trim punctuation from token ends, and skip empties. This is simpler and fast for plain English text but less accurate for tricky cases:

public static int simpleWordCount(String text) {
    if (text == null || text.trim().isEmpty()) return 0;
    String[] tokens = text.trim().split("\\s+");
    int count = 0;
    for (String t : tokens) {
        String clean = t.replaceAll("^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$", "");
        if (!clean.isEmpty()) count++;
    }
    return count;
}

Notes and tips

  • For sentences use BreakIterator.getSentenceInstance(...) rather than counting punctuation characters yourself.
  • Reset counters or use local variables; do not let previous calls accumulate state.
  • Be aware of edge cases: abbreviations (Mr.), decimals (3.14), ellipses, hyphenated words, and different locales.
  • See the BreakIterator Javadoc for details: BreakIterator (Javadoc).

This will give more accurate, maintainable results than counting spaces and manually looking for punctuation. : the above fixes the loop/accumulator issues and handles common corner cases.

I just figured a way to do it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.