In: Computer Science
Create a Java method findLongestPalindrome that takes a Scanner scn as its parameter and returns a String. It returns the longest token from scn that is a palindrome (if one exists) or the empty string (otherwise). (Implementation note: Use the built in isPalindrome method. This method calls for an optimization loop.)
Where the isPalindrome Method takes a String s as a parameter and returns a boolean. It returns true if s reads the same forwards and backwards, i.e., is a Palindrome, and returns false otherwise.
I only need help creating the findLongestPalindrome method, I already have the isPalindrome method.
import java.util.Scanner;
public class LongestPalindrome {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.println("Longest
Palindrome: "+findLongestPalindrome(sc));
}
// takes series of words from user
//returns longest palindrome among them
public static String findLongestPalindrome(Scanner sc)
{
String s="";
String longestPal="";
while(!s.equalsIgnoreCase("Quit")){
s=sc.nextLine();
if(isPalindrome(s)){
if(s.length()>longestPal.length())
longestPal=s;
}
}
return longestPal;
}
//checks given string is palindrome or not
public static boolean isPalindrome(String s) {
char aC[]=s.toCharArray();
int i=0,j=s.length()-1;
//iterating from the both
ends
while(i<j){
if(aC[i]!=aC[j]){
return false;
}
i++;j--;
}
return true;
}
}