我只是将我的所有代码都放在这里以防一些代码出现问题,而不是在“SelectName()”子代中。
Module Module1
Dim selectednames As String = ""
Dim index As Short = 0
Dim inarray As Boolean = False
Dim amountofkeys As Short
Dim namesarray() As String
Dim names As String = ""
Dim input As String = ""
Dim totalnames As Short = 0
Dim indexofcomma As Short = 0
Sub Main()
Console.Write("Howmany keys are there to be given away? ")
amountOfKeys = CShort(Console.ReadLine())
Start()
While Not amountofkeys = -1
SelectName(names, totalnames)
amountofkeys = amountofkeys - 1
End While
Console.Write("The winners are: " & selectednames)
Console.ReadLine()
End Sub
Sub SelectName(ByVal names As String, ByVal totalnames As Short)
ReDim namesarray(totalnames - 1)
If inarray = False Then
For x = 0 To totalnames - 1
indexofcomma = InStr(names, ",")
namesarray(x) = Left(names, indexofcomma - 1)
names = Mid(names, indexofcomma + 1, (Len(names)))
Next
inarray = True
End If
Randomize()
index = Int(Rnd() * (totalnames - 1))
For x = 0 To totalnames - 1
Debug.Print("namesarray(" & x & ") = " & namesarray(x))
Next
selectednames &= namesarray(index) & " "
movenames()
End Sub
Sub movenames()
For x = index To totalnames - 1
namesarray(index) = namesarray(index + 1)
Next
totalnames -= 1
End Sub
Sub Start()
Console.WriteLine("Enter all the viewer's names, one by one.")
Console.WriteLine("Once all names have been entered, press 0.")
input = Console.ReadLine()
While Not input = "0"
names &= input & ","
totalnames += 1
input = Console.ReadLine()
End While
End Sub
End Module
这是它的作用的图像(我想你可以看到出了什么问题)
13个输入,预期3个输出,仅给出1个输出。
任何人都有机会帮助我找出问题所在?
从我到目前为止所知,它正在做正确数量的循环等。只要它开始为第二个游戏键生成“赢家”它就不会从namesarray获得字符串值
另外,为什么
For x = 0 To totalnames - 1
Debug.Print("namesarray(" & x & ") = " & namesarray(x))
Next
没有给我调试输出?
答案 0 :(得分:1)
简化您的问题。
将名称设为List(Of String),而不是在字符串中添加“,name”,而是使用names.Add(namereadfromconsole)
。而不是通过名称字符串循环,一个简单的names.Contains(thename)可以替换你正在使用的inArray
标志。而不是movenames()
来电,简单names.Remove(nametoremove)
。
只要Debug.Print()调用没有显示任何内容,请尝试检查,在Options-> Debugging-> General-> [x]下将所有输出窗口文本重定向到立即窗口。
答案 1 :(得分:1)
主要错误在于
For x = index To totalnames - 1
namesarray(index) = namesarray(index + 1)
Next
我认为你应该这样做
For x = index To totalnames - 1
namesarray(x) = namesarray(x + 1)
Next
请记住,Random index会导致代码崩溃,如果它等于namesarray中的最大值。 (例如:totalnames=6
和index = Int(Rnd() * (totalnames - 1))
导致index = 5,然后movenames崩溃)
Debug.Print输出转到立即窗口或输出窗口,而不是代码打开的控制台窗口。使用Console.Writeline。