In: Computer Science
IN JAVA PLEASE
The Palindrome class will have a single constructor that accepts a String argument and checks to see if the String is a palindrome.
If it is a palindrome it will store the palindrome and the original String as state values. If is not a palindrome it will throw a “NotPalindromeError” and not finish the creation of the new Palindrome object.
The constructor will use a single stack to evaluate if the String is a palindrome.
You must use a bounded stack to do the evaluation. You may use the ArrayBoundedStack from the book.
The bounded stack may only hold one half of the target String.
The Strings to be checked will consist of alphanumeric characters, spaces, and punctuation. The spaces and punctuation are to be ignored for the purpose of determining if the Strings are palindromes. Capitalization should not affect the identification of a palindrome.
public class Palindrome {
private String original;
public String palindrome;
public Palindrome(String str) throws Exception {
this.original = str;
int n=str.length();
ArrayBoundedStack s =new ArrayBoundedStack(n/2);// Creating array of half of size of string
for(int i=0;i<n/2;i++)
{
s.push(str.charAt(i));
}
for(int i=n-n/2;i<n;i++)
{
if(s.pop()!=str.charAt(i))
{
throw new Exception("NotPalindromeError");// throwing exception if the string is not string
}
}
this.palindrome=this.original;
}
}
code snap:
ArrayBoundedStack class:
public class ArrayBoundedStack {
private int size;
char[] arr;
int i=0;
public ArrayBoundedStack(int size) {
super();
this.size = size;
arr=new char[size];
}
public void push(char c)
{
arr[i++]=c;
}
public char pop()
{
return arr[--i];
}
public char peek()
{
return arr[i-1];
}
}
code snap:
main method:
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner src=new Scanner(System.in);
String s=src.nextLine();
Palindrome p=new Palindrome(s);
System.out.println("Palindrome is:"+p.palindrome);
}
}
code snap:
output for a string which is a palindrome:
output for a string which not a palindrome: