Reputation: 150
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
Upvotes: 0
Views: 96
Reputation: 3433
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);
}
Upvotes: 3