检查输入是否为整数

Check for input being an integer

我知道这里有很多关于此的问题,但 none 的答案似乎对我有用。我试图让我的程序检查给定的输入是 1 还是 0,我真的遇到了死胡同。我对编程还是个新手,互联网帮助加载了这方面的内容,但我找不到任何东西

这个程序是我正在为我的课程做的事情,我试图实现它的细节如下

Public Class Form1
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Sensor1, Sensor2, Sensor3, SensorTotal, Temp As Integer

    Sensor1 = InputBox("Please enter the state of Sensor 1, 0 for off, 1 for on", "System")
    If Sensor1 = 1 Then PictureBox5.Hide()

    Sensor2 = InputBox("Please enter the state of Sensor 2, 0 for off, 1 for on", "System")
    If Sensor2 = 1 Then PictureBox6.Hide()

    Sensor3 = InputBox("Please enter the state of Sensor 3, 0 for off, 1 for on", "System")
    If Sensor3 = 1 Then PictureBox7.Hide()

我需要检测输入框中每个传感器的输入是 1 还是 0。遇到了死胡同,在我解决/找到完成此计划的方法之前,我无法在此计划上取得任何进展。

它需要检查给定值是作为整数给出的 1 还是 0,如果不是 1 或 0,则需要再次询问并继续询问,直到给出 1 或 0

您可以使用 Int32.TryParse 和以下循环:

Dim Sensor1, Sensor2, Sensor3, SensorTotal, Temp As Integer
Dim sensor1Valid, sensor2Valid, sensor3Valid As Boolean
Dim validSensorValues = {0, 1}

While Not sensor1Valid
    Dim s1 As String = InputBox("Please enter the state of Sensor 1, 0 for off, 1 for on", "System")
    sensor1Valid = Int32.TryParse(s1, Sensor1) AndAlso validSensorValues.Contains(Sensor1)
End While
If Sensor1 = 1 Then PictureBox5.Hide()

While Not sensor2Valid
    Dim s2 As String = InputBox("Please enter the state of Sensor 2, 0 for off, 1 for on", "System")
    sensor2Valid = Int32.TryParse(s2, Sensor2) AndAlso validSensorValues.Contains(Sensor2)
End While
If Sensor2 = 1 Then PictureBox6.Hide()

While Not sensor3Valid
    Dim s3 As String = InputBox("Please enter the state of Sensor 3, 0 for off, 1 for on", "System")
    sensor3Valid = Int32.TryParse(s3, Sensor3) AndAlso validSensorValues.Contains(Sensor3)
End While
If Sensor3 = 1 Then PictureBox7.Hide()

您需要使用 Integer.TryParse - 最好将其全部放在一个单独的函数中:

Public Function GetInputState(sensorNum as Integer) As Integer
    Dim inputValue as Integer = -1
    Do 
        Dim inputString = InputBox("Please enter the state of Sensor " & sensorNum &  ", 0 for off, 1 for on", "System")
        If Not Int32.TryParse(inputString, inputValue) then inputValue = -1
    Loop Until inputValue = 1 OrElse InputValue = 0
    Return inputValue
End Function

Int32.TryParse return 如果解析成功则为真,因此如果解析失败它会将值设置为 -1 以确保它再次循环并请求一个数字。如果解析成功,它会检查值是零还是 1。

那么你可以这样确定输入的值是1还是0:

Sensor1 = GetInputState(1)
Sensor2 = GetInputState(2)
Sensor3 = GetInputState(3)