Reversing word with Stack

2019-08-27 20:02发布

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
   }

}

4条回答
做个烂人
2楼-- · 2019-08-27 20:38

You're pushing Strings onto your array (which is an array of Strings), and trying to pop a char. Change your method to

public String pop() {
    return stackArray[top--];
}
查看更多
倾城 Initia
3楼-- · 2019-08-27 20:39

Your signature says you are returning a char, but you are returning a String.

change

public char pop()

to

public String pop()
查看更多
Lonely孤独者°
4楼-- · 2019-08-27 20:53

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
查看更多
Evening l夕情丶
5楼-- · 2019-08-27 21:02

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.

查看更多
登录 后发表回答