我在我的程序中遇到队列问题,它要求用户输入一个单词并且程序将每个字母存储到队列中。当我输出队列的内容时,字母都被打乱了。大多数单词都会发生这种情况。例如,当我输入“racecar”时,队列将显示为 [a, c, a, r, e, c, r],而不是 [r, a, c, e, c, a, r]。知道为什么会这样吗?
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
}
}
}