I am making a program that outputs random numbers and then organizes them.
I am organizing the numbers so later I can add code to tell the user how many matching numbers he or she has received.
The program compiles fine, but then when I run the exe, after the first line of random numbers is outputted it crashes. The error I receive is:
the index is outside the boundaries of the array.
Any help at all would be gratefully appreciated.
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
The code doesn’t really make sense as it is now. You create some random numbers, then you throw them away, and sort an array that never has been assigned anything. Also, the array only has one item, so it would not be able to hold the random values.
I think that you want to declare the array for five items, not one (as
indexis zero by the time you create the array):Then put the random numbers in the array instead of putting them in a variable where each random number will replace the previous one:
When you sort the array, you start looking at index 6 (as the variable
indexis 5), which is outside the array. You would want to start at one item from the last in the array (i.e. at index 3). Then you loop untilindexis -1, otherwise you won’t be comparing the two first items in the array.Also, you have to continue sorting until there are no more swaps, just going through the array once doesn’t make it sorted:
This sorting algorithm is called Bubble Sort.
There is also sorting built into the framework, if you want to use that instead:
If you would write out the values while sorting, you would get them several times over, so you do that after they are sorted: