-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordCharacterCount.java
More file actions
27 lines (24 loc) · 937 Bytes
/
Copy pathWordCharacterCount.java
File metadata and controls
27 lines (24 loc) · 937 Bytes
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
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordCharacterCount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter file name: ");
String fileName = input.nextLine();
input.close();
File file = new File(fileName);
int wordCount = 0, charCount = 0;
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNext()) {
String word = scanner.next();
wordCount++;
charCount += word.length();
}
System.out.println("Total Words: " + wordCount);
System.out.println("Total Characters (excluding spaces): " + charCount);
} catch (FileNotFoundException e) {
System.out.println("Error: File not found.");
}
}
}