Home > Back-end >  How do I exclude numbers from my word count?
How do I exclude numbers from my word count?

Time:01-19

I wanted to make a word count, but exclude all of the words that started with a number.

The code below is supposed to print the number 4, but it instead prints 5.

public class WordCountLab {

    public static void main(String[] args) {
    String Words = "This is a test123 123";
       int WordCount = 1;
        for (int i = 0; i < Words.length(); i  )
        {
            if (Words.charAt(i) == ' ')
            {
                WordCount  ;
            
                if (Character.isDigit(Words.charAt(i)))
                {

                    WordCount  ;
                    
                }
            }
        }
        System.out.println("The number of words is "   WordCount); 
    }
}

CodePudding user response:

Use String.split so you don't have to check for spaces

public static void main(String[] args) {
        String words = "This is a test123 123";
        int wordCount = 0;
        for (String word : words.split(" "))
        {
            if (!Character.isDigit(word.charAt(0)))
            {
                wordCount  ;
            }
        }
        System.out.println("The number of words is "   wordCount); 
}

CodePudding user response:

The isDigit() check doesn't belong inside the if. You need to move it into the if condition, and you want to check the next character before incrementing:

if (Words.charAt(i) == ' '
        && i   1 < Words.length()
        && !Character.isDigit(Words.charAt(i   1)))
{
    WordCount  ;
}

Note that only checking digits means any other character following a space is considered a new word, including symbols or additional spaces.

  •  Tags:  
  • java
  • Related