In: Computer Science
You are to name your package assign1 and your file Palindrome.java.
Palindrome Class
Palindrome
- testString : String
+ Palindrome (String)
+ isPalindrome (): boolean |
The method isPalindrome is to determine if a string is a palindrome. A palindrome, for this assignment, is defined as a word or phrase consisting of alphanumeric characters that reads the same frontwards and backwards while ignoring cases, punctuation and white space. If there are no alphanumeric characters, the string is considered a palindrome. The method should return true if it is a palindrome and false otherwise.
Notice – there is no main, no input and no output for this assignment. You are limited to the following Java library classes.
- String
- Character
Here are the restrictions on this method. Up to 20% penalty if not followed.
1. You may NOT return from the inside of a loop.
2. You may NOT break from the inside of a loop.
3. You may use ONLY ONE loop (either while or do-while).
4. You may NOT copy the String to another String.
5. You may NOT process the String more than one time (only make one
pass
through it).
6. You must STOP processing as early as possible (when you find
that it is or is not
a palindrome). In other words, using a for loop is not a good solution.
Program code in java:
//declaring package
package assign1;
//class definition
public class Palindrome {
//variable declaration
String testString;
//constructor
public Palindrome(String text) {
//assigning value to the
variable after removing all the spaces and putting text in lower
case
testString=text.replaceAll("\\s", "").toLowerCase();
}
//method to find if the string is palindrome or
not
boolean isPalindrome(){
System.out.println("Provided text is: "+testString);
//variable
declaration
boolean flag=true;
//finding the length of
string and storing in variable
int
len=testString.length();
//running the loop to
find if the string is pallindrome
for(int i=0;
i<=len/2;i++){
//comparing each character in the string and if the are not equal,
reset the flag
if(testString.charAt(i)!=testString.charAt(len-i-1)){
flag=false;
}
}
//return true if the
string is palindrome or false if it is not
return flag;
}
//main method
public static void main(String[] args) {
//creating object and
providing the string to the constructor
Palindrome pr=new
Palindrome("Hello tmolleh");
//claling the function
to find the palindrome and storing the result in varianble
boolean
val=pr.isPalindrome();
//checking for the value
of variable
if(val==true){//true
means the string is palindrome
System.out.println("The given text is a palindrome");
}
else{//false if string
is not palindrome
System.out.println("The given text is not a palindrome");
}
}
//end of main method
}
//end of class
Output: