I'm asking the user to input some text and print out whether or not that text is a palindrome. No matter what I input, it always evaluates to false. Is there something wrong with my reverse class? Are there bugs I'm missing or is there something wrong with my variables that .equals isn't working? For example:
Type in your text:
racecar
The original string reversed = racecar
racecar
It's not a palindrome
false
import java.util.Scanner;
public class Palindromes
{
/**
* This program lets the user input some text and
* prints out whether or not that text is a palindrome.
*/
public static void main(String[] args)
{
// Create user input and let user know whether their word is a palindrome or not!
String text="";
System.out.println("Type in your text:");
Scanner input = new Scanner(System.in);
text = input.nextLine();
System.out.println(reverse(text));
System.out.println(isPalindrome(text));
}
/**
* This method determines if a String is a palindrome,
* which means it is the same forwards and backwards.
*
* @param text The text we want to determine if it is a palindrome.
* @return A boolean of whether or not it was a palindrome.
*/
public static boolean isPalindrome(String text)
{
String newString= "";
if (newString.equals(text)){
System.out.println("It's a palindrome!");
return true;
}
else{
System.out.println("It's not a palindrome");
return false;
}
// return false;
}
/**
* This method reverses a String.
*
* @param text The string to reverse.
* @return The new reversed String.
*/
public static String reverse(String text)
{
String newString="";
for(int i = text.length() - 1; i >= 0; i--)
{
//remove spaces
newString = newString.replaceAll("\\s","");
//convert to lowercase
//newString = newString.toLowerCase();
newString = newString.replaceAll("'", "");
newString = newString.toLowerCase();
String character = text.substring(i, i+1);
newString += character;
}
System.out.println("The original string reversed = " +newString);
return newString;
}
}
Aucun commentaire:
Enregistrer un commentaire