Results 1 to 13 of 13
Thread: if else loop problem
- 04-23-2009, 10:19 PM #1
Member
- Join Date
- Jun 2008
- Posts
- 85
- Rep Power
- 0
if else loop problem
Hi all
Below is the code i am working.
What i get isJava 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); } }
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
- 04-23-2009, 10:54 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
Run through the code by hand to see what it is doing.
After a bit of reformating the while loop looks like this:
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.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); }
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 10:56 PM.
- 04-23-2009, 11:10 PM #3
Member
- Join Date
- Jun 2008
- Posts
- 85
- Rep Power
- 0
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
- 04-23-2009, 11:49 PM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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:
String.split() or a real CSV library might be more robust than StringTokenizer.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 listsLast edited by pbrockway2; 04-24-2009 at 12:34 AM.
- 04-24-2009, 01:18 AM #5
Member
- Join Date
- Feb 2009
- Posts
- 46
- Rep Power
- 0
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; } }
- 04-24-2009, 01:23 AM #6
Member
- Join Date
- Feb 2009
- Posts
- 46
- Rep Power
- 0
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..
- 04-24-2009, 08:37 AM #7
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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')?
- 04-24-2009, 10:11 AM #8
Member
- Join Date
- Apr 2009
- Location
- Brisbane
- Posts
- 86
- Rep Power
- 0
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.
- 04-24-2009, 02:45 PM #9
Member
- Join Date
- Jun 2008
- Posts
- 85
- Rep Power
- 0
Thanks a lot Johnny:)..the code works great...Thanks pbrockway2 for the pseudocode.
- 04-24-2009, 03:50 PM #10
Member
- Join Date
- Jun 2008
- Posts
- 85
- Rep Power
- 0
Keith
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...Posting complete code solutions is generally frowned upon, extra-especially for what is obviously a homework question.
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 shineThe 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 this is not how you respond to them....the not-so-bright to realise there error and go study politics, law, or something equally drab
Even if you are not helpful plz dont discourage people who want to help others...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.
- 04-25-2009, 01:40 AM #11
Senior Member
- Join Date
- Mar 2009
- Posts
- 552
- Rep Power
- 5
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!
- 04-25-2009, 05:43 AM #12
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,
CJSLChris S.
Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.
- 04-25-2009, 09:30 AM #13
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
@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 09:36 AM.
Similar Threads
-
While loop triangle problem
By cmb3587 in forum New To JavaReplies: 4Last Post: 03-02-2009, 12:53 PM -
Some while loop problem need help
By shaggyoo7 in forum New To JavaReplies: 4Last Post: 01-14-2009, 07:16 PM -
Loop Problem
By jralexander in forum New To JavaReplies: 4Last Post: 12-02-2008, 07:08 AM -
Problem to use different for loop to add up
By matt_well in forum New To JavaReplies: 6Last Post: 08-03-2008, 10:24 PM -
For loop problem
By mcal in forum New To JavaReplies: 32Last Post: 01-25-2008, 03:51 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks