Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 43

Thread: Presumably simple fix sets/maps

  1. #1
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Presumably simple fix sets/maps

    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:


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Can you post the program's output that shows the problem, add some comments to the output describing what is wrong with it and show what it should be.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    I updated the first post.

    Edit- Also went back and messed around with my code more and got it to a point where I feel it is even closer. I also added some code for formatting and counting word occurances. This is only the printEntry method.

    	//prints id, line numbers, and occurance for the individual entry
    	@SuppressWarnings("rawtypes")
    	public static void printEntry(Map.Entry entry){
     
    		//local occurance variable
    		int occurance = 1;
     
    		//print the word and the line numbers
    		Iterator itr = ((List) entry.getValue()).iterator();
    		System.out.print("ID: " + entry.getKey() + "   Lines: " + itr.next());
    		while(itr.hasNext()){
    			if (itr.toString() != itr.next().toString()){
    			System.out.print(", " + itr.next());
    			occurance++;
    			}
    			else{
    				return;
    			}
    		}
    		System.out.print("  " + " Occurance: " + occurance);
    		System.out.println();
    	}

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Where does the code test for a duplicate entry?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    if (itr.toString() != itr.next().toString()){
    			System.out.print(", " + itr.next());
    			occurance++;
    			}
    			else{
    				return;
    			}

    well, i know this much already doesn't work. It should be something simple but I have no idea how to do it.

  6. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Presumably simple fix sets/maps

    String comparison shouldn't be done using comparison operators, rather you should use the .equals() method.

  7. The Following User Says Thank You to helloworld922 For This Useful Post:

    waltershc (March 12th, 2013)

  8. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Is it ok to have duplicate line numbers in the list?
    If you don't understand my answer, don't ignore it, ask a question.

  9. The Following User Says Thank You to Norm For This Useful Post:

    waltershc (March 12th, 2013)

  10. #8
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    Quote Originally Posted by Norm View Post
    Is it ok to have duplicate line numbers in the list?
    Not for a single identifier. In other words, any given line number should not appear more than once on a line in the console.

    --- Update ---

    Quote Originally Posted by helloworld922 View Post
    String comparison shouldn't be done using comparison operators, rather you should use the .equals() method.
    I played around with that a little bit but couldn't get it to work. I will go back and try again. Thanks.

    Helloworld, something like this?
    if (itr.toString().equals(itr.next()))

  11. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    The posted code doesn't check for duplicates before adding a number to the list.
      lines.add(new Integer(lineNum));
    If you don't understand my answer, don't ignore it, ask a question.

  12. The Following User Says Thank You to Norm For This Useful Post:

    waltershc (March 12th, 2013)

  13. #10
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    			//Read the words 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 list is empty/doesnt exist
    					if (lines == null){
    						lines = new LinkedList();
    						wordMap.put(word, lines);
    					}
    					//presumably checks for duplicates
    					else if (lines.contains(lineNum)){
    						System.out.println("inside if statement");
    						return;
    					}
    					//list wasnt empty, lineNum being inserted wasnt a dup
    					else{
    					lines.add(new Integer(lineNum));
    					}
    				}
    			}

    Am I close?

  14. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Does it compile, execute and work correctly?


    I'm done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    waltershc (March 14th, 2013)

  16. #12
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps



    Thanks for the help so far. Let me know if you cannot read the text.

  17. #13
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Presumably simple fix sets/maps

    please copy and paste the text instead of using a screenshot.

  18. The Following User Says Thank You to helloworld922 For This Useful Post:

    waltershc (March 14th, 2013)

  19. #14
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    Running.
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.LinkedList$ListItr.next(Unknown Source)
    at driver1.printEntry(driver1.java:67)
    at driver1.main(driver1.java:50)
    //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({ "unchecked", "rawtypes", "resource" })
    	public static void main(String[] args) {
     
    		int check;
    		System.out.println("Running.");
    		String fileName = "strings.txt";
    		try{
    			BufferedReader inFile = new BufferedReader(new FileReader(fileName));
    			Map wordMap = new TreeMap();
    			String oneLine;
     
    			//Read the words 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 list is empty/doesnt exist
    					if (lines == null){
    						lines = new LinkedList();
    						wordMap.put(word, lines);
    					}
    					//presumably checks for duplicates
    					else if (lines.contains(lineNum)){
    						System.out.println("inside if statement");
    						return;
    					}
    					//list wasnt empty, lineNum being inserted wasnt a dup
    					else{
    					lines.add(new Integer(lineNum));
    					}
    				}
    			}
     
    			//goes through the word map
    			Iterator itr = wordMap.entrySet().iterator();
    			while (itr.hasNext()){
    				printEntry((Map.Entry) itr.next());
    			}
    		}
    			catch(IOException e){
    				e.printStackTrace();
    			}
    	}
     
    	//prints id, line numbers, and occurance for the individual entry
    	@SuppressWarnings("rawtypes")
    	public static void printEntry(Map.Entry entry){
     
    		//local occurance variable
    		int occurance = 1;
     
    		//print the word and the line numbers
    		Iterator itr = ((List) entry.getValue()).iterator();
    		System.out.print("ID: " + entry.getKey() + "   Lines: " + itr.next());
    		while(itr.hasNext()){
    			System.out.print(", " + itr.next());
    			occurance++;
    			}
    		System.out.print("  " + " Occurance: " + occurance);
    		System.out.println();
    	}
    }

  20. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Is there an element avaiable when the next() method is called on line 67? The code should test BEFORE calling next()
    If you don't understand my answer, don't ignore it, ask a question.

  21. The Following User Says Thank You to Norm For This Useful Post:

    waltershc (March 14th, 2013)

  22. #16
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    So get rid of the elseif statement and put something in around the while loop at the bottom of the main class?

  23. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Basically the code should call hasNext() before calling next()
    If you don't understand my answer, don't ignore it, ask a question.

  24. The Following User Says Thank You to Norm For This Useful Post:

    waltershc (March 14th, 2013)

  25. #18
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    Forgive my ignorance, but where? There is a hasNext() call on line 49 when it runs through the iterator to call the printEntry method.

  26. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Where is that iterator that has said that it had a next entry used in the printEntry() method?
    There is a new iterator created in the printEntry() method. That is the one to test.

    Add some println statements to show the contents of the collections and variables so you know what you are working with.
    If you don't understand my answer, don't ignore it, ask a question.

  27. The Following User Says Thank You to Norm For This Useful Post:

    waltershc (March 14th, 2013)

  28. #20
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    //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({ "unchecked", "rawtypes", "resource" })
    	public static void main(String[] args) {
     
    		System.out.println("Running.");
    		String fileName = "strings.txt";
    		try{
    			BufferedReader inFile = new BufferedReader(new FileReader(fileName));
    			Map wordMap = new TreeMap();
    			String oneLine;
     
    			//Read the words 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 list is empty/doesnt exist
    					if (lines == null){
    						lines = new LinkedList();
    						wordMap.put(word, lines);
    					}
    					lines.add(new Integer(lineNum));
     
    				}
    			}
     
    			//goes through the word map
    			Iterator itr = wordMap.entrySet().iterator();
    			while (itr.hasNext()){
    				printEntry((Map.Entry) itr.next());
    			}
    		}
    			catch(IOException e){
    				e.printStackTrace();
    			}
    	}
     
    	//prints id, line numbers, and occurance for the individual entry
    	@SuppressWarnings("rawtypes")
    	public static void printEntry(Map.Entry entry){
     
    		//local occurance variable
    		int occurance = 1;
     
    		//print the word and the line numbers
    		Iterator itr = ((List) entry.getValue()).iterator();
    		System.out.print("ID: " + entry.getKey() + "   Lines: " + itr.next());
    		while(itr.hasNext()){
    			if(itr.equals(itr.next()))
    			System.out.print(", " + itr.next());
    			occurance++;
    			}
    		System.out.print("  " + " Occurance: " + occurance);
    		System.out.println();
    	}
    }
    Its soooooo close.

    Output:
    Running.
    ID: cat Lines: 2 Occurance: 1
    ID: mouse Lines: 3 Occurance: 2
    ID: phone Lines: 4 Occurance: 2
    ID: string Lines: 1 Occurance: 1

    Phone should also have 5 listed as a line occurance. The occurance counts are right, and the mouse line occurance is correct. Phone seems to be the last thing.

  29. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    Continue debugging to see what is happening to the data.
    If you don't understand my answer, don't ignore it, ask a question.

  30. #22
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    //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({ "unchecked", "rawtypes", "resource" })
    	public static void main(String[] args) {
     
    		System.out.println("Running.");
    		String fileName = "strings.txt";
    		try{
    			BufferedReader inFile = new BufferedReader(new FileReader(fileName));
    			Map wordMap = new TreeMap();
    			String oneLine;
     
    			//Read the words 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 list is empty/doesnt exist
    					if (lines == null){
    						lines = new LinkedList();
    						wordMap.put(word, lines);
    					}
    					lines.add(new Integer(lineNum));	
    				}
    			}
     
    			//goes through the word map
    			Iterator itr = wordMap.entrySet().iterator();
    			while (itr.hasNext()){
    				printEntry((Map.Entry) itr.next());
    			}
    		}
    			catch(IOException e){
    				e.printStackTrace();
    			}
    	}
     
    	//prints id, line numbers, and occurance for the individual entry
    	@SuppressWarnings("rawtypes")
    	public static void printEntry(Map.Entry entry){
     
    		//local occurance variable
    		int occurance = 1;
     
    		//print the word and the line numbers as well as test for duplicate line integers on the same key
    		Iterator itr = ((List) entry.getValue()).iterator();
    		System.out.print("ID: " + entry.getKey() + "   Lines: " + itr.next());
    		while(itr.hasNext()){
    			if(itr.equals(itr.next())){
    				System.out.println("blah");
    			}
    			else{
    			System.out.print(", " + itr.next());
    			occurance++;
    			}	
    		}
    		System.out.print("  " + " Occurance: " + occurance);
    		System.out.println();
    	}
    }
    I spoke too soon. I am back to my original code. I realized that I need the negative of the if statement in the printEntry method.
    It's:
    if (!itr.equals(itr.next()))
    ...right?

    if so, its throwing an error:
    Running.
    ID: cat Lines: 2 Occurance: 1
    ID: mouse Lines: 3Exception in thread "main" java.util.NoSuchElementException
    at java.util.LinkedList$ListItr.next(Unknown Source)
    at driver1.printEntry(driver1.java:64)
    at driver1.main(driver1.java:41)

  31. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    This code makes not sense:
    if (!itr.equals(itr.next()))
    The two objects being compared are probably of different types.

    java.util.NoSuchElementException
    Print out the value of entry first thing in the printEntry() method to see what data is there.

    Use this line vs what's in the code:
    System.out.print("ID: " + entry.getKey() + "   Lines: " + itr.hasNext()); //  use hasNext()
    If you don't understand my answer, don't ignore it, ask a question.

  32. The Following User Says Thank You to Norm For This Useful Post:

    waltershc (March 14th, 2013)

  33. #24
    Member
    Join Date
    Feb 2013
    Posts
    42
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Presumably simple fix sets/maps

    	public static void printEntry(Map.Entry entry){
     
    		//local occurance variable
    		int occurance = 1;
    		System.out.println(entry.getValue().toString());
     
    		//print the word and the line numbers as well as test for duplicate line integers on the same key
    		Iterator itr = ((List) entry.getValue()).iterator();
    		System.out.print("ID: " + entry.getKey() + "   Lines: " + itr.next());
    		while(itr.hasNext()){
    			if(itr.equals(itr.next())){
    			//	System.out.println("blah");
    			//}
    			//else{
    			System.out.print(", " + itr.next());
    			occurance++;
    			}	
    		}
    		System.out.print("  " + " Occurance: " + occurance);
    		System.out.println();
    	}
    Output:
    Running.
    [2]
    ID: cat Lines: 2 Occurance: 1
    [3, 3]
    ID: mouse Lines: 3 Occurance: 1
    [4, 5]
    ID: phone Lines: 4 Occurance: 1
    [1]
    ID: string Lines: 1 Occurance: 1

    I need the if statement to test for a 'does not' equal value but I am not really sure how.

  34. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Presumably simple fix sets/maps

    What objects do you want to compare?

    What is in the collection: wordMap?
    What is in the object: entry? The code only prints part of it.
    If you don't understand my answer, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. Sets/Maps help needed
    By waltershc in forum What's Wrong With My Code?
    Replies: 5
    Last Post: March 11th, 2013, 02:07 PM
  2. A simple mistake I can't fix
    By xdx in forum What's Wrong With My Code?
    Replies: 5
    Last Post: September 5th, 2012, 05:50 AM
  3. Simple Google Maps like Image viewer in Java
    By javaguy2020 in forum What's Wrong With My Code?
    Replies: 26
    Last Post: December 7th, 2011, 11:46 PM
  4. [SOLVED] Maps and adding to sets as values
    By mds1256 in forum Collections and Generics
    Replies: 3
    Last Post: March 26th, 2010, 09:12 AM
  5. Convert Maps of String to Map of Maps
    By abhay8nitt in forum Collections and Generics
    Replies: 1
    Last Post: October 27th, 2009, 07:27 AM