Java program looping help! I need to restart the program via a y/n input

Okay so I made a program to check for palindromes but I need to be able to restart the program by asking if the user wants to try again y/n? But I can't seem to loop it correctly. Help me! P.S sorry for formatting.

import java.util.*;
import java.util.Scanner;
class PalidromeTester
{
public static void main(String args[])
{
boolean play = true; 
while(play == true){
String inputString;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a potential palindrome:");
inputString = in.nextLine();
int length  = inputString.length();
int i, begin, end, middle;
begin  = 0;
end    = length - 1;
middle = (begin + end)/2;
for (i = begin; i <= middle; i++) {
  if (inputString.charAt(begin) == inputString.charAt(end)) {
    begin++;
    end--;
  }
  else {
    break;
  }
}
if (i == middle + 1) {
  System.out.println("That string is a palindrome.");
}
else {
  System.out.println("Sorry, that string is not a palindrome.");
    }
System.out.println("y/n?");
String playagain = in.nextLine();
if (playagain == "y")
play = true;
else
play = false;
}
}
}
Last updated:12/30/2014 1:05:38 AM

1 Answers

Takeshi Okada
Takeshi Okada

Try this:

if ('y'.equalsIgnoreCase(playagain))

Don't use == to compare Strings. All that does is compare reference values. You want equals(): it compares String contents.

Answer