我正在做一項識別回文的任務,我必須使用堆棧來完成它。我目前收到消息錯誤:預期標識符:palStack.push(nextChar);我的教授說我正在嘗試將 Stack 用作原始類型,這就是我收到錯誤的原因,但我不確定他到底是什么意思?我對數據結構很陌生,所以任何關于使用 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); } }}
1 回答

有只小跳蛙
TA貢獻1824條經驗 獲得超8個贊
問題出在這一行:
Stack<char> palStack = new Stack<>();
您不能將原語/原始類型(在這種情況下char
)用作泛型類型(https://docs.oracle.com/javase/tutorial/java/generics/types.html)。所以你只需要使用一個引用類型,即java.lang.Character
:
Stack<Character> palStack = new Stack<>();
添加回答
舉報
0/150
提交
取消