|
-
January 10th, 2012, 03:58 AM
#1
Help fix this code
when I try to it is being executed but unable to get my desired output
Desired Output:
when i call my "remove()" method
I want my Priority Queue to first give out the words starting with 's' then 'z' and then the rest.
import java.util.*;
public class PriorityCustom {
public static void main(String[] args) throws Exception {
//String[] words = {"apple", "crowd", "snow", "place", "snap", "zoo", "zing", "smile", "motto", "simple", "elegant","zebra"};
PriorityQueue<String> stringQueue = new PriorityQueue<String>(20,new Comparator<String>() {
String Z = "z";
String S = "s";
//@Override
public int compare(String S1,String S2) {
if (S1.startsWith(S)) {
return -1;
}
else if (S1.startsWith(Z)) {
return 0;
}
else {
return +1;
}
}
});
stringQueue.add("apple");
stringQueue.add("simple");
stringQueue.add("zoo");
stringQueue.add("zing");
stringQueue.add("elegant");
stringQueue.add("snap");
stringQueue.add("smile");
stringQueue.add("motto");
stringQueue.add("zebra");
stringQueue.add("crowd");
stringQueue.add("snow");
stringQueue.add("place");
/*for (int i = 0; i <0; i++)
stringQueue.add(new String());*/
while(!stringQueue.isEmpty())
System.out.println(stringQueue.remove());
}
}
-
January 10th, 2012, 05:38 AM
#2
Re: Help fix this code
Do you actually ever add something to the priority queue? You create it with size and a comprator, but theres no trace of actual values being added.
Last edited by Londbrok; January 10th, 2012 at 05:43 AM.
-
January 10th, 2012, 07:40 AM
#3
Re: Help fix this code
 Originally Posted by Londbrok
Do you actually ever add something to the priority queue?
The code contains a list of adds starting with stringQueue.add("apple");,
-
January 10th, 2012, 08:27 AM
#4
Re: Help fix this code
yeah sure does , how blind of me.
-
January 10th, 2012, 08:54 AM
#5
Re: Help fix this code
 Originally Posted by Londbrok
yeah sure does , how blind of me.
Don't worry we've all done similar things before now and will probably do them again in the future.
 Originally Posted by Harini Rao
I want my Priority Queue to first give out the words starting with 's' then 'z' and then the rest.
Your compare method needs to do something like:
Code:
public int compare(String S1,String S2) {
if ( S1.startsWith(S) ) {
if ( S2.startsWith(S) ) {
return 0;
}
return -1;
}
if (S1.startsWith(Z)) {
if ( S2.startsWith(S) ) {
return 1;
}
if ( S2.startsWith(Z) ) {
return 0;
}
return -1;
}
if (S2.startsWith(S) || S2.startsWith(Z)) {
return 1;
}
return 0;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|