-
Notifications
You must be signed in to change notification settings - Fork 0
/
Taskno.2
54 lines (48 loc) · 1.85 KB
/
Taskno.2
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
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 'text' to input text or 'file' to input a file path:");
String inputType = scanner.nextLine();
if (inputType.equalsIgnoreCase("text")) {
System.out.println("Enter text:");
String inputText = scanner.nextLine();
countWordsInText(inputText);
} else if (inputType.equalsIgnoreCase("file")) {
System.out.println("Enter file path:");
String filePath = scanner.nextLine();
try {
String fileContent = readFileContent(filePath);
countWordsInText(fileContent);
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
} else {
System.out.println("Invalid input type. Please enter 'text' or 'file'.");
}
scanner.close();
}
private static void countWordsInText(String text) {
String[] words = text.split("[\\s\\p{Punct}]+");
int wordCount = 0;
for (String word : words) {
if (!word.isEmpty()) {
wordCount++;
}
}
System.out.println("Total words in the text/file: " + wordCount);
}
private static String readFileContent(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
return content.toString();
}
}