Home > Software engineering >  How to let a stack store coordinates on a board
How to let a stack store coordinates on a board

Time:01-05

I was writing a stack that can store row and column which a user inputs through textboxes on windows forms. However when I use the code I added when you press a button it doesn't work.

Stack mystack = new Stack();
Stack.Push(Row,Column);

The error I get is "No overload for method push takes 2 arguments". How can I correct my code so it adds the row and column to the stack everytime the user presses the button.

CodePudding user response:

A Stack stores a list of objects, not a list of pairs of objects. You can only add one object at a time. If you want to store a row and column as a single value then you need to use a type that can store those two values. You could define your own type but you may as well just use the existing Point type. You should also use a generic Stack<T>, just as you would use a List<T> rather than an ArrayList.

var points = new Stack<Point>();

points.Push(new Point(column, row));

Note the order of the column and row values, because the first value should be the X (horizontal) value and the second should be the Y (vertical) value.

When you Pop, you'll get a Point value and you can then get the X and Y values from that.

CodePudding user response:

You can have a class called coordinate as follows:

    public class coordinate 
    { 
        public coordinate(double _x, double _y)
        {
            this.x = _x;
            this.y = _y;
        }
        public double x; 
        public double y; 
    }

And define the stack as below:

     Stack<coordinate> mystack = new Stack<coordinate>();
     mystack.Push( new coordinate(1,1));
  •  Tags:  
  • c#
  • Related