Hello,
Lets assume i have 2 methods 1 that places a element on the array and one that removes it.
const int Max = 10;
int[] table= new int[Max];
I would like to call it up like this:
s1.Place(5); // 5 0 0 0 0 0 0 0 0 0 0
s1.Place(9); // 5 9 0 0 0 0 0 0 0 0 0
s1.Remove(9); // 5 0 0 0 0 0 0 0 0 0 0
I would only like to use : using system for this.
The result i get right now when i run the program is s1 = "nameofprogram" "name of class object"
Normally i should get 0 0 0 0 0 0 0 0 0 0 to begin with.
Any ideas how i can exactly add or remove those elements on the array?
public void Place(int g)
{
if (top == Max)
{
throw new Exception("Stack overflow...");
}
else
{
table[top] = g;
top++;
}
....
Best Regards.
EDIT:
Thanks to jon for the stringbuilder i finally get display of the values in the array. Although i am still not able to remove any elements from the array with calling up s1.remove for example
class Stack: Object
{
private int top;
private int Value;
const int Max = 5;
int[] tabel = new int[Max];
public void Push(int g)
{
if (top == Max)
{
throw new Exception("Stack overflow...");
}
else
{
tabel[top] = g;
top++;
}
}/*Push*/
public int Pop()
{
return Value; //??
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
foreach (int value in tabel)
{
builder.Append(value);
builder.Append(" ");
builder.Append(top); // how to make this so it displays Top: .....value???
}
return builder.ToString();
}
}/*Stack*/
Above is the object class, beneath the driver where the program gets its values from.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stack
{
class ConsCode
{
public void ExecuteProgram()
{
Console.Title = "StackDemo";
Stack s1 = new Stack(), s2 = new Stack();
ShowStack(s1, "s1");
ShowStack(s2, "s2");
Console.WriteLine();
int getal = TryPop(s1);
ShowStack(s1, "s1");
TryPush(s2, 17);
ShowStack(s2, "s2");
TryPush(s2, -8);
ShowStack(s2, "s2");
TryPush(s2, 59);
ShowStack(s2, "s2");
Console.WriteLine();
for (int i = 1; i <= 3; i++)
{
TryPush(s1, 2 * i);
ShowStack(s1, "s1");
}
Console.WriteLine();
for (int i = 1; i <= 3; i++)
{
TryPush(s2, i * i);
ShowStack(s2, "s2");
}
Console.WriteLine();
for (int i = 1; i <= 6; i++)
{
getal = TryPop(s2);
//use number
ShowStack(s2, "s2");
}
}/*ExecuteProgram*/
private void TryPush(Stack s, int Value)
{
try
{
s.Push(Value);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}/*TryPush*/
private int TryPop(Stack s)
{
try
{
return s.Pop();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return 0;
}
}/*TryPop*/
private void ShowStack(Stack s, string stackName)
{
Console.WriteLine("{0} = {1}", stackName, s);
}/*ShowStack*/
}/*ConsCode*/
}