0

I am fairly new to coding in VB and I am trying to reverse the string of numbers in the variable 'binary' by using a while loop (at the bottom of the code) but when the program runs I get a System.IndexOutOfRangeException error. What changes do I need to make to fix this? Thanks

Module Module1


    Sub Main()
        Dim denary As Integer
        Dim binary As String = " "
        Dim x As Integer
        Dim y As Integer = 0
        Console.WriteLine("What is the denary number?") 'Asks the user what number denary number they want converted
        denary = Console.Read()

        While denary > 0 'Calculates the binary number, but reversed
            If denary Mod 2 = 0 Then
                binary = binary + "0"
                denary = denary / 2
            Else
                binary = binary + "1"
                denary = denary / 2
            End If
        End While

        Console.WriteLine("The binary equivalent is:" & binary) 'Prints the binary number in reverse
        Console.ReadLine()
        x = Len(binary)
        While x > 0
            Console.WriteLine(binary(x)) 'Print the correct binary equivalent (Not working)
            Console.ReadLine()
            x = x - 1
        End While


    End Sub

End Module
1
  • 2
    This is a great problem to lean about debugging: breakpoints, watch variables etc. Please read How to Ask and take the tour Commented May 15, 2017 at 19:51

1 Answer 1

1

Array indexes start at 0, so the last one is always 1 less than the length of the array:

x = Len(binary) - 1
While x >= 0
  '...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.