Home > Net >  How to loop in visual basic?
How to loop in visual basic?

Time:01-06

So i have an assignment and im struggling to add a loop. I want to make 3 valid answers for the question and any other inputs would cause the code to say invalid vehicle type and ask the questions again.

I tried doing it for a few days but i cant make the loops as it just ends when i run the code or goes to the next question even if the answers invalid

The programs 2019 visual basic Code:

Dim vehicle_type As string
Dim days_required as integer
Dim insurance_cover as string
Dim new_existing as string
Dim B_S_G As string
Dim total_hire_cost as single
Const lowemission as single =15.5
Const zero emission as single =20.0
Const electric as single 32.0

Vehicle_type = inputbox("enter any 3 vehicle types, lowemission, zeroemission or electric")

Do
  Msgbox("invalid vehicle type")
Loop until vehicle type <> lowemission or zeroemission or electric

CodePudding user response:

Give this a go:

Do
    vehicle_type = InputBox("enter any 3 vehicle types, lowemission, zeroemission or electric")
    If vehicle_type = "lowemission" Or vehicle_type = "zeroemission" Or vehicle_type = "electric" Then
        Exit Do
    End If
    MsgBox("invalid vehicle type")
Loop

CodePudding user response:

I'd create an array to hold your valid responses:

Dim index As Integer
Dim types() As String = {"lowemission", "zeroemission", "electric"}
Dim strTypes As String = String.Join(", ", types)
Do
    vehicle_type = InputBox("Valid Vehicle types:" & vbCrLf & strTypes, "Enter vehicle type").ToLower().Trim()        index = Array.IndexOf(types, vehicle_type)
    If index = -1 Then
        MessageBox.Show("invalid vehicle type")
    End If
Loop While index = -1

Looks like:

enter image description here

  • Related