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

Total Post:104

Points:728
Java  Loop 
 1829  View(s)
Ratings:
Rate this:
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;
}
}
}
  1. Post:89

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

    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.

      Modified On Apr-07-2018 06:00:45 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!