0

In my code, I am testing palidromes, but my input variable is not being reset with each iteration. The test works perfectly the first time, but with the same input, it comes out wrong.

Scanner input = new Scanner(System.in);
int i;
System.out.print("Enter a string: ");
String pal = input.nextLine();
String reverse = "";
boolean isFalse = false;

while (!isFalse) {
    if (pal.isEmpty()) {
        System.out.println("Empty line read - Goodbye!");
        isFalse = true;
    }
    if (pal.length() > 0) {
        for (i = pal.length() - 1; i >= 0; --i) {
            reverse = reverse + pal.charAt(i);
        }
        if (pal.equals(reverse)) {
            System.out.println(pal + " is a palidrome");
            System.out.println();
        } else {
            System.out.println(pal + " is not a palidrome");
            System.out.println();
        }
        System.out.print("Enter a string: ");
        pal = input.nextLine();
    }
}

pal is the input variable. While debugging, I printed the results of pal. 1331 comes out as a palidrome, but as I reentered 1331, the program outputs a false statement. Any suggestions? Edit: I added the rest of the code above the while loop

buræquete
  • 12,943
  • 4
  • 34
  • 69
  • Hard to tell with the code you posted but it looks like this may be the problem: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – GBlodgett Sep 20 '18 at 15:50
  • You should provide a [mcve] - the current code is missing a bunch of stuff... – achAmháin Sep 20 '18 at 15:51
  • Have you carefully debugged, either on paper, or with the debugger? Have you checked your assumptions regarding what specifically is contained in `pal`, the result of the `nextLine` call? Unrelated, but maybe change the name of `isFalse` to something like `shouldContinue`, and set it to `false` when you shouldn't? – Dave Newton Sep 20 '18 at 15:51

1 Answers1

3

You should reset variable reverse by writing reverse = ""; before the for loop:

reverse = "";
for (i = pal.length() - 1; i >= 0; --i) {
    reverse += pal.charAt(i);
}
buræquete
  • 12,943
  • 4
  • 34
  • 69
Hülya
  • 3,054
  • 2
  • 10
  • 16