I have made a good bit of progress with my code and am now stuck on something I believe to be quite simple. I have it printing out the line numbers that the word occurs on in the supplied text file but it is not supposed to count multiple occurances on the same line.
Text file:
string
cat
mouse mouse
phone
phone
//Name: Hal Walters //Class: SCSC 321 //Date: 3/10/2013 import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; public class driver1 { @SuppressWarnings({ "resource", "rawtypes", "unchecked" }) public static void main(String[] args) { String fileName = "strings.txt"; try{ BufferedReader inFile = new BufferedReader(new FileReader(fileName)); Map wordMap = new TreeMap(); String oneLine; //Read the wortds and add them to the wordMap for (int lineNum = 1; (oneLine = inFile.readLine()) != null; lineNum++){ StringTokenizer st = new StringTokenizer(oneLine); while (st.hasMoreTokens()){ String word = st.nextToken(); List lines = (List) wordMap.get(word); if (lines == null){ lines = new LinkedList(); wordMap.put(word, lines); } lines.add(new Integer(lineNum)); } } //go through the word map Iterator itr = wordMap.entrySet().iterator(); while (itr.hasNext()){ printEntry((Map.Entry) itr.next()); } } catch(IOException e){ e.printStackTrace(); } } //prints everything @SuppressWarnings("rawtypes") public static void printEntry(Map.Entry entry){ //print the word and line numbers Iterator itr = ((List)(entry.getValue())).iterator(); System.out.print(entry.getKey() + ": " + itr.next()); while (itr.hasNext()){ if (itr.equals(itr.next())){ return; } else{ System.out.print(", " + itr.next()); } } System.out.println(); } }
As always, thanks in advance.
The problem is around the if statement inside the printEntry method.
Output: