我的do / while循环代码无法正常工作,我无法弄清楚问题出在哪里

时间:2019-06-08 15:32:26

标签: powershell do-while

我应该更正此代码,并使其显示正确的输出。用户输入的数字介于1到10之间,其他任何数字都应提示用户该数字无效。

我尝试将do..whiledo..until结合使用,但我要么不断陷入无限循环,要么不显示有效或无效数字。

[int]$UserGuess = Read-Host "pick a number between 1 and 10"

do {
    $UserGuess = Read-Host "Invalid number. Please re-enter (1 - 10)"
} while ($UserGuess -lt 1 -and $UserGuess -gt 10) {
}
do {
    Write-Host "You guessed: $UserGuess"
} until ($UserGuess -gt 1 -and $UserGuess -lt 10) {
}

它显示无限循环。

3 个答案:

答案 0 :(得分:1)

您应使用-or而不是-and,并检查第一个条目。结果的显示不需要直到循环。并释放空的脚本块。

[int]$UserGuess = Read-Host "pick a number between 1 and 10"

while ($UserGuess -lt 1 -or $UserGuess -gt 10)  
{
    $UserGuess = Read-Host "Invalid number. Please re-enter (1 - 10)"
} 

Write-Host "You guessed: $UserGuess"

答案 1 :(得分:1)

就像mhu回答的那样,首先您需要使用-or来代替,因为11不能同时大于10和小于10。同样,do..while loop在这种情况下也不可取,因为它至少每次都必须提供一个输出:

  

无效的号码。请重新输入(1-10)

即使我输入了正确的数字。如果要使用它,则还必须使用if statement来确保其正常工作,如下所示:

[int]$UserGuess = Read-Host "pick a number between 1 and 10"

do {
    if (($UserGuess -gt 10) -or ($UserGuess -lt 1))
    {
        $UserGuess = Read-Host "Invalid number. Please re-enter (1 - 10)"
    }
} while (($UserGuess -gt 10) -or ($UserGuess -lt 1)) {
}

    Write-Host "You guessed: $UserGuess"

答案 2 :(得分:0)

为您的理解提供了另一个示例,还添加了一些注释

$Numbers =1..10
$Userinput =read-host "Please enter number between 1 and 10 "

while(1){ ## loop for eternity

if ( $Numbers -contains $Userinput) ## if your list contains user entered number
{

write-host "You have entered right input, you guessed : $userinput"
$prompt =Read-Host "do you want to still play : Press Y for Yes ,N for No"

Switch($prompt){ ## check for second prompt

'Y' {continue}
'N' {return}
Default { "Wrong option,Press Y or N only " }

              }

}

## if user enters wrong input, he wwill be prompted again
Write-Host "You have entered wrong input,Please enter again"
$Userinput =read-host "Please enter number between 1 and 10 "

}