Repository navigation
Expand file tree
/
Copy pathHomework.java
More file actions
60 lines (46 loc) · 1.72 KB
/
Copy pathHomework.java
File metadata and controls
60 lines (46 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package day21_JavaMethods;
import java.util.Scanner;
public class Homework {
// 5. Write a Java method to count all words in a string. Go to the editor
// Test Data:
// Input the string: The quick brown fox jumps over the lazy dog.
// Expected Output:
//
// Number of words in the string: 9
//advanced, put in a new class and call the method from the main method.
}
class WordCount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input the string :");
String str = in.nextLine();
int count = wordCount(str);
wordCounter(str);
if (count == 1)
System.out.println("number of words in the string: " + wordCount(str) + " word");
else
System.out.println("number of words in the string: " + wordCount(str) + " word(s)");
}
public static void mainSena(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog";
System.out.println(sentence);
wordCounter(sentence);
}
private static void wordCounter(String sentence) {
String[] arr = sentence.split(" ");
int counter = arr.length;
System.out.println("You have " + counter + " words in your sentence");
}
public static int wordCount(String sentence) {
int count = 0;
char ch[] = new char[sentence.length()];
for (int i = 0; i < sentence.length(); i++) {
Character letterChar = sentence.charAt(i);
ch[i] = sentence.charAt(i);
if (((i > 0) && (ch[i] != ' ') && (ch[i - 1] == ' '))
|| ((ch[0] != ' ') && (i == 0)))
count++;
}
return count;
}
}