使用多个 else if 语句

Using multiple else if statements

我试图用 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

当我运行程序时,错误显示:"Expected end of statement"。我在这里没有看到问题,因为在所有这些 else if 语句之后我有 end if

去掉elseif之间的space,变成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 之间的附加 space,您开始嵌套在 else 分支中的新 if 语句,而不是继续第一个 if语句。嵌套的 if 语句需要它们自己的 end if,这就是您收到错误的原因。

一个Select Case通常是一个simpler/clearer结构,用于根据单个变量值选择操作

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

使其工作的最小改进:

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

检查作为执行的操作符的类型和范围。