The issue I am having is once I input a word like "non" I get back it IS a palindrome. I then type "Yes" as I ask "Keep Going?". It starts back up at "Type Word:" and I type "non" again. This time however I get back it is NOT a palindrome. I think it has something to do with how I declare my variables or possibly with the for loop. I can't figure it out though. Any Help is appreciated.
import java.util.*;
public class palindromeTest
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
String word = "", backword = "", exit = "";
int length;
do{
System.out.print ("Type a Word: ");
word = in.nextLine();
length = word.length();
for (int i = length - 1; i >= 0; i--)
backword = backword + word.charAt(i);
if (word.equalsIgnoreCase(backword))
System.out.println ("This IS a Palindrome.");
else
System.out.println ("This is Not a Palindrome.");
System.out.println ("Keep Going? /n Yes or No?");
exit = in.nextLine();
}while(exit.equalsIgnoreCase ("Yes"));
}//end main
}//end palindromeTest
Move the declaration of backward
into the loop body (so it resets on each iteration),
String word = "", exit = "";
int length;
do {
String backword = "";
However, it's a better idea to use StringBuilder
for String
concatenation but I'll leave optimization as an exercise for the reader.