This document provides a Java method to return a given input word concatenated with its mirror image by using a stack. The method takes a string as input, pushes each character onto a stack, then pops the characters off the stack to build the reverse string which is concatenated and returned with the original input word.
Making communications land - Are they received and understood as intended? we...
Using stacks create a method in java that given a word(a string) retur.docx
1. Using stacks create a method in java that given a word(a string) returns that word and its mirror
image. or example, if the input is "example", the output must be "exampleelpmaxe".
Solution
import java.util.Scanner;
import java.util.Stack;
public class ReverseString {
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
String str = "";
Stack<String> stack = new Stack<String>();
System.out.println("Enter a string to be reversed: ");
str = scanner.nextLine();
if (str == null || str.equals("")){
System.out.println("It seems you aren't ready as yet to enter the string, ok buhbye !!");
System.exit(0);
}
for (int i=0;i<str.length();i++){
// Here we push all the characters in the string one by one into the Stack
stack.push(str.substring(i,i+1));
}
String strrev = "";
while(!stack.isEmpty()){
// Here we pop all the elements from the Stack one by one which is essentially reversing.
strrev += stack.pop();
}
System.out.println(str + "" + strrev);
}
}