The purpose of my code is to determine if a string entered by a user is a palindrome (meaning that the spelling of the word backwards and normally is the same). I am supposed to do this using 2 methods, the first one (reverse) which reverses the word. In this method, the string of the reversed word is returned, but I need to use it on the other method (isPalindrome) to compare if both the original text and the reversed word are spelled the same. How do I use the string being returned in the reverse method on the method isPalindrome?
import java.util.Scanner;
public class Palindromes
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type in your text:");
String palindrome = input.nextLine();
reverse(palindrome);
if(isPalindrome(palindrome))
{
System.out.println("Your word is a palindrome!");
}
else
{
System.out.println("Your word isn't a palindrome!");
}
}
public static boolean isPalindrome(String text)
{
boolean value = false;
if(reverse.equals(text))
{
value = true;
}
return value;
}
public static String reverse(String text)
{
String reverse = "";
for(int i = text.length()-1; i>=0; i--)
{
reverse = reverse + text.substring(i, i+1);
}
return reverse;
}
}
In your isPalindrome()
method, you just need to call:
return text.equals(reverse(text));
No need for the intermediate boolean value
.
And to take it one step further, no need for the reverse logic either, since you can just use StringBuilder.reverse()
.