Advertisements
Advertisements
Question
A class Flipgram has been defined to flip the letters of the left and right halves of a non-heterogram word. If the word has odd number of characters, then the middle letter remains at its own position.
A heterogram is a word where no letter appears more than once.
Example 1: INPUT : BETTER
OUTPUT: TERBET
Example 2: INPUT : NEVER
OUTPUT: ERVNE
Example 3: INPUT : THAN
OUTPUT: HETEROGRAM
The details of the members of the class are given belwo:
| Class name: | Flipgram |
| Data member/instance variable: | |
| word: | to store a word |
| Methods/member functions: | |
| Flipgram(String s): | parameterised constructor to assign word = s |
| boolean ishetero( ): | to return true if word is a heterogram else return false |
| String flip ( ): | to interchange the left and right sides of a non-heterogram word and return the resultant word |
| void display ( ): | to print the flipped word for a non-heterogram word by invoking the method flip( ). An appropriate message should be printed for a heterogram word |
Specify the class Flipgram giving the details of the constructor(String), boolean ishetero( ), String flip( ) and void display( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Code Writing
Advertisements
Solution
public class Flipgram {
private String word;
// Parameterised constructor
public Flipgram(String s) {
word = s;
}
// Method to check if the word is a heterogram
public boolean ishetero() {
// Convert to lowercase to make case-insensitive
comparison
String lowerWord = word.toLowerCase();
for (int i = 0; i < lowerWord.length(); i++) {
char currentChar = lowerWord.charAt(i);
// Check if the current character appears again
in the remaining string
if (lowerWord.indexOf(currentChar, i + 1) !=-1){
return false;
}
}
return true;
// Method to flip the left and right halves of a non-
heterogram word
public String flip() {
int length = word.length();
int half = length/2;
//1f length is even, simply swap the two halves
if (length % 2 == 0) {
String left = word substring(0, half);
String right = word.substring(half);
return right + left;
}
// If length is odd, swap halves keeping middle
character in place
else {
String left = word.substring(0, half);
String right = word substring (half + 1);
char middle = word.charAt(half);
return right + middle + left;
}
}
// Method to display the result
public void display() {
if (ishetero()) {
System.out.println("HETEROGRAM");
} else {
System.out.println(flip());
}
}
// Main method to test the class
public static void main(String[] args) {
// Test cases from the examples
Flipgram f1 = new Flip Gram("BETTER");
f1.display(); // Should print "TERBET"
Flipgram f2 = new Flip Gram("NEVER");
f2.display(); // Should print "ERVINE"
Flipgram f3 = new Flip Gram("THAN");
f3.display(); // Should print "HETEROGRAM"
}
}shaalaa.com
Is there an error in this question or solution?
