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
}
}
You're pushing
String
s onto your array (which is an array ofString
s), and trying to pop achar
. Change your method toYour signature says you are returning a char, but you are returning a String.
change
to
stackArray
is astring
array and the return type of your method ischar
.If you want to reverse a word with your
Stack
object, consider using achar
array and not aString array
.And the following test case :
Output :
You have two choices
pop
method, return the char you want from the top stringpop
, get the char from the String that was returned frompop
.The second choice is probably the better of the two as one would expect
pop
to return whatever type is on the stack.