I am trying to build a for loop that greats a rectangle with asterisks where a user can enter the number of rows and columns they would wish displayed. I am able to get the rows working correctly but I unable to get the columns to work as they should. Could anyone correct me on where am going wrong:
Private Sub cmdProcess_Click(sender As Object, e As EventArgs) Handles cmdProcess.Click
Dim rows As Integer
Dim columns As Integer
rows = txtRow.Text
columns = txtColumn.Text
lbloutput.Text = ""
For i = 1 To rows
lbloutput.Text = lbloutput.Text & "*" & vbCrLf
Next
End Sub
CodePudding user response:
Before anything else: your code will error if the user enters a negative number, or 0. Unless you have any other code to address this, you might want to try something like this:
rows = Abs(cInt(txtRow.Text))
columns = Abs(cInt(txtColumn.Text))
if rows*columns < 1 Then Exit Sub
(If your code is in VBA, rather than VB, then there is no advantage to using Integer
over Long
, as they both use the same amount of memory — an Integer
just locks half of it out as unusable)
A naïve approach would be to use two loops, like so:
lbloutput.Text = ""
For i = 1 To rows 'How many lines of text?
For j = 1 to columns 'How many asterisks per line?
lbloutput.Text = lbloutput.Text & "*"
Next j
lbloutput.Text = lbloutput.Text & vbCrLf
Next i
However, a simpler method would be to use the String
function:
lbloutput.Text = ""
For i = 1 To rows
lbloutput.Text = lbloutput.Text & String(columns, "*") & vbCrLf
Next i