-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordcount.java
More file actions
40 lines (35 loc) · 1.03 KB
/
Copy pathWordcount.java
File metadata and controls
40 lines (35 loc) · 1.03 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
import java.util.Scanner;
import java.io.File;
public class Wordcount {
public static void main(String[] args) {
//gets user input and puts it into lowercase
System.out.println("Input word to search for.");
Scanner top = new Scanner(System.in);
String word = top.next();
word = word.toLowerCase();
String sample;
int count = 0;
try{
//gets file input
File file = new File("myfile.txt");
Scanner in = new Scanner(file);
//while runs as long as there are more words in file
while(in.hasNext()) {
sample = in.next();
//strips punctuation
if (sample.contains(".") || sample.contains(";") || sample.contains(",")){
sample = sample.substring(0, sample.length()-1);
}
//increments count var if word equals user input
if(word.equals(sample.toLowerCase())) {
count++;
}
}
System.out.println("There are " + count + " instances of " + word + ".");
}
catch(Exception e){
//exception catch
System.out.println(e);
}
}
}