In: Computer Science
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
Greetings!!!!!!!!!!!!!!!
Please find the required program and few sample run screen shots as below.
import java.io.*;
import java.util.*;
// class StackX
class StackX
{
// word data field as private
String word;
//Constructor of StackX
public StackX()
{
}
/* revNoDup function, which takes word as argument and print the word in
reverse order with removal of consecutive character */
void revNoDup(String str)
{
//Stack class of java is used.
// created object of class Stack.
Stack <Character> stack =new Stack<>();
//Prevchar is used to check for consecutive character.
char prevchar=' ';
//looping entire string character by character
for(int i = 0; i < str.length(); i++)
{
//Taking current character in currentchr variable.
char currentchr = str.charAt(i);
/* Checking current character with previous one and ignoring if
matching occur */
if(currentchr!=prevchar)
stack.push(currentchr);
//Keeping track of previous character for comparison.
prevchar=currentchr;
}
//popping element from the stack and displaing reverse word.
while(!stack.empty())
{
Character reverseChar = (Character) stack.pop();
System.out.print(reverseChar);
}
}
}
public class Test
{
public static void main(String[] args) {
//System.in is used for standard input stream
Scanner scannerObj= new Scanner(System.in);
//take input word from the user
System.out.print("Enter a word: ");
String strWord= scannerObj.nextLine();
//Create object of the StackX class created as above.
StackX stkObj = new StackX();
//call revNoDup function, passing word as parameter.
stkObj.revNoDup(strWord);
}
}
Thank You