Count words
# Topic
Input stream
# Problem
Count words
Read an input text from the console and print the number of words. By word we mean a sequence of characters separated by one or several spaces.
If the input is empty or there are no characters except spaces, print 0.
# Hint & Explain
Make sure to follow this order: 1- use reader.readLine() to read the input 2 - use trim() on the input 3- CLOSE THE READER with reader.close() 4- use if statement: 5- if string.isEmpty() then ... 6- else, split("\s+") string into an array => String[] string = input.split("\s+") then print count
# Solution
# Other solution 1
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// start coding here
String input = reader.readLine().trim();
reader.close();
if (input.isEmpty()) {
System.out.println(0);
} else {
String[] array = input.split("\\s+");
System.out.println(array.length);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Other solution 2
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// start coding here
int inputAsInt = reader.read();
int count = 0;
final int intSpace = 32;
final int intDec = 10;
boolean flag = false;
while (inputAsInt != -1) {
if (inputAsInt != intSpace && !flag) {
count++;
flag = true;
} else if (inputAsInt == intSpace) {
flag = false;
}
inputAsInt = reader.read();
if (inputAsInt == intDec) {
break;
}
}
System.out.println(count);
reader.close();
}
}
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
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
编辑 (opens new window)
上次更新: 2022/09/25, 10:41:23