JavaAlgorithms/countwords.java

27 lines
659 B
Java
Raw Normal View History

2017-04-09 12:56:56 +08:00
import java.util.Scanner;
/**
* You enter a string into this program, and it will return how
* many words were in that particular string
*
2017-06-01 07:59:11 +08:00
* @author Marcus
*
*/
class CountTheWords{
2017-06-01 07:59:11 +08:00
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your text: ");
String str = input.nextLine();
System.out.println("Your text has " + wordCount(str) + " word(s)");
input.close();
}
public static int wordCount(String s){
if(s.isEmpty() || s == null) return -1;
return s.trim().split("[\\s]+").length;
2017-04-08 20:56:06 +08:00
}
2017-06-01 07:59:11 +08:00
}