我在java方面相当新,并且有一个当前的任务来获取给定的单词,将第一个单词放在最后,从反向重建单词,看看它是否与原始单词相同,例如:语法,土豆,不均匀,梳妆台,香蕉等。到目前为止我有这个:
Scanner input = new Scanner(System.in);
String original, reverse = "";
String exit = "quit";
int index;
System.out.println("Please enter a word (enter quit to exit the program): ");
original = input.next();
while (!original.equalsIgnoreCase(exit))
{
String endingChar = original.substring(0, 1);
String addingPhrase = original.substring(1);
reverse += endingChar;
for (index = addingPhrase.length() - 1; index >= 0; --index)
{
char ch = addingPhrase.charAt(index);
reverse += ch;
}
if (original.equals(reverse))
{
System.out.println("Success! The word you entered does have the gramatic property.");
}
else
{
System.out.println("The word you entered does not have the gramatic property."
+ " Please try again with another word (enter quit to exit the program): ");
}
original = input.next();
}
input.close();
当我运行它并输入“banana”这个词时,它正确地识别出当 b 移到最后时它确实向后相同,并且对上面列出的其他词也这样做,但是当我输入第二个词时循环,它永远不会正确识别它,并且总是使用来自 else 块的打印语句进行响应:
Please enter a word (enter quit to exit the program):
banana
Success! The word you entered does have the gramatic property.
banana
The word you entered does not have the gramatic property. Please try again
with another word (enter quit to exit the program):
我猜这与我制作 for 循环的方式有关,或者与我在 while 循环结束时要求输入的方式有关,但就像我说的那样,我在调试方面很新而且很糟糕。任何帮助将不胜感激,非常感谢。
慕森卡
慕无忌1623718
相关分类