Nana Kwame
Nana Kwame

Reputation: 1309

Create a right triangle with loop in Visual Basic

I tried to solve the Visual Basic assignment in dart and I was able to using this :

enter image description here

I don't know if that's the best way to do it though. In Visual Studio I don't know what commands or methods that can help me do this and this is the result there.

Public Class Form1
    Dim input As Integer
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Text = "Nested Loops"
    End Sub
    
    Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label.Click
    End Sub
    
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles InputTextBox.TextChanged
        input = Val(InputTextBox.Text)
    End Sub
    
    Private Sub ComputeButton_Click(sender As Object, e As EventArgs) Handles ComputeButton.Click
        For outer As Integer = 1 To input
            For inner As Integer = 1 To outer
                ListBox.Items.Add("#")
            Next
            ListBox.Items.Add("")
        Next
    End Sub
    
    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox.SelectedIndexChanged
    End Sub
End Class

enter image description here

I get this error when trying to treat it like dart

System.InvalidCastException: 'Conversion from string "#" to type 'Double' is not valid.'

I need help.

Upvotes: 0

Views: 994

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

Consider:

    For outer As Integer = 1 To input
        Dim s as String
        For inner As Integer = 1 To outer
            s &= "#"
        Next
        ListBox.Items.Add(s)
    Next

i.e. you want to have a string that grows by one # each time before you add it to the thing that will display it:

"#"
"##"
"###"
"####"

This uses simple string concatenation. In the future when you're programming for real (and e.g. wanting to run a process that creates millions of strings) you should consider using something designed for the job, such as a StringBuilder. This will be ok for some small handful of operations though

Though I'm rather puzzled why you use a listbox and not just a textbox..

Upvotes: 1

Related Questions