Update countwords.java

Easier to read.
This commit is contained in:
MarcHines 2017-05-31 19:59:11 -04:00 committed by GitHub
parent 3907716e1f
commit 56ca966d47

View File

@ -4,30 +4,21 @@ 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 public static void main(String[] args){
{ Scanner input = new Scanner(System.in);
/** System.out.println("Enter your text: ");
* The main method String str = input.nextLine();
*
* @param args Command line arguments System.out.println("Your text has " + wordCount(str) + " word(s)");
*/ input.close();
public static void main(String args[])
{
System.out.println("Enter the string");
Scanner sc = new Scanner(System.in);
String s=sc.nextLine();
int count = 1;
for (int i = 0; i < s.length()-1; i++)
{
if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
{
count++;
} }
public static int wordCount(String s){
if(s.isEmpty() || s == null) return -1;
return s.trim().split("[\\s]+").length;
} }
System.out.println("Number of words in the string = "+count);
sc.close();
} }
}