2012-10-17 52 views
0

我正在製作一個輸出隨機數然後組織它們的程序。訂購輸出隨機數

我正在組織數字,以便稍後我可以添加代碼以告訴用戶他或她已收到多少匹配的號碼。

該程序編譯得很好,但後來當我運行exe文件,輸出第一行隨機數後輸出崩潰。我收到的錯誤是:

索引超出了數組的邊界。

任何幫助都將不勝感激。

Option Explicit On 
Option Strict On 

Imports System 

Module Yahtzed 

Sub Main() 

    Randomize() 
    Dim Index, Values, NumberOfPlayers,Temp as Integer 
    Dim order(index) as integer 
    Dim Last As Integer = 0 'to Order.Length-2 
    Console.Write("How many people will be playing Yahtzed?: ") 
    NumberOfPlayers = convert.toint32(Console.Readline) 
    Do while NumberOfPlayers > 0 
     Index = 0 
     Do until index = 5 
      Values = CInt(Int((6 * Rnd()) + 1)) 
      Console.Write(" "&values) 
      Index += 1 
     Loop 
     Do Until Index = 0 
      If Order(Index + 1) < Order(index) 
       Temp = Order(Index + 1) 
       Order(Index + 1) = order(index) 
       Order(index) = Temp 
       Console.WriteLine(Order(Index)) 
      End if 
      index -= 1 
     loop 
     Console.Writeline 
     NumberOfPlayers -= 1 
     Console.Writeline() 
    Loop 

End Sub 

End Module 
+0

也許我在這裏的方式,但問題可能與行'Dim命令(索引)作爲整數'?你只在上面的一行聲明'index',所以不會把'Dim order(index)as integer'實質上變成'Dim order(0)as integer'?你是否已經通過代碼來確定哪一行失敗了? – LittleBobbyTables

回答

2

該代碼並不像現在這樣。你創建一些隨機數,然後把它們扔掉,然後對從未分配過任何東西的數組進行排序。此外,數組只有一個項目,所以它不能保存隨機值。

我認爲你要聲明數組的五個項目,而不是一個(如index是你創建數組時零):

然後把隨機數數組中,而不是將它們放在一個變量,其中每個隨機數將取代前一:

Index = 0 
Do until index = 5 
    order(index) = CInt(Int((6 * Rnd()) + 1)) 
    Console.Write(" " & order(index)) 
Loop 

當排序的陣列,則開始尋找在索引6(作爲可變index爲5),這是陣列外部。你會想從數組的最後一個項目開始(即在索引3)。然後你循環直到index爲-1,否則你不會比較數組中的兩個第一項。

此外,你還得繼續整理,直到有沒有更多的交換,只是經歷了一次陣不讓它排序:

Dim swapped as Boolean = True 
Do While swapped 
    index = 3 
    swapped = False 
    Do Until index = -1 
    If order(index + 1) < order(index) 
     temp = order(index + 1) 
     order(index + 1) = order(index) 
     order(index) = temp 
     swapped = True 
    End if 
    index -= 1 
    Loop 
Loop 

此排序算法稱爲Bubble Sort

另外也排序內置的框架,如果你想使用來代替:

Array.Sort(order) 

如果你會寫出來,而排序的值,你會比讓他們好幾次,所以你做他們排序後:

index = 0 
Do until index = 5 
    Console.Write(" " & order(index)) 
Loop 
+0

謝謝Guffa!非常有幫助和信息 – user1683391