简体   繁体   中英

Easy fix for while loop not executing properly second time?

I'm fairly new at java and have a current assignment to take a given word, put the first word at the end, rebuild the word from reverse, and see if it's the same word as the original, such as: grammar, potato, uneven, dresser, banana etc. So far I have this:

    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();

When I run it and enter the word "banana," it properly recognizes that it is indeed the same backwards when the b is moved to the end, and does the same with the other words listed above, but when I enter a second word on the loop, it never recognizes it properly, and always responds with the print statement from the else block:

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): 

I'm guessing it's something to do with either the way I made my for loop, or the way I asked for input at the end of the while loop, but like I said I'm fairly new and awful at debugging. Any help would be much appreciated, thanks a lot in advance.

You are changing string reverse in every iteration, but you are not clearing it. So before the end of the loop or at the beginning clear the string for example like so: reverse = "" , and then it should be fine.

Just add reverse = ""; in the end of the while loop in order to set the variable reverse to its original state, ie empty string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM