2013-12-07 68 views
0

這是一個非常簡單的代碼。我剛開始使用VB。我在做一個遊戲,試圖以最少的時間和最少的點擊次數來解決難題。每次我調試程序時,它都會突出顯示Clicks和FinalTime,並說Null引用異常是未處理的。我宣佈Clicks和FinalTime全球空引用異常未處理

Public Class Form1 
Dim Clicks As Integer = 0 'The variable that counts the number of times you clicked 
Dim Time As Integer 'The vairable that holds the time 
Dim TimeMin As Integer 'The variable that holds the minutes 
Dim TimeSec As Integer 'The variable that holds the seconds 
Dim FinalTime As String 'The variable that holds the final time (minutes and seconds) 
Dim NumArray() As Integer 
Dim NumArray1() As String 

Private Sub Times 

    Time = Time + 1 
    TimeSec = TimeSec + 1 
    TimeMin = Convert.ToInt32(TimeSec \ 60) 
    If Time >= 60 Then 
     Time = 0 
    End If 
    FinalTime = TimeMin & " min " & Time & " seconds" 
    lblTime.Text = FinalTime 
End Sub 
Private Sub Record(ByVal NumArray() As Integer, ByVal NumArray1() As String) 

    For i As Integer = 0 To 1000 
     NumArray(i) = Clicks 'Problem is here 
     i = +1 
     Array.Sort(NumArray) 
    Next i 
    lblRecordClicks.Text = NumArray(0) & " Clicks" 
    For k As Integer = 0 To 1000 
     NumArray1(k) = FinalTime 'Problem is here 
     k = +1 
     Array.Sort(NumArray1) 
    Next k 
    lblRecordTime.Text = NumArray1(0) 
End Sub 
+0

你在哪裏聲明'Clicks'和'FinalTime'?如果你不聲明它們,那麼它們將是空的。也許嘗試使用[Option Explicit](http://support.microsoft.com/kb/311329) – Sam

+0

我也建議打開Option Strict。您可以將它放在類文件的最頂端,或者在項目設置中全局執行。 – Ceres

+0

請添加聲明傳遞給此函數的數組的代碼以及調用此函數的代碼 – Steve

回答

2

規則#1。 VB.NET中的字符串與VB6中的字符串不一樣。

在VB6中,你可以說

Dim text as String 

,你將有text = ""初始化

在VB.NET你需要

Dim text as String = vbNullString 

Dim text as New String 

釷È同樣適用於串的陣列(或任何其他陣列)

Dim arr as String() ' This makes arr = Nothing 
arr = New String(10) { } ' This allocates an array with 11 items (0..10) 

Dim arr as String() = New String(10) {} 

Dim arr() As String = New String(10) {} 

Dim arr() = New String(10) {} 

Dim arr = New String(10) {} 

查看關聯:Classes and arrays how to initialize?