我正在做一项识别回文的任务,我必须使用堆栈来完成它。我目前收到消息错误:标识符预期:
palStack.push(nextChar);
我的教授说我正在尝试使用Stack作为原始类型,这就是我收到错误的原因,但我不确定他的意思是什么?我对数据结构很新,所以任何关于使用堆栈的提示都将受到赞赏!
以下是我遇到问题的部分:
public static void main(String[] args){
int replay = 0;
Stack<char> palStack = new Stack<>();
char nextChar;
int characterCount;
String phrase, emptyPhrase = "", replayAns;
@SuppressWarnings("unchecked")
Scanner reader = new Scanner(System.in);
while(replay != 1){
System.out.println("Enter phrase: ");
phrase = reader.nextLine();
characterCount = phrase.length();
System.out.print("Original phrase: ");
for(int i = 0; i < characterCount; i++){
nextChar = phrase.charAt(i);
@SuppressWarnings("unchecked")
palStack.push(nextChar);
System.out.print(nextChar);
}
}
}
问题出在这一行:
Stack<char> palStack = new Stack<>();
您不能使用基元/原始类型(在本例中为char
)作为泛型类型(https://docs.oracle.com/javase/tutorial/java/generics/types.html)。所以你只需要使用引用类型,即java.lang.Character
:
Stack<Character> palStack = new Stack<>();