M. Ridgeway
M. Ridgeway

Reputation: 3

Having trouble coding an application using a pretest do...loop in visual basic that displays a list of numbers

In my homework assignment, the user is given two text boxes in a form application to enter numbers. In the From box, the user will enter the first number they want to start with in the list. In the To box, they will enter the last number they want to show in the list.

For example:

From: 1 To: 5

List: 1 2 3 4 5

The assignment requires that I use a pretest do...loop to accomplish this. The problem is I can't figure out how to get the code to use numbers entered by the user.

Edit:

This is my current interface:

interface of application

I have already coded the For...Next loop. I will post that code below. I now have to complete the same concept as a pretest Do...Loop. I can't figure out how to get the loop to display the range of numbers specified by the user.

Code for For...Next:

Private Sub btnForNext_Click(sender As Object, e As EventArgs) Handles btnForNext.Click
    ' Display a list of numbers.

    Dim intFrom As Integer
    Dim intTo As Integer

    Integer.TryParse(txtFrom.Text, intFrom)
    Integer.TryParse(txtTo.Text, intTo)
    lstNumbers.Items.Clear()

    For intList As Integer = intFrom To intTo
        lstNumbers.Items.Add(intList)
    Next intList
End Sub

I have tried using Dim intList as Integer = intFrom To intTo but that gives me an end of statement expected error.

Upvotes: 0

Views: 81

Answers (2)

Mary
Mary

Reputation: 15091

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    'You get the input from the user exactly like you did for the For loop
    Dim intFrom As Integer
    Dim intTo As Integer

    Integer.TryParse(TextBox1.Text, intFrom)
    Integer.TryParse(TextBox2.Text, intTo)
    ListBox2.Items.Clear()

    'You want your do loop to keep looping While the intFrom is less than or Equal to intTo
    'The trick is to increment intFrom on every iteration or you will have an infinite loop
    Do While intFrom <= intTo
        ListBox2.Items.Add(intFrom)
        intFrom += 1
    Loop
    'Alternatively
    'Here you loop will continue Until intFrom is greater than intTo
    Do Until intFrom > intTo
        ListBox2.Items.Add(intFrom)
        intFrom += 1
    Loop
    'Both are pre-tests - choose one
End Sub

Upvotes: 1

A.Buonanni
A.Buonanni

Reputation: 101

I've tried your code and it works as expected without any error. This is just my idea but from the event handler declaration, I see it handles the click event for button "btnForNext" wich, looking at your interface, may not be the button you are supposed to click for the "Do...Loop Pretest". Maybe you have just coded the event for the wrong button.

Upvotes: 0

Related Questions