Frizeio Official Frizeio Official - 1 month ago 7
Vb.net Question

Issue with making terminal

I am coding a terminal in VB.net, And when I type in 'help' and press enter, Nothing happens. It is supposed to show 'This is the only command. :P'.

I appear to not be more specific so let me explain what happened.

I put in the code below, I executed the application and then I typed in 'help' and then I hit the enter key then nothing happened at ALL.

Here is the entire code:

Private Sub RichTextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
Dim lines = RichTextBox1.Lines
Dim num = lines
Dim textlength = RichTextBox1.TextLength

If Asc(e.KeyChar) = 13 Then
If num.Last.ToString() = "help" Then
RichTextBox1.AppendText("This is the only command. :P\r\n")
End If
End If
End Sub


Please help!

Answer

So, having attached a debugger to your code, it was instantly obvious what the problem is... When you get to the comparison, lines.Last() is an empty string.

There are a number of ways to get the 2nd to last line. I prefer LINQ, so here's your code tidied up, using a case and culture-insensitive string comparison (so you can type Help too)...

Private Sub RichTextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles RichTextBox1.KeyPress
    If Asc(e.KeyChar) = 13 Then
        If String.Equals(RichTextBox1.Lines.Reverse.Skip(1).First(),
                         "help",
                         StringComparison.InvariantCultureIgnoreCase) Then
            RichTextBox1.AppendText(String.Format("This is the only command. :P{0}", Environment.NewLine))
        End If
    End If
End Sub

I've also used Environment.NewLine to make your code more portable, and String.Format() to combine the strings in a way that doesn't eat memory for no reason. It's overkill for this example but it shows how it should be done.

It's worth noting that using a debugger is a crucial skill for any developer (well, ok, there is an alternative which is extensive logging, but you need to know both). You will need this skill to solve any number of problems.

In case you're not familiar with the concept, debugging is like pausing your program and letting you examine what's going on, then run a single command at a time to see what the program is doing.

Comments