Finding the number of words from a user input string or a text file
On Regex use
To correctly split on white space and count the amount of words you want, use trim().split('\\s+').length
You want to split on all whitespace, not just a single ones in between, and you need to trim first because otherwise you'll also get inaccurate results for any input beginning with spaces.
This will also work just as well for your file input -- not too sure why you use a different method.