learning about loops (still a beginner) in VB.net. I have got the below code and basically it is meant to stop the loop once it reaches a number above 20. Now, the problem is that it does stop after number 20 but the last number that is displayed in the list is always above 20…..any idea how I can stop it showing the last number as above 20?
If you guys know it can you also explain a bit about the answer – would like to learn as well as have the code..Thanks!
Private Sub btnDoWhileLoop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDoWhileLoop.Click
Dim objRandom As New Random
Dim intRandomNumber As Integer = 0
ClearList()
Do While intRandomNumber < 20
intRandomNumber = objRandom.Next(25)
lstData.Items.Add(intRandomNumber.ToString)
Loop
End Sub
The problem is that you are adding the random item immediately after it was generated, without checking whether you should add it.
You can check that the number should be added to the list before adding it:
Or, break out of the loop: