Skip to content

Commit 6ff4a1f

Browse files
Merge pull request #53 from MarcHines/patch-2
Update countwords.java
2 parents e8e6550 + abc0e45 commit 6ff4a1f

File tree

1 file changed

+17
-24
lines changed

1 file changed

+17
-24
lines changed

countwords.java

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,23 @@
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+
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;
2924
}
30-
System.out.println("Number of words in the string = "+count);
31-
sc.close();
32-
}
33-
}
25+
26+
}

0 commit comments

Comments
 (0)