我需要用户填写一个整数,但是下面显示的代码也允许加倍。如何更改为仅允许整数?

do{

    $opgegevenGetal = read-host "Enter an integer"

    if(![bool]($opgegevenGetal -as [int])){
        write-host "Only integers please"
    }

}

until ([bool]($opgegevenGetal -as [int]))

最佳答案

尝试:

do{
    $opgegevenGetal = read-host "Enter an integer"
    $a = ""
    if(  ![int32]::TryParse( $opgegevenGetal , [ref]$a ))
      {
        write-host "Only integers please"
      }
  } until ($a -gt 0)

接受0作为输入的代码:
do{
    $opgegevenGetal = read-host "Enter an integer"
    $a = ""
    if(  ![int32]::TryParse( $opgegevenGetal , [ref]$a ))
      {
        write-host "Only integers please"
      }
  } until ($a -gt 0 -or $opgegevenGetal -eq '0')

要么:
do{
    $opgegevenGetal = read-host "Enter an integer"
    $a = ""
    $b = [int32]::TryParse( $opgegevenGetal , [ref]$a )
    if(  !$b)
      {
        write-host "Only integers please"
      }
  } until ($b)

07-27 18:31