‹ Back to the paper
Question 5(i)
6 marks
Computer ScienceISC 2022 Computer Science - Specimen paper (Semester 2), Paper 1ProgramObjects
Write the program described below.
Design a class Check which checks whether a word is a palindrome or not. (Palindrome words are…
Design a class Check which checks whether a word is a palindrome or not. (Palindrome words are those which spell the same from either ends). Example: MADAM, LEVEL etc.
The details of the members of the class are given below:
Class name: Check
Data members/instance variables:
wrd: stores a word
len: to store the length of the word
Methods/Member functions:
Check(): default constructor
void acceptword(): to accept the word
boolean palindrome(): checks and returns ‘true’ if the word is a palindrome otherwise returns ‘false’
void display(): displays the word along with an appropriate message
Specify the class Check giving details of the constructor, void acceptword(), boolean palindrome() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.
Answer
Answer
import java.util.*;
class Check
{
String wrd;
int len;
Check()
{
wrd = "";
len = 0;
}
void acceptword()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
wrd = sc.next();
len = wrd.length();
}
boolean palindrome()
{
for (int i = 0; i < len / 2; i++)
if (wrd.charAt(i) != wrd.charAt(len - 1 - i))
return false;
return true;
}
void display()
{
if (palindrome())
System.out.println(wrd + " is a palindrome word");
else
System.out.println(wrd + " is not a palindrome word");
}
public static void main(String[] args)
{
Check ob = new Check();
ob.acceptword();
ob.display();
}
}The method palindrome() compares the characters from both ends moving towards the middle; any mismatch returns false. Sample run: MADAM gives "MADAM is a palindrome word".