patternjavaMinor
Finding the number of words from a user input string or a text file
Viewed 0 times
numberthefileuserwordstextinputfindingfromstring
Problem
I'm new to Java and is trying to solve the beginners problem of finding out the number of words in an user input string or a text file. I was just wondering if there are any alternatives to any of the steps that can improve efficiency as well as simplicity.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class WordsCount{
public static void main(String[] args) {
try(Scanner sc1 = new Scanner(System.in)){
String userInputOrTextFile = sc1.next();
if (userInputOrTextFile.equalsIgnoreCase("userInput")){
WordsCount.countUserInput();
} else {
WordsCount.countTextFile();
}
}
}
private static void countUserInput() {
try(Scanner sc1 = new Scanner(System.in)){
String s1 = sc1.nextLine();
System.out.println(s1.split(" ").length + " words in the user input sentence." );
}
}
private static void countTextFile() {
int countingWords = 0;
try(Scanner sc1 = new Scanner(new BufferedReader(new FileReader("xanadu.txt")))){
while(sc1.hasNext()){
sc1.next();
countingWords++;
}
} catch (FileNotFoundException e){
System.out.println("File not found");
}
System.out.println(countingWords + " words are in the xanadu.txt file");
}
}Solution
On Regex use
To correctly split on white space and count the amount of words you want, use
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.
To correctly split on white space and count the amount of words you want, use
trim().split('\\s+').lengthYou 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.
Context
StackExchange Code Review Q#118593, answer score: 5
Revisions (0)
No revisions yet.