Write a Java program that prompts the user to input a word (String).
The program must print the reversed word with all consecutive duplicate characters removed.
The program must contain the following classes: -
The StackX class (you can use the Java Stack class). - The Reverse class which must contain a private data field called “word” of type string, a constructor, and a void method called revNoDup(). The revNoDup() method must reverse the word and remove the consecutive duplicate characters. The revNoDup() method must print the new word (i.e. reversed with consecutive duplicate characters removed). The revNoDup() method must use a Stack to reverse the word and remove the duplicate characters. - The Test class which must contain the main() method. In the main() method, you must prompt the user to input a word (String), create an object from class Reverse, and call the revNoDup() method.
Here is a sample run:
Enter a word:
Tomorrow
woromoT
import java.io.*;
import java.util.*;
//Declaring class Stack
public class StackX {
public static void main(String[] args) {
String str;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a word: ");
str = scan.nextLine();
//Object reference fror Reverse class
Reverse reverse = new Reverse(str);
reverse.revNoDup();
}
}
class Reverse{
//Private variable word
private String word;
//Parameterized constructor
public Reverse(String str) {
word=str;
}
//Void method
void revNoDup() {
//Creating java stack class
Stack<Character> stack = new Stack<>();
for(int i=0;i<word.length();i++) {
if(i==0) {
//Appending first character of word
stack.push(word.charAt(i));
}
else {
//Validating next character with previous character
if(Character.toLowerCase(stack.peek())!=Character.toLowerCase(word.charAt(i))) {
stack.push(word.charAt(i));
}
}
}
// Creating an iterator
Iterator value = stack.iterator();
String name="";
// Displaying the characters
// after iterating through the stack
//Adding each character to name variable
while (value.hasNext()) {
name = name+value.next();
}
//Printing name variable in reverse
for(int i=name.length()-1;i>=0;i--)
System.out.print(name.charAt(i));
}
}
Sample Input and Output:
Enter a word: Tomorrow
woromoT
Enter a word: LiriLl
LiriL
//Please leave comment, if you have any doubts. THANK YOU.
Get Answers For Free
Most questions answered within 1 hours.