Merge pull request #53 from MarcHines/patch-2

Update countwords.java
This commit is contained in:
Anup Kumar Panwar
2017-06-01 11:24:40 +05:30
committed by GitHub

View File

@ -4,30 +4,23 @@ import java.util.Scanner;
* You enter a string into this program, and it will return how * You enter a string into this program, and it will return how
* many words were in that particular string * many words were in that particular string
* *
* @author Unknown * @author Marcus
* *
*/ */
class CountTheWords class CountTheWords{
{
/** public static void main(String[] args){
* The main method Scanner input = new Scanner(System.in);
* System.out.println("Enter your text: ");
* @param args Command line arguments String str = input.nextLine();
*/
public static void main(String args[]) System.out.println("Your text has " + wordCount(str) + " word(s)");
{ input.close();
System.out.println("Enter the string"); }
Scanner sc = new Scanner(System.in);
String s=sc.nextLine(); public static int wordCount(String s){
int count = 1; if(s.isEmpty() || s == null) return -1;
for (int i = 0; i < s.length()-1; i++) return s.trim().split("[\\s]+").length;
{
if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
{
count++;
}
} }
System.out.println("Number of words in the string = "+count);
sc.close(); }
}
}