我目前正在为一款名为Caladont的游戏编写代码。
该游戏是关于第一个玩家说出该单词,而下一个玩家必须说出以上一个单词的最后两个字母开头的单词。
当我要检查单词是否包含少于3个字母或它是否为空时,就会出现问题。
在第一个循环中,如果要填充的列表仍然为空,则一切正常。
但是,在我键入5个或更多单词并键入一个字母或将其保留为空之后,它会打印两条"You've lost!"
消息,这意味着if语句中的代码将被忽略,因为它将bool变量更改为false,并且应该退出While循环。
我尝试用ok = false
替换Exit While
,条件是检查单词是否包含少于3个字母并且它可以工作,但是我想了解问题所在。
代码也可以在Caladont game - GitHub处找到:
Module Module1
Sub Main()
Kaladont()
End Sub
Sub Kaladont()
Const msg As String = "You've lost!"
Dim list As New List(Of String)
Dim word As String
Dim i As Integer
Dim ok As Boolean
ok = True
While ok
Console.Write("Insert word:")
word = Console.ReadLine()
list.Add(word)
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
End If
If list.Count > 1 Then 'Skip checking first word
For i = 0 To list.Count - 2
If word.ToLower = lista(i).ToLower Then
Console.WriteLine(msg)
ok = False
End If
Next
If LastTwo(word) = "ka" Or LastTwo(word)="nt" Then
Console.WriteLine("KALADONT! You won!")
ok = False
End If
If FirstTwo(list.Last) <> LastTwo(list(list.Count - 2)) Then
Console.WriteLine(msg)
ok = False
End If
End If
End While
Check()
End Sub
Function FirstTwo(ByVal s1 As String) As String
Return Left(s1.ToLower, 2)
End Function
Function LastTwo(ByVal s2 As String) As String
Return Right(s2.ToLower, 2)
End Function
Sub Check()
Dim sign As Char
Console.WriteLine("Do you want to start new game? y\n")
sign = Console.ReadLine()
If sign = CChar("y") Then
Console.Clear()
Kaladont()
ElseIf sign = CChar("n") Then
Exit Sub
End If
End Sub
End Module
有解决方案吗?
答案 0 :(得分:0)
即使将ok设置为false,它仍将进入另一个循环,您将需要使用Else
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
Else If list.Count > 1 Then 'Skip checking first word
另一种方法是使用End while退出while。
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
Exit While
End If