سؤال

I'm having trouble with queue in my program where it asks the user to input a word and the program stores each letter into the queue. When I output the contents of the queue, the letters are all scrambled up. This happens to most words. For example, when I input "racecar", the queue would show up as [a, c, a, r, e, c, r], rather than [r, a, c, e, c, a, r]. Any idea why this happens?

import java.util.Scanner;
import java.util.*;

public class WordQueue
{
    public static void main(String arg[])
    {
        while(true){
            String phrase;
            int phraselength;
            PriorityQueue queue = new PriorityQueue();
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter a word/phrase");
            phrase = sc.nextLine();
            phrase = phrase.replaceAll("\\p{Punct}|\\d",""); //remove all punctuation
            phraselength = phrase.length();                  //get length of phrase
            System.out.println(phraselength);

            for(int x = 0; x <= phraselength-1; x++)         //store each letter 
            {                                                //in queue
                queue.offer(phrase.charAt(x));    
            }

            System.out.println("");

                System.out.printf("%s ", queue);             //output queue

        }
    }
}
هل كانت مفيدة؟

المحلول

The elements in a PriorityQueue do not follow any particular order, except for the head which is the smallest element. In particular, iteration order is not defined. If you continuously remove from the queue you will get the elements in natural order (alphabetical in your example).

In any case, it is probably not what you need. Why don't you use your Stack instead?

نصائح أخرى

PriorityQueue is not a FIFO queue. It orders elements so that the one with the highest priority is always at the head of the queue. Use LinkedList.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top