轻松修复while循环第二次无法正常执行?

时间:2018-09-30 06:59:34

标签: java

我在Java领域还很陌生,现在有一个任务,可以接受一个给定的单词,将第一个单词放在最后,从相反的方向重建该单词,然后查看它是否与原始单词相同,例如:grammar ,土豆,高低不平,梳妆台,香蕉等。到目前为止,我有这个:

    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移到末尾时,它确实是向后的,并且对上面列出的其他单词也是如此,但是当我输入a时循环中的第二个单词,它永远无法正确识别它,并始终使用else块中的print语句进行响应:

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循环结束时要求输入的方式有关,但就像我说的那样,我相当陌生,调试起来很糟糕。任何帮助将不胜感激,在此先感谢。

2 个答案:

答案 0 :(得分:0)

您将在每次迭代中更改字符串reverse,但没有清除它。因此,在循环结束之前或开始之前,请清除字符串,例如:reverse = "",然后就可以了。

答案 1 :(得分:0)

只需添加反向=“”;在while循环的最后,以便将变量设置回其原始状态,即空字符串