我知道这里有很多关于此的问题,但没有一个答案似乎对我有用。我试图让我的程序检查,看看给定的输入是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
答案 0 :(得分:2)
你需要使用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返回True,因此如果解析失败,则将值设置为-1以确保它再次绕过循环并请求数字。如果解析成功,则检查该值是零还是1.
然后你可以确定输入的值是1或0,如下所示:
Sensor1 = GetInputState(1)
Sensor2 = GetInputState(2)
Sensor3 = GetInputState(3)
答案 1 :(得分:1)
您可以使用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()