File tree Expand file tree Collapse file tree 1 file changed +17
-24
lines changed Expand file tree Collapse file tree 1 file changed +17
-24
lines changed Original file line number Diff line number Diff line change 4
4
* You enter a string into this program, and it will return how
5
5
* many words were in that particular string
6
6
*
7
- * @author Unknown
7
+ * @author Marcus
8
8
*
9
9
*/
10
- class CountTheWords
11
- {
12
- /**
13
- * The main method
14
- *
15
- * @param args Command line arguments
16
- */
17
- public static void main (String args [])
18
- {
19
- System .out .println ("Enter the string" );
20
- Scanner sc = new Scanner (System .in );
21
- String s =sc .nextLine ();
22
- int count = 1 ;
23
- for (int i = 0 ; i < s .length ()-1 ; i ++)
24
- {
25
- if ((s .charAt (i ) == ' ' ) && (s .charAt (i +1 ) != ' ' ))
26
- {
27
- count ++;
28
- }
10
+ class CountTheWords {
11
+
12
+ public static void main (String [] args ){
13
+ Scanner input = new Scanner (System .in );
14
+ System .out .println ("Enter your text: " );
15
+ String str = input .nextLine ();
16
+
17
+ System .out .println ("Your text has " + wordCount (str ) + " word(s)" );
18
+ input .close ();
19
+ }
20
+
21
+ public static int wordCount (String s ){
22
+ if (s .isEmpty () || s == null ) return -1 ;
23
+ return s .trim ().split ("[\\ s]+" ).length ;
29
24
}
30
- System .out .println ("Number of words in the string = " +count );
31
- sc .close ();
32
- }
33
- }
25
+
26
+ }
You can’t perform that action at this time.
0 commit comments