问题描述:

So im having troubles with my Console Application. Im trying to implement a interface with some methods into my class. But i cant really get the hang of it.

  • im supposed to push letters (char) into my Stack with a push method from the class.

  • I need to pop them from the stack and write out each char from the stack into the console. I should also check if the Stack is empty with a isEmpty method, which I think is correctly done ATM.

  • I've also done a stack in the class, because I'm trying to do something with the methods. But it doesn't seem to affect the stack that is created in the program.

The problem I get is that nothing is happening. When I start the application the console pops and runs the code and waits for the Console.Read() to happen.

Hope you understand, the code is kind of straight forward. I'll post the Interface, Class and program code.

Interface code:

public interface IStackInterface

{

char peek();

char pop();

void push(char nytt);

bool isEmpty();

}

Class Code:

public class StackClass : IStackInterface

{

Stack<char> stacken = new Stack<char>();

public StackClass()

{

}

public bool isEmpty()

{

if (stacken.Count == 0)

{

return false;

}

else

{

return true;

}

}

public char peek()

{

return stacken.Peek();

}

public char pop()

{

return stacken.Pop();

}

public void push(char nytt)

{

stacken.Push(nytt);

}

}

Program code:

static void Main(string[] args)

{

StackClass stacken = new StackClass();

try

{

stacken.push('t'); stacken.push('s');

stacken.push('ä'); stacken.push('b');

stacken.push(' ');

stacken.push('r'); stacken.push('ä');

stacken.push(' '); stacken.push('m');

stacken.push('o'); stacken.push('g');

stacken.push('a'); stacken.push('L');

}

catch (InvalidOperationException e)

{

Console.WriteLine(e.Message);

}

while (!stacken.isEmpty())

{

Console.WriteLine(stacken.pop());

}

Console.Read();

}

Best Regards.

网友答案:

Your code does not do as you expect purely for the reason that your implementation of isEmpty is the wrong way round. It should return true when the count is zero.

网友答案:

You have a logical bug in your code... isEmpty returns the opposite of what you want. Also, you can optimize it this way:

public bool isEmpty()
{
    return (stacken.Count == 0);
}

or even:

public bool isEmpty()
{
    return stacken == null ? true : (stacken.Count == 0);
}
相关阅读:
Top