1

I have a VB project for school and it requires to use a loop. I'm trying to test it on my computer but each time I press "OK" on my program the program freezes and nothing is added onto the listbox. The only thing that appears new is the scroll bar on the listbox.

    Dim counter As Integer = 0

    If total = 5 Then
        Do While counter < 5
            Marks.Items.Add(studentNumber)
        Loop
    End If
7
  • 4
    How about increasing the counter inside your loop: counter += 1 ;-). And how will total ever reach 5? Where is it defined? As this hasn't been part of the posted code, we can't give any suggestion of this may be part of your problem.
    – SaschaM78
    Nov 9, 2017 at 20:32
  • Oh jeez, I totally forgot about that. Fixed it, thanks. I had didn't include the rest of the code that included the value of total, but the problem is solved Nov 9, 2017 at 20:35
  • Where are you incrementing/instantiating total? Nov 9, 2017 at 20:37
  • That was an easy one and one that happens frequently when new to a programming language ;-). Do you mind if I create an answer so the question can be closed and doesn't remain open? Otherwise feel free to do so yourself.
    – SaschaM78
    Nov 9, 2017 at 20:37
  • Yeah you can create an answer, thanks! Nov 9, 2017 at 20:39

2 Answers 2

1

You have to increment the counter

Dim counter As Integer = 0

Do While counter < 5
   Marks.Items.Add(studentNumber)
   counter += 1
Loop

If you want to add 5 items to your list, it is not necessary to use the If statement, because the while loop will be executed exactly 5 times

1
  • 1
    You could even use counter += 1 instead of counter = counter + 1 to shorten it a bit.
    – SaschaM78
    Nov 9, 2017 at 21:04
1

Incrementing the counter will fix the issue you're having in your do/while loop, but I'd also suggest you might be better suited just using a for loop, as this is exactly what they're made for.

For i As Integer = 1 to 5
    Marks.Items.Add(i) 'Assuming your counter == studentNumber.
Next

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.