Reputation:
I am making a program at school and I don't know how to end the Do...Until
loop. What I have already is a program that when a button is clicked an input box comes up asking for a password. What I then want to happen is if the user enters the wrong password, the price that appears should double and they get prompted for the password again. If they get the password correct, i want the program to exit. This is what I have already:
Public Class Form1
Private Property userPassword As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim price = 100
Dim realPassword = "hello"
Do
Dim userPassword = InputBox("Please enter the correct password to claim your money", "Claim Winnings")
If userPassword = realPassword Then
MsgBox("You owe us £" & price)
Else
MsgBox("Incorrect password entered. You now owe £" & price * 2)
End If
Loop Until userPassword = realPassword
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
The price doesn't go up if they enter the wrong password.
Upvotes: 1
Views: 1985
Reputation: 259
Use While userPassword <> realPassword
the while statement will wait until userPassword and realPassword is equal, if equal the while statement will terminate.
Upvotes: 0
Reputation: 112352
The problem is that you have a property as well as a variable called userPassword
.
Since the variable is defined inside of the loop with ...
Dim userPassword = InputBox(...)
... the property will never be set and the variable's scope will be limited to the loop block (the statements inside the loop). Therefore the loop condition Loop Until userPassword = realPassword
refers to the property that has never been set!
Fix: Remove the Dim
userPassword = InputBox(...) 'Now this sets the property
'instead of declaring a new variable
And also change the value of price
price = 2 * price
or
price *= 2
You are only showing the double price, but the variable price
is never changed!
It is usage in VB to start the property names with an upper case letter and the local variables and the method parameter names with a lower case letter. This helps to avoid confusion.
Note: The scope of a variable, i.e. the area where it is known to VB, is the statement block where it has been declared
Dim k, x, y As Integer
IF x = y Then
Dim i As Integer = 5
Else
k = i ' Not possible since `i` is not known here!
End If
If you want to leave a loop from within the loop, you can use Exit Do
. If you want to leave the method altogether, you can do it with Return
. But there is no need to use it in your solution. I'm only mentioning it, because it was a subject of discussion in the comments.
Do
DoSomething()
If WeWantToExitNow Then
Exit Do ' Or "Return" if you want to leave the method here.
End If
DoSomethingElse()
Loop Until x = y
Upvotes: 2