I am not sure why this is giving me an error. I am in the method pop and i want to return the value stored at the position top. Though it says they are incompatible types. I do not see why it should be a problem as I only want the character to be printed out at the position. This is part of a bigger program just so you know and will be getting the word from a different class.
public class Stack
{
private int maxSize;
private String[] stackArray;
private int top;
/**
* Constructor for objects of class Stack
*/
public Stack(int a)
{
maxSize = a;
stackArray = new String [maxSize];
top = -1;
}
public void push(String j)
{
top++;
stackArray[top] = j;
}
public char pop()
{
return stackArray[top--];//Error is here
}
}
stackArray
is a string
array and the return type of your method is char
.
Reversing word with Stack
If you want to reverse a word with your Stack
object, consider using a char
array and not a String array
.
class Stack
{
private int maxSize;
private char[] stackArray;
private int top;
/**
* Constructor for objects of class Stack
*/
public Stack(int a)
{
maxSize = a;
stackArray = new char [maxSize];
top = -1;
}
public void push(char j)
{
top++;
stackArray[top] = j;
}
public char pop()
{
return stackArray[top--];
}
public int getSize(){
return maxSize;
}
}
And the following test case :
String s = "test";
Stack st = new Stack(s.length());
for(char c : s.toCharArray())
st.push(c);
for(int i = 0; i <st.getSize();i++)
System.out.print(st.pop());
Output :
tset
You're pushing String
s onto your array (which is an array of String
s), and trying to pop a char
. Change your method to
public String pop() {
return stackArray[top--];
}
Your signature says you are returning a char, but you are returning a String.
change
public char pop()
to
public String pop()
You have two choices
- In the
pop
method, return the char you want from the top string
- where you call
pop
, get the char from the String that was returned from pop
.
The second choice is probably the better of the two as one would expect pop
to return whatever type is on the stack.