Results 1 to 13 of 13
  1. #1
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default if else loop problem

    Hi all

    Below is the code i am working.

    Java Code:
    public class mapsample { 
    
    public static void main(String args[])
        {
    	  HashMap<String,String> hm=new HashMap<String,String>();
    	  ArrayList<String> name=new ArrayList<String>();
    	  ArrayList<String> subject=new ArrayList<String>();
    	  ArrayList<String> college=new ArrayList<String>();
    	  
    	  hm.put("chemistry", "ODHD");
    	  hm.put("physics", "OFFW");
    	  hm.put("maths", "OFFE");
    	  
    	  String s="Sam,Steve,physics,UPN";
    	  String pattern="S([^,])*";
    	  StringTokenizer st=new StringTokenizer(s,",");
    	  while(st.hasMoreTokens())
    	  {
    		  String tempStr=st.nextToken();
    		  //System.out.println(tempStr);
    		  if (Pattern.matches(pattern, tempStr)) 
    		  {  			  
      	        name.add(tempStr);
      	      }  
    		  
    		  for(Map.Entry<String, String> sub:hm.entrySet())
      		    {
      			if(tempStr.equals(sub.getKey()))
          		{
      				subject.add(tempStr);  				
          		}
      			 			
      		   }
    		  college.add(tempStr);
    	  }
    	 
    	  System.out.println(name);
    	  System.out.println(subject);
    	  System.out.println(college);
    	  
    		
      }
    
    }
    What i get is

    Output
    [Sam, Steve]
    [physics]
    [Sam, Steve, physics, UPN]

    But this is what i want.I know this is simple,but somehow i am too confused
    and cannot see how can i solve ,spending quite a time on it,but not able to ..i am sorry..can someone help
    Expected Output
    [Sam, Steve]
    [physics]
    [UPN]

    Thanks

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Run through the code by hand to see what it is doing.

    After a bit of reformating the while loop looks like this:

    Java Code:
    while(st.hasMoreTokens())
    {
       String tempStr=st.nextToken();
       //System.out.println(tempStr);
       if (Pattern.matches(pattern, tempStr)) 
       {  			  
          name.add(tempStr);
       }  
    		  
       for(Map.Entry<String, String> sub:hm.entrySet())
       {
          if(tempStr.equals(sub.getKey()))
          {
             subject.add(tempStr);  				
          }
       }
       college.add(tempStr);
    }
    That the college list contains every token should come as no surprise - after all the line "college.add(tempStr);" will be executed at the end of the loop for every token found.

    So don't do that.

    The real question is what should you do? And that's hard to answer unless you describe the problem. What would you do with input like the following:

    Foo,Stella,Samantha,maths,UPN
    Stella,maths,ABC
    maths,ABC
    Stella,maths,Samantha,physics,UPN
    etc

    As you can see, no-one really knows what the input might look like (the complete range of possible input) until you say. Nor the precise output expected from each possible input type. And until they know that, any anwser would be a mixture of guesswork and faith.
    Last edited by pbrockway2; 04-23-2009 at 11:56 PM.

  3. #3
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default

    The name part of my actual data are in a specific way i find no problems in extracting them with the help of regex and adding in a arraylist.
    The next part is the subject part,i have a hashmap of them..so looping through the hashmap list and token could give me the subject part..

    Next is the college part,the way i want is whatever is left out in the tokens,i need them in the college arraylist.

    so the question is how do i reformat the loop so that i can get this?

    Thanks a lot

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Quote Originally Posted by Ms.Ranjan View Post
    so the question is how do i reformat the loop so that i can get this?
    No. I'm sorry to repeat myself, but the question really is: what is the format of the input? what is the desired transformation? Where "what" means a description that is both comprehensive and specific.

    Assuming that the input consists of some number (zero or more) of tokens matching a given pattern, followed by a token from a given set, followed by any token, then a possible strategy could be:

    Java Code:
    String token
    while there are more tokens
        token = get next token
        if token matches pattern add it to name list
    end while
    
    if(token is still unassigned OR token matches pattern) 
       signal error "Unexpected end of input" and stop
    token = get next token
    if(token is in entry set)
       add token to subject list
    else 
       signal error "Invalid or missing subject" and stop
    
    if(there are no more tokens) 
       signal error "Missing college" and stop
    token = get next token
    add token to college list
    
    if(there *are* more tokens) 
       signal error "Unexpected data after college name" and stop
    
    print the name, subject and college lists
    String.split() or a real CSV library might be more robust than StringTokenizer.
    Last edited by pbrockway2; 04-24-2009 at 01:34 AM.

  5. #5
    JohnnyR is offline Member
    Join Date
    Feb 2009
    Posts
    46
    Rep Power
    0

    Default

    I've had a play, and got the desired outcome, not sure why you were using the Map.Thing - Personally never used it but my eclipse we only use 1.4 java at work so I assume it was implemented after it. But got it to work with basic for loops and making sure the log was there, however had to implement a 'if exists' method cause you don't want duplicates.

    Is this what you were looking for?

    Java Code:
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.StringTokenizer;
    import java.util.regex.Pattern;
    
    public class Test {
    
        public static void main(String args[]) {
            HashMap<String, String> hm = new HashMap<String, String>();
            ArrayList<String> name = new ArrayList<String>();
            ArrayList<String> subject = new ArrayList<String>();
            ArrayList<String> college = new ArrayList<String>();
    
            hm.put("chemistry", "ODHD");
            hm.put("physics", "OFFW");
            hm.put("maths", "OFFE");
    
            String s = "Sam,Steve,physics,UPN";
            String pattern = "S([^,])*";
            StringTokenizer st = new StringTokenizer(s, ",");
    
            while (st.hasMoreTokens()) { //while delimiters exist
                String tempStr = st.nextToken(); //temp String of current delim
                
                if (Pattern.matches(pattern, tempStr)) { //regex test
                    if (!checkIfExists(tempStr, name)) { //if name doesn't exist add it
                        name.add(tempStr);
                    }
                } else { // else do the rest of code
                    for (int i = 0; i < hm.size(); i++) { //loops through size of the map
                        if (hm.containsKey(tempStr) && (!checkIfExists(tempStr, subject))) { 
                            subject.add(tempStr); //If map contains the string key and it doesn't exist in the subject loop - add it.
                        }
                        if (!checkIfExists(tempStr, college) && !checkIfExists(tempStr, subject)) { //if doesn't exist in college and doesn't exist in subject add to college
                            college.add(tempStr);
                        }
                    }
                }
            }
            System.out.println(name);
            System.out.println(subject);
            System.out.println(college);
    
        }
    
        /**
         * 
         * @param tempStr - String to test
         * @param list - The list to compare against
         * @return - If String exists in the list return true else return false
         */
        public static boolean checkIfExists(String tempStr, ArrayList list) {
            for (int i = 0; i < list.size(); i++) {
                if (tempStr == list.get(i)) {
                    return true;
                }
            }
            return false;
    
        }
    }

  6. #6
    JohnnyR is offline Member
    Join Date
    Feb 2009
    Posts
    46
    Rep Power
    0

    Default

    Just remember, this is all in accordance with the correct information given into the 'String s' - IE I put a few extra things into the hm Map (maths/computers/science) added them to the string s and it correctly put them into the 'Subects'. Also added a few peoples names starting with 'S' and they went into the name but if you enter in the name 'John' or anything like that it goes into the College section as it's the last check if doesn't exist - Not really sure what the point of the whole this is as per the other person who's posted but from what you've given what i've done works..

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Johnny: your approach clearly assumes a different interpretation of what the OP was getting at...

    Just posting to say that your checkIfExists(String tempStr, ArrayList list) looks like it could just be list.contains(tempStr). Also since the input string is tokenized using ',' as a delimiter, doesn't the regex pattern just amount to tempStr.startsWith('P')?

  8. #8
    corlettk is offline Member
    Join Date
    Apr 2009
    Location
    Brisbane
    Posts
    86
    Rep Power
    0

    Default

    Johnny,

    Posting complete code solutions is generally frowned upon, extra-especially for what is obviously a homework question.

    The student must be left to sink-or-swim on there own merits... otherwise we risk turning out a whole generation of qualified know-nothings... and we don't want that... we want the stars to shine brightly, and the not-so-bright to realise there error and go study politics, law, or something equally drab.

    I know it's all pretty abstract, but please, even if you "don't get it" try to resist the temptation to be too helpful.

    Cheers. Keith.

  9. #9
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default

    Thanks a lot Johnny:)..the code works great...Thanks pbrockway2 for the pseudocode.

  10. #10
    Ms.Ranjan is offline Member
    Join Date
    Jun 2008
    Posts
    85
    Rep Power
    0

    Default

    Keith

    Posting complete code solutions is generally frowned upon, extra-especially for what is obviously a homework question.
    For your information this is not a homework question nor I am student expecting other people to do my work.I know the credibility of this forum and what forums are exactly for...I was just expecting some logic or some idea,to workaround for my problem.The code and the data which i have posted is not the exact one i am working on..johnny's code solution and the other person with algorithm gave me just an idea to use a condition to workaround actual my problem ..I just appreciated his efforts in helping me in the previous post,without seeing your post...

    The student must be left to sink-or-swim on there own merits... ..otherwise we risk turning out a whole generation of qualified know-nothings... and we don't want that... we want the stars to shine brightly, ..
    I appreciate your care for the next generation students..nobody is a born star with computer programming skills,with only the continued efforts and hardwork,they become one,at times they do need help...to shine
    the not-so-bright to realise there error and go study politics, law, or something equally drab
    and this is not how you respond to them....
    I know it's all pretty abstract, but please, even if you "don't get it" try to resist the temptation to be too helpful.
    Even if you are not helpful plz dont discourage people who want to help others...

  11. #11
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Quote Originally Posted by Ms.Ranjan View Post
    Even if you are not helpful plz dont discourage people who want to help others...
    And therein lies the paradox... If you complete someone's code for them, no matter who it is, are you really helping them? They may get the assignment done, however, they do not learn anything. Perhaps a compromise of posting partial code, or the code with some of the important questions as pseudocode is what is needed.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  12. #12
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default

    I so wanna jump into this discussion... yes, giving OPs full blown solutions is not right... it helps nobody... it's too much temptation to cut & paste & forget.... no effort or learning involved. What is correct is to offer suggestions, links, code snippets, pseudo code, etc.

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  13. #13
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    @OP: thanks for your thanks

    My take about whether tis better to give or not to give teh codes. (not intended to be counterposed to Chris or Keith)

    I see these threads as discussions and not as some form of wisdom-charity. Witnesses in a court case might be required to "just answer the question", but real discussions don't proceed that way. You respond as much about a question as to a question. And you are as much (or more) interested in the questioner and their understanding as in the question and its "answer".

    At least I am. So I'll post code if that best expresses what I want to say. But, more often than not, what I want to say is a response not an answer and I simply have no wish to post the "solution". (assuming there is one. and assuming I know it!) I'd prefer the response pushes a poster towards their finding a solution. I'm convinced the finding, not the solution, matters most.

    In this thread then, I responded with the need for clarity when parsing. In fact, the need for clarity before writing any parsing code. The statutory StringTokenizer warning. Some pseudocode illustrating a neurotic approach to error detection.

    It being (I hoped) a discussion, these reponses would themselves be responded to. But you respond however you like: you can't stop anyone looking for wisdom-charity. And gleaning whatever response you give for whatever wisdom-charity they might find. So there you go...

    Anyway, to people posting questions: this ain't Google or the "back pages" of your textbook! Ask a question, by all means. But you'll get the best value out of any internet forum if you participate in a discussion rather than expecting it to provide "answers" like so many search query "hits".
    Last edited by pbrockway2; 04-25-2009 at 10:36 AM.

Similar Threads

  1. While loop triangle problem
    By cmb3587 in forum New To Java
    Replies: 4
    Last Post: 03-02-2009, 01:53 PM
  2. Some while loop problem need help
    By shaggyoo7 in forum New To Java
    Replies: 4
    Last Post: 01-14-2009, 08:16 PM
  3. Loop Problem
    By jralexander in forum New To Java
    Replies: 4
    Last Post: 12-02-2008, 08:08 AM
  4. Problem to use different for loop to add up
    By matt_well in forum New To Java
    Replies: 6
    Last Post: 08-03-2008, 11:24 PM
  5. For loop problem
    By mcal in forum New To Java
    Replies: 32
    Last Post: 01-25-2008, 04:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •