已编辑代码以正确缩进它应该有助于突出显示该问题。错误是因为If
语句只能有一个Else
条件,If
语句的基本结构是;
If <boolean condition> Then
<true outcome>
Else
<false outcome>
End If
目前你有
If <boolean condition> Then
<true outcome>
Else
<false outcome>
Else
<unknown condition>
End If
多个实例,这是无效的语法,因为一个基本If
语句只能返回True
或False
。
但也有ElseIf
它允许指定多个布尔条件并返回不同的结果。
看起来像这样;
If <boolean condition> Then
<true outcome>
ElseIf <boolean condition> Then
<true outcome>
ElseIf <boolean condition> Then
<true outcome>
Else
<false outcome>
End If
根据您如何嵌套If
声明,相关代码可以像这样重写;
Randomize
value = Int((150 * Rnd + 1) * Rnd + lowerbound)
guess = InputBox("guess the number", "guess", "guess here")
If guess = value Then
Call MsgBox("correct", vbOKOnly + vbInformation + vbSystemModal, "guess")
WScript.Quit
ElseIf guess < value Then
Call MsgBox("too low", vbOKOnly + vbQuestion + vbSystemModal, "guess")
once = 1
Else
Call MsgBox("too high", vbOKOnly + vbQuestion + vbSystemModal, "guess")
End if
once = 1
Do
guess = InputBox("try again", "guess", "guess here")
If guess = value Then
Call MsgBox("correct", vbOKOnly + vbInformation + vbSystemModal, "guess")
ElseIf guess < value then
Call MsgBox("too low", vbOKOnly + vbQuestion + vbSystemModal, "guess")
Else
Call MsgBox("too high", vbOKOnly + vbQuestion + vbSystemModal, "guess")
End If
Loop
几件事情要注意有关该行
guess+inputbox("guess the number","guess","guess here")
取代了+
与=
上述
的例子,因为它不会指派的InputBox()
到guess
结果这就是我假设你正在做的事情。如果你想的InputBox()
结果串联到guess
仍然是行不通的,你将不得不使用
guess = guess + InputBox("guess the number", "guess", "guess here")
如果是这样的话,虽然我个人更喜欢使用&
超过+
字符串连接。
MsgBox()
中的括号似乎有点奇怪,如果没有将结果返回给变量,通常可以调用MsgBox()
而没有括号,如下所示;
MsgBox "correct", vbOKOnly + vbInformation + vbSystemModal, "guess"
,但如果你确实想包括括号(因为我更喜欢这样做)你可以使用Call
这样
Call MsgBox("correct", vbOKOnly + vbInformation + vbSystemModal, "guess")
避免了可怕的
Microsoft VBScript compilation error: Cannot use parentheses when calling a Sub
但仍然允许函数在没有值返回时用括号括起来。
您可能还注意到,我用Named Constants替换MsgBox()
中的硬编码数值,使其他人更容易阅读和解释它们的含义。它们也被烧成VBScript,所以没有理由不使用它们。
你想做什么思考以为我可以重新因子的代码一点点希望使其工作如你预期
Dim value, guess, msg, once
Randomize
value = Int((150 * Rnd + 1) * Rnd + lowerbound)
Do
If once = 0 Then
msg = "guess the number"
Else
msg = "try again"
End If
guess = CInt(InputBox(msg, "guess", "guess here"))
If guess = value Then
Call MsgBox("correct", vbOKOnly + vbInformation + vbSystemModal, "guess")
WScript.Quit
ElseIf guess < value then
Call MsgBox("too low", vbOKOnly + vbQuestion + vbSystemModal, "guess")
once = 1
Else
Call MsgBox("too high", vbOKOnly + vbQuestion + vbSystemModal, "guess")
once = 1
End If
Loop
事情从这个拿;
我们只需要一个InputBox()
环路内同时处理第一初始猜测和随后的“重试”的尝试。这意味着我们不再复制同一段代码,请参见DRY Principle。
InputBox()
返回一个字符串,所以起初代码试图比较一个字符串值与一个整数值,这将给出各种奇怪的结果。通过使用CInt()
转换为整数,比较开始按预期工作。
你的意思是在很多时候使用'else if'而不是'else'。 –
或者'else'下的行应该和'else'在同一行,以将它变成'else if'。另外,'lowerbound'没有被定义,因此将被视为0. –
或者,您可以使用['Select-Case'](http://www.w3schools.com/asp/vbscript_conditionals.asp)以获得更快和更具可读性码。 –