Results 1 to 4 of 4

Thread: How do I Prevent a Crash When a Letter is Typed Instead of an Integer

  1. #1

    Thread Starter
    New Member
    Join Date
    May 2013
    Posts
    8

    How do I Prevent a Crash When a Letter is Typed Instead of an Integer

    So here's the problem, I have a variable called Denary which is an integer as I need to do maths with it. If someone using my program were to type in a
    letter instead of a number it would crash. I would prefer to be able to post an error message but it crashes at the console.ReadLine so my knowledge leaves me unable to solve it.

    Code:
    Console.WriteLine("Type a denary number between 0 and 255 to convert or press * to return to the main menu")
            Denary = Console.ReadLine 'Reads in the Denary Number
    
            If Denary > 0 And Denary < 255 Then
                Do While Denary > 0
                    Binary(i) = Denary Mod 2
                    Denary = Fix(Denary / 2) 'Divides Denary number by 2 and rounds dpwn
                    i = i + 1
                Loop

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,397

    Re: How do I Prevent a Crash When a Letter is Typed Instead of an Integer

    Use tryparse:
    Code:
    If Integer.TryParse(Console.ReadLine, Denary) Then
       'Do stuff if it's an integer
    Else
       'Do stuff if it's not an integer
    End If
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  3. #3

    Thread Starter
    New Member
    Join Date
    May 2013
    Posts
    8

    Re: How do I Prevent a Crash When a Letter is Typed Instead of an Integer

    Thanks!!

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: How do I Prevent a Crash When a Letter is Typed Instead of an Integer

    By the way, you wouldn't have to use Fix in there. You can just do this:

    Denary = Denary \ 2

    Note the difference between / and \. The latter is an integer division, while the former....is what you used and had to Fix.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width