使用多个else if语句

时间:2015-06-01 11:47:04

标签: vbscript

我试图在VBScript中制作一个计算器来测试我的技能,但遇到了一个错误。我的程序使用多个else if语句来测试用户输入的内容。

以下是我的代码:

Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans

head = "Calculator"

msg1 = msgBox("Ruan's Vbscript calculator",0,head)
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)

num1 = inputBox("Enter your first number",head)
num2 = inputBox("Enter your second number",head)

if (input1 = vbcancel) then
    wscript.quit()
else if (input1 = "+") then
    ans = num1 + num2
else if (input1 = "-") then
    ans = num1 - num2
else if (input1 = "*") then
    ans = num1 * num2
else if (input1 = "/") then
    ans = num1 / num2
else
    msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if

msgAns = msgBox "Your answere is: " + head

当我运行程序时,错误显示:"语句的预期结束"。我没有在这里看到问题,因为我在所有end if次陈述之后else if

3 个答案:

答案 0 :(得分:3)

删除elseif之间的空格,并将其设为elseif。像这样:

if (input1 = vbcancel) then
    wscript.quit()
elseif (input1 = "+") then
    ans = num1 + num2
elseif (input1 = "-") then
    ans = num1 - num2
elseif (input1 = "*") then
    ans = num1 * num2
elseif (input1 = "/") then
    ans = num1 / num2
else
    msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if

使用elseif之间的额外空格,您可以在if分支中嵌套新的else语句,而不是继续第一个if语句。嵌套的if语句需要end if个自己的语句,这就是您收到错误的原因。

答案 1 :(得分:2)

使其有效的最小改进:

Option Explicit

Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans

head = "Calculator"
msgBox "Ruan's Vbscript calculator", 0, head
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
If Not IsEmpty(input1) Then
   num1 = CDbl(inputBox("Enter your first number",head))
   num2 = CDbl(inputBox("Enter your second number",head))
   if     input1 = "+" then
      ans = num1 + num2
   elseif input1 = "-" then
      ans = num1 - num2
   elseif input1 = "*" then
      ans = num1 * num2
   elseif input1 = "/" then
      ans = num1 / num2
   elseif input1 = "\" then
      ans = num1 \ num2
   else
      msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
   end if
   msgBox "Your answere is: " & ans
else
   msgBox "Aborted"
end if

对执行者留下的操作数进行类型和范围检查。

答案 2 :(得分:0)

Select Case通常是一种更简单/更清晰的结构,用于根据单个变量值选择操作

Select Case input1
    Case vbCancel
        wscript.quit()
    Case "+"
        ans = num1 + num2
    Case "-"
        ans = num1 - num2
    Case "*"
        ans = num1 * num2
    Case "/", "\" '//multiples
        ans = num1 / num2
    Case Else
        msgBox "Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces", , "Error"
End Select