如何设置BATCH if语句来选择随机预定义变量?

时间:2015-04-16 00:11:27

标签: windows batch-file

如何根据用户输入设置我的if语句调用不同的预定义变量。

实施例1是红色2是橙色3是蓝色4是随机的。 如果用户输1,他们就会变红。如果他们放2,他们会变成橙色。如果他们放3,他们就会变蓝。如果他们放4,他们会得到红色,橙色或蓝色。

3 个答案:

答案 0 :(得分:0)

以下脚本显示了一种方法,使用颜色数组和对变量进行双重扩展的方法(允许数组访问):

@setlocal enableextensions enabledelayedexpansion
@echo off

set color[1]=red
set color[2]=orange
set color[3]=blue

:loop
    set /p inp="Enter a number [1=red, 2=orange, 3=blue, 4=random]: "
    if "%inp%"=="4" set /a "inp = %RANDOM% %% 3 + 1"
    call set color=%%color[%inp%]%%
    if "%color%"=="" goto loop

endlocal && set color=%color%

对于更通用的解决方案,您可以查看以下脚本,该脚本可以更好地处理任意颜色的提示:

@setlocal enableextensions enabledelayedexpansion
@echo off

rem Clear out all color variables then create array.

set color=junk
for /f "delims==" %%a in ('set color') do set %%a=

set /a "count = 0"
set /a "count = count + 1" && set color[!count!]=red
set /a "count = count + 1" && set color[!count!]=orange
set /a "count = count + 1" && set color[!count!]=blue
set /a "count = count + 1" && set color[!count!]=green
set /a "next = count + 1"

rem Loop until color is valid.

:loop
    echo.Choices:
    for /l %%a in (1,1,%count%) do (
        set value=!color[%%a]!
        echo.   %%a. !value!
    )
    echo.   %next%. Random choice from above

    set /p inp="Enter a number: "
    rem set inp=1

    rem Special handling, choose random value

    if "%inp%"=="%next%" set /a "inp = %RANDOM% %% count + 1"

    call set color=%%color[%inp%]%%
    if "%color%"=="" goto loop

rem Exit local scope, "leaking" color value.

endlocal && set color=%color%

答案 1 :(得分:0)

@ECHO Off
SETLOCAL
SET "choices=1=red 2=blue 3=green 4=random"
SET /p inp="[%choices%]: "
FOR /f %%a IN ('echo %choices: =^&echo %') DO SET /a maxchoice=%%a
IF "%inp%"=="%maxchoice%" SET /a inp=%RANDOM% %% (maxchoice - 1) +1
FOR /f "tokens=1,2" %%a IN ('echo %choices: =^&echo %') DO IF "%%a"=="%inp%" SET "hue=%%b"
ECHO %hue%
GOTO :EOF

这是我的版本。您需要做的就是按照弹跳球设置choices并确保random是最后一个选择。

答案 2 :(得分:0)

我开始写评论作为对新paxdiablo解决方案的回复,但它变得太大了,所以我更喜欢在这里编写我自己的解决方案,包括所有这些点:

@echo off
setlocal EnableDelayedExpansion

rem Create the color array
set n=0
for %%a in (red orange blue green) do (
   set /A n+=1
   set color[!n!]=%%a
)
set /A next=n+1

rem Show the available colors menu
echo Choices:
echo/
for /L %%i in (1,1,%n%) do echo    %%i. !color[%%i]!
echo    %next%. Random choice from above
echo/

rem Loop until color is valid
:loop
   set /P "inp=Enter a number: "
   if "%inp%" equ "%next%" set /A inp=%random% %% n + 1
   set color=!color[%inp%]!
if "%color%" equ "" goto loop

echo/
echo Color: %color%