From 56ca966d478795fdbc444779aa8e37f153f4ba65 Mon Sep 17 00:00:00 2001 From: MarcHines Date: Wed, 31 May 2017 19:59:11 -0400 Subject: [PATCH] Update countwords.java Easier to read. --- countwords.java | 39 +++++++++++++++------------------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/countwords.java b/countwords.java index c11540de..5d18ae52 100644 --- a/countwords.java +++ b/countwords.java @@ -4,30 +4,21 @@ import java.util.Scanner; * You enter a string into this program, and it will return how * many words were in that particular string * - * @author Unknown + * @author Marcus * */ -class CountTheWords -{ - /** - * The main method - * - * @param args Command line arguments - */ - 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 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; } - System.out.println("Number of words in the string = "+count); - sc.close(); - } -} \ No newline at end of file + + }