-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab1WordCounterAttempt2.java
More file actions
83 lines (66 loc) · 2.21 KB
/
Lab1WordCounterAttempt2.java
File metadata and controls
83 lines (66 loc) · 2.21 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package instilLabQuestions;
import java.io.*;
import java.util.HashMap;
public class Lab1WordCounterAttempt2 {
static BufferedReader buffer = null;
//static Scanner keyboard = new Scanner(System.in);
static String enterFileName() {
String retVal = null;
System.out.println("Please Enter File ");
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
try {
retVal= buffer.readLine();
} catch (IOException e) {
}
return retVal;
}
static String readFile(String filepath)
{
String fileContent = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filepath));
fileContent = br.readLine();
while (fileContent != null) {
String temp = br.readLine();
if (temp == null) {
break;
} else {
fileContent += " " + temp;
}
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
static String [] TokeniseInput (String content) {
String [] tokens = content.split(" ");
return tokens;
}
static HashMap<String,Integer> wordCount(String[] tokens) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String token : tokens)
{
if (map.containsKey(token)) {
int count = map.get(token).intValue();
map.put(token, new Integer(count + 1));
}
else {
map.put(token, new Integer(1));
}
}
return map;
}
public static void main(String[] args) {
String filename = enterFileName();
String content = readFile(filename);
String [] tokens = TokeniseInput(content);
HashMap<String,Integer> wordCountMap = wordCount(tokens);
for (String key : wordCountMap.keySet())
{
int value = wordCountMap.get(key).intValue();
System.out.println(key + " " + value);
}
}//main
}//class