lundi 9 mars 2015

How to find on which line a word is in Java



I am trying to create a program that counts the number of times a word appears in a text and also tell you how many times it appears on each line. I have managed to find the number of times the word appears and the number of lines in the text, but I cannot find on which line the word appears in and how many times. Could you please help me? This is my code so far:



FileReader file = new FileReader("C:/Users/User/Desktop/test.txt");
BufferedReader buffer = new BufferedReader(file);

String line = buffer.readLine();
Map<String, Integer> hash = new HashMap<String, Integer>();
int counter = 0; //number of lines

while (line != null){
String[] words = line.split(" ");

for (String s : words) {
Integer i = hash.get(s);
hash.put(s, (i==null)? 1: i+1);
}

line = buffer.readLine();
counter = counter + 1;
}

System.out.println(hash);
System.out.println(counter);



Aucun commentaire:

Enregistrer un commentaire