如何在批处理文件中为数字变量指定名称

时间:2013-11-12 08:49:18

标签: batch-file

我有一个数字生成器的代码,它随机选择1到30之间的数字。我想使用批处理文件来为每周做出晚餐选择,所以我不必自己做。我的问题是,我不知道如何将晚餐名称分配给数字,然后我想要检查晚餐是否符合晚餐评级,这样可以确保晚餐健康足够的,如果它没有达到评级,那么代码将/应该让它重新选择晚餐。 这是数字生成器:(不要告诉我,我可以做得更好,我有点像菜鸟)

@echo off
echo.
echo             Welcome %username%
ping localhost -n 2 >nul
echo        This Is The Dinner Selector.
ping localhost -n 2 >nul
echo This Program Will Select The Weekly Dinner.
ping localhost -n 2 >nul
set /a selection1=%random% %%30 +1
set /a selection2=%random% %%30 +1
set /a selection3=%random% %%30 +1
set /a selection4=%random% %%30 +1
set /a selection5=%random% %%30 +1
echo %selection1%
echo %selection2%
echo %selection3%
echo %selection4%
echo %selection5%

请帮助我找到解决问题的办法,我很厌倦自己选择健康的晚餐。

2 个答案:

答案 0 :(得分:0)

好的,不完全确定你想要什么,但可能就是这样:

Main.bat

@echo off
setlocal Enabledelayedexpansion
echo.
echo             Welcome %username%
sleep 2
echo        This Is The Dinner Selector.
sleep 2
echo This Program Will Select The Weekly Dinner.
sleep 2
Echo.
Echo.
Echo How healthy do you want your food [0 - Anything :: 9 - max]
choice /c "1234567890" /n /m ": " /d 0 /t 20
set rate=%errorlevel%
set /a count=0
set /a total=0
for /f %%a in (Dinner.txt) do (set /a total+=1)


:: START LOOP ----------------------
:choose
set /a count+=1
:random
set /a process=0
set sel=
set /a sel=%random% %% %total% + 1

for /f "tokens=1,2 delims=:" %%a in (Dinner.txt) do (
    set /a process+=1
    if !process! EQU !sel! (
        if %%b GEQ !rate! (
            set sel=%%a
            )
        )
    )

if "%sel%" EQU "" (Echo %sel%
) Else (
goto :random)

if count leq 5 goto choose
:: END LOOP   ----------------------

cls
Echo Enjoy your meal!
sleep 3
Exit

注意如果健康状况很高,这会导致重复和/或无限/非常长的循环。

Dinner.txt

这是您所有选择的列表。当批处理文件适应其大小时,它可以是您想要的长/短。

总共有5个选择

; This is how you format the dinner file: [Food]:[Healthyness 0 - 9]
; Lines starting with semi-colons are ignored (if you want a blank line comment it)
; Examples:
;
; Vegetarian
Salad:9
Pasta:8
;
;
; Non-Veg
Uncooked Meat:2
Pizza:5
Burger:6
Pure Oil:0

我还没有对此进行测试,并且还可以保证会出现错误,因为它非常平凡且很长,但我确信会有一些错误测试可以完成这项工作

莫纳。

答案 1 :(得分:0)

管理多个相同类型的元素(每个元素由索引标识)的方法是通过array。在您尝试使用arrays in Batch之前,我强烈建议您了解此主题以及环境变量的延迟扩展。获得基础知识后,您可以执行以下操作:

set dinner[1]=Name of first dinner
set dinner[2]=Name of second dinner
set dinner[3]=Name of third dinner, etc

或者,以更先进的方式:

set i=0
for %%a in (Pasta:9 Dessert:5 Soup:8) do (
   for /F "tokens=1,2 delims=:" %%b in ("%%a") do (
      set /A i+=1
      set dinner[!i!]=%%b
      set rating[!i!]=%%c
   )
)

例如:

set /A selection=%random% %% 30 + 1
if !rating[%selection%]! gtr 7 echo Rating of !dinner[%selection%]! correct: greater than 7