Reputation: 31
This is my code so far, I need to create a reverse string so input= "hello" will output = "olleh"... The errors I'm having is in push and pop part of the code. I can't use StringBuffer. The error is -
Exception in thread "main" java.lang.Error: Unresolved compilation problems: l cannot be resolved l cannot be resolved
at E.reverse(E.java:10) at E.main(E.java:17)
Can you please help?
public class Rev {
public static String reverse(String s) {
MyStack st = new MyStack();
while (!s.isEmpty()) {
String k = st.toString();
st.push(s);
}
while (!s.isEmpty()) {
String p = st.pop();
return s;
}}
public static void main(String[] args) {
System.out.println(reverse("hello"));
}
}
Upvotes: 0
Views: 3502
Reputation: 123
A simple way is:
private Stack s = new Stack();
public void reversestack( String str )
{
for(int j = 0; j < str.length(); j++)
{
s.push( str.charAt( j ) );
}
while(s.isEmpty() != true)
{
System.out.println(s.pop());
}
}
Upvotes: 1
Reputation: 172628
How about trying like this:-
public class StringReverse {
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();
for (int i=0;i<str.length();i++){
stack.push(str.substring(i,i+1));
}
String strrev = "";
while(!stack.isEmpty()){
strrev += stack.pop();
}
System.out.println("Reverse of the string \"" + str + "\" is: \"" + strrev + "\"");
}
}
Upvotes: 0