Getting a null reference exception trying to push a zero to a stack

Well I am on my last day of school trying to finish a program and I can't for the life of me get past this null reference exception. My code is supposed to average together [count] numbers entered by the user using a stack of Integers. It was throwing a null reference exception because it attempted to get the count of the stack which was empty, so I added the line to Push a zero on to it. The program now stops at that line with the same error (nullreferenceexception). If I change the stack to accept Strings it works fine, but I need it to accept Integers. Thanks for anyone who can help :)

Module Module1

    Sub Main()
        Dim count As Integer = 16
        Dim stack As New Stack(Of Integer)
        stack.Push(0)
        Console.WriteLine("Please enter " & count & " numbers")
        Do While stack.Count - 1 = count
            stack.Push(Console.ReadLine)
            If Not IsNumeric(stack.Peek) Then
                Console.WriteLine(stack.Pop & " is not a number please try again.")
            End If
        Loop
    End Sub

End Module

You're declaring a variable named stack , but you are not actually creating a Stack object. Do this instead (with the New keyword):

Dim stack As New Stack(Of Integer)

Without New , the variable will contain a null reference, which is why you were getting the NullReferenceException whenever you attempt to do anything with that variable.

链接地址: http://www.djcxy.com/p/42830.html

上一篇: 使用Nullable(Of Date)处理空日期的数据库表

下一篇: 获取空引用异常,尝试将零推入堆栈