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");
}
}