2

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

do{

    $opgegevenGetal = read-host "Enter an integer"

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

}

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

2 回答 2

5

尝试:

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)
于 2012-12-04T10:47:28.450 回答
5

克里斯蒂安回答的更紧凑的版本:

$value = 0
$read = Read-Host 'Enter an integer'
while( ![int]::TryParse( $read, [ref]$value ) ) {
  $read = Read-Host 'Only integers please'
}
于 2012-12-07T14:14:51.887 回答