Java中的堆栈无法按特定顺序打印
Posted
技术标签:
【中文标题】Java中的堆栈无法按特定顺序打印【英文标题】:Stack in Java not being able to print in specific order 【发布时间】:2022-01-11 02:53:29 【问题描述】:目前我正在开发一个应该是反向猜词游戏的项目。 它应该是这样工作的:
Enter a word: (input = cheese)
Your word is: _ _ _ _ _ e
What letter do you guess? (input = s)
用法一直在猜测单词,直到完全拼出为止。如果用户猜对了字母,就会显示出来,如果不是,它仍然会如下所示
Your word is: _ _ _ _ _ e
What letter do you guess?
Your word is: _ _ _ _ s e
What letter do you guess?
Your word is: _ _ _ e s e
What letter do you guess?
Your word is: _ _ e e s e
What letter do you guess?
Your word is: _ h e e s e
What letter do you guess?
Your word is: c h e e s e
Gameover!
⚠️目前我有一个包含给定单词的所有字母的堆栈,如下所示:⚠️ 底部:c h e e s e:顶部
我目前有这个代码:
while(guesses < letters.size())
System.out.print("Your word is: ");
for(int i = 1; i < letters.size(); i++)
System.out.print("_ ");
System.out.println(letters.peek() + test);
System.out.println("Score: " + score);
System.out.print("What letter do you guess? ");
char guess = sc.next().charAt(0);
if((Object)guess == letters.peek())
test += letters.pop();
score++;
else
test += letters.pop();
score--;
但是它正在打印这个:
Your word is: _ _ _ _ _ e
Score: 0
What letter do you guess?
Your word is: _ _ _ _ se
Score: 0
What letter do you guess?
Your word is: _ _ _ ees
Score: 0
What letter do you guess?
Your word is: _ _ eese
Score: 0
What letter do you guess?
Your word is: _ hesee
Score: 0
What letter do you guess?
Your word is: ceseeh
Score: 0
Gameover!
谢谢。如果需要更多信息,请发表评论并告诉我!
【问题讨论】:
您是否尝试过调试您的代码? 【参考方案1】:您的代码不完整,因此我无法确定问题出在哪里。为了回答您的问题,我假设问题是 System.out.println(letters.peek() + test);
行错误地打印了单词。
通过执行test += letters.pop();
,您将letters.pop()
附加到test
。
相反,您应该将letters.pop()
添加到test
:
test = letters.pop() + test;
【讨论】:
多么愚蠢的错误!我不敢相信就这么简单!谢谢!【参考方案2】:尝试: if(Character.compare(guess, (char) letters.peek())) . 现有逻辑 .
【讨论】:
感谢您的回答,不幸的是,这不起作用并且与我的问题有点无关。再次感谢您的回答!if((Object)guess == letters.peek()) test += letters.pop(); score++; else test += letters.pop(); score--;
------------------------- 在这里,您将 's' 与堆栈'e'。希望这会有所帮助。以上是关于Java中的堆栈无法按特定顺序打印的主要内容,如果未能解决你的问题,请参考以下文章