Skip to content

Instantly share code, notes, and snippets.

@biodunalfet
Created January 9, 2017 15:21
Show Gist options
  • Save biodunalfet/bcf293e5853f286d2b9dae95fcde6280 to your computer and use it in GitHub Desktop.
Save biodunalfet/bcf293e5853f286d2b9dae95fcde6280 to your computer and use it in GitHub Desktop.
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
public class quest1 {
public static void main(String[] args){
ArrayList<String> words = new ArrayList<>();
try {
System.out.print("Enter the file name with extension e.g. file.txt: ");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
File file = new File(fileName);
System.out.print("Enter the word you're looking for: ");
String word = input.nextLine();
input = new Scanner(file);
while (input.hasNext()) {
String line = input.next();
//System.out.println(line);
words.add(line);
}
input.close();
print("File contains " + words.size() + " words.");
ArrayList<Integer> position = new ArrayList();
int wordCount = 0;
for (int i = 0; i < words.size(); i++){
String currentWord = words.get(i);
if (currentWord.trim().equalsIgnoreCase(word.trim())){
wordCount += 1;
position.add(i + 1);
}
}
print("Word " + word + " occurs " + wordCount + " times in " + fileName);
if (wordCount > 0){
print("at position(s) " + convertPositionsToPrintableString(position));
}
} catch (Exception ex) {
ex.printStackTrace();
print(ex.getMessage());
}
}
public static String convertPositionsToPrintableString(ArrayList<Integer> position){
String positions = "";
for (int j = 0; j < position.size(); j++){
positions += position.get(j) + " ";
}
return positions;
}
public static void print(String text){
System.out.println(text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment