-1

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); 
    }
}
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • 1
    Check your code's logic. If `Words.charAt(i)==' '` then `Character.isDigit(Words.charAt(i))` is false (a character cannot be a space and a digit at the same time). Better yet, use `String.split()` method to separate words. – DYZ Jan 19 '23 at 04:09
  • You want to [split](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String)). That will give you an array of `String`. You can then iterate through the array, testing the first character of each element. If you want to split on any whitespace character, see the checked answer at https://stackoverflow.com/questions/225337/how-to-split-a-string-with-any-whitespace-chars-as-delimiters – Old Dog Programmer Jan 19 '23 at 04:11
  • 1
    your logic doesn't make sense: a char at any position ca have exactly one value :) use a piece of paper or a debugger to work through it – kleopatra Jan 19 '23 at 04:12

2 Answers2

1

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); 
}
Tyler Liu
  • 989
  • 1
  • 6
  • 7
0

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138