Greg Koc Greg Koc - 10 days ago 5
Vb.net Question

If statement true regardless of input

Recently I have been tasked with making a calculator in VB. It must include stuff like logic or denary/binary/hex conversions. When I was making the binary->denary conversion I encountered a thing where an if statement checking if the inputted number is binary always returned true and activated. Here is the code for the binary conversion system: (please forgive me for the goto's)

Private Sub bbin_Click(sender As Object, e As EventArgs) Handles bbin.Click
If temp = IsNumeric(inputbox.Text) Then
MessageBox.Show("Value Not Numeric", "ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
Else
For i = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, i, 1) <> "0" Or Mid(inputbox.Text, i, 1) <> "1" Then
MessageBox.Show("Value Not Binary", "ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
GoTo skipbin
End If
Next
For x = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, x, 1) = "1" Then
decnum = decnum + 2 ^ (Len(inputbox.Text) - (x - 1))
End If
Next
binnum = inputbox.Text
inputbox.Text = ""

End If
textbox.Text = "Dec = " + decnum.ToString + " Bin = " + binnum.ToString + " Hex = " + hexnum.ToString
skipbin:
End Sub


Let me explain:


  1. The inputbox is the place where the user can input the numbers/operations. The first If checks if the value inputed is a number.

  2. Then a check is ran to ensure the number is binary. (this is where im having problems)

  3. The conversion is ran. It doesn't work as intended at the moment, but I'm sure I'll get it working.

  4. Then the binary and denary values get displayed in a second textbox that I use to display the answers.



The problem I'm having is only with this section: (again, forgive me for the goto functions)

For i = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, i, 1) <> "0" Or Mid(inputbox.Text, i, 1) <> "1" Then
MessageBox.Show("Value Not Binary", "I AM ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
GoTo skipbin
End If
Next


It's supposed to check each digit if it's a 1 or a 0, and if not, it displays an error and skips the conversion.

What do I need to change to make the input validation work as intended?

Answer

You need And instead of Or.

When you get a bit of code that you can't figure out why it doesn't work, it is often a good idea to make the minimal bit of code that shows the problem - removing everything else can often lead you to the problem.

In this case, to confirm my answer was correct, I used this:

Option Infer On
Option Strict On

Module Module1

    Sub Main()
        Dim s = "000012"
        For i = 1 To Len(s)
            Dim c = Mid(s, i, 1)
            If c <> "0" And c <> "1" Then
                Console.WriteLine("Value Not Binary: {0}", c)

            End If
        Next

        Console.ReadLine()

    End Sub

End Module

You can use AndAlso instead of And: it eliminates any unnecessary processing of the clauses (known as short-circuiting). Similarly, there is OrElse instead of Or.