2017-07-30 41 views
0

我想提出一个计算器,并想知道它可能有多个IF运行ELSE命令多个If Else语句之前的答案? (批)

我当前的代码是之前回答了这个

echo 1 - Addition 
echo 2 - Subtraction 
echo 3 - Multiplication 
echo 4 - Division 
echo 5 - Exit 
set /p startans=Type 1, 2, 3, 4 or 5 then press ENTER: 
if %startans%==1 goto :addition 
if %startans%==2 goto :subtraction 
if %startans%==3 goto :multiplication 
if %startans%==4 goto :division 
if %startans%==5 goto :end 

但是,如果你输入其他的东西比这些数字,它会带你直接增加,因为它接下来在文件中。如何使ELSE命令适用于所有5个答案?

+1

在最后一个if后放置一个'goto:eof'或'goto:inputerror'。您可能会对[选择](https://ss64.com/nt/choice.html)感兴趣。 – Stephan

回答

0

批处理文件逐行解释。因此,要实现一个else分支你已经之后添加goto语句你最后的if语句:

if %startans%==5 goto :end 
goto :wrong_input 

rem all of your other jump marks here 

:wrong_input 
echo Your input is not valid 

另一种方法是使用替代IF-语法,在那里你可以嵌套IF条件:

IF "%startans%" == 1 (
    REM addition code here 
) ELSE (
    IF "%startans%" == 2 (
     REM Subtraction here 
    ) ELSE (
     REM neither addition nor subtraction code here 
     echo Your input is not valid 
    ) 
)