Skip to content

Commit 56ca966

Browse files
authored
Update countwords.java
Easier to read.
1 parent 3907716 commit 56ca966

File tree

1 file changed

+15
-24
lines changed

1 file changed

+15
-24
lines changed

countwords.java

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,21 @@
44
* You enter a string into this program, and it will return how
55
* many words were in that particular string
66
*
7-
* @author Unknown
7+
* @author Marcus
88
*
99
*/
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+
public static void main(String[] args){
11+
Scanner input = new Scanner(System.in);
12+
System.out.println("Enter your text: ");
13+
String str = input.nextLine();
14+
15+
System.out.println("Your text has " + wordCount(str) + " word(s)");
16+
input.close();
17+
}
18+
19+
public static int wordCount(String s){
20+
if(s.isEmpty() || s == null) return -1;
21+
return s.trim().split("[\\s]+").length;
2922
}
30-
System.out.println("Number of words in the string = "+count);
31-
sc.close();
32-
}
33-
}
23+
24+
}

0 commit comments

Comments
 (0)