首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >读取-宿主在While循环中使用if语句

读取-宿主在While循环中使用if语句
EN

Stack Overflow用户
提问于 2018-11-19 00:01:41
回答 2查看 4.4K关注 0票数 2

这应该很简单,但我做不到。我是PowerShell新手,所以我的错误可能是显而易见的。我试图使用while循环向用户请求输入,如果输入的内容不是数字,则提示用户再试一次。在bash中,它应该是这样的:

代码语言:javascript
运行
复制
while read -p "What is the first number? " first; do
if [[ $first = *[[:digit:]]* ]]; then
break   # if $first is numeric, break loop
else
echo "$first is not numeric. Enter a numeric value. "
fi
done

下面是我对PS的看法:

代码语言:javascript
运行
复制
While ($first = (Read-Host "What is the first number?") -as [double]) {
if ($first -eq $null) { Write-Host "Please enter a numeric value." }
else { break }
}

在上面的例子中,当输入一个数字时,我可以很好地中断循环,但是如果我输入一个字符串,我就看不到Write-Host语句。

EN

Stack Overflow用户

回答已采纳

发布于 2018-11-19 00:18:35

查看While行:

代码语言:javascript
运行
复制
While ($first = (Read-Host "What is the first number?") -as [double]) 

这只会在输入已经是双倍时进入/继续循环体,因为它将转换为double作为循环条件的一部分。您希望在任何输入上输入循环体,然后只检查它是否为双变量。至少,bash代码就是这样做的:

代码语言:javascript
运行
复制
While ($first = (Read-Host "What is the first number?")) {
    if ( ($first -as [double]) -eq $null) { Write-Host "Please enter a numeric value." }
    else { break }
}

或者,可以通过否定整个表达式继续使用强制转换作为条件的一部分,从而避免对尴尬的break的需要。

代码语言:javascript
运行
复制
While (-not ($first = (Read-Host "What is the first number?") -as [double])) {
    Write-Host "Please enter a numeric value." 
}
票数 4
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53366707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档