Results 1 to 12 of 12

Thread: New to Visual Basic, need help with code

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2009
    Posts
    5

    Exclamation New to Visual Basic, need help with code

    Hi. I'm new to the VB language but I'm familiar with programming/scripting.

    I'm also new to these forums so please forgive me if this post is in the wrong board.

    I started playing with Visual Basic when I realized my tech school had it installed on the network computers, and became a bit addicted (within a few days) of the possibilities it contains.

    I've started writing something basic.. a number guessing game in a Windows Application. The layout may not be optimal/strategically formed, because I'm not familiar with the language yet.

    Here's the code:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Public Rand As Integer = 0
    4.     Public Attempts As Integer = 5
    5.  
    6.     Public Function DoFail()
    7.         MsgBox("You failed. The number was: " + Rand)
    8.         Attempts = 0
    9.         Return 1
    10.     End Function
    11.  
    12.     Private Sub Button1_Click() Handles Button1.Click
    13.         If Rand < 1 Then
    14.             Randomize()
    15.             Rand = Int(Rnd() * 11)
    16.             If Rand = 0 Then
    17.                 Rand += 1
    18.             End If
    19.         End If
    20.         If GuessBox.Text = 0 Then
    21.             MsgBox("You must enter a guess!", MsgBoxStyle.Exclamation, "Guess")
    22.         Else
    23.             Dim Guess As Integer = GuessBox.Text
    24.             If Guess > Rand Then
    25.                 Attempts -= 1
    26.                 If Attempts = 0 Then
    27.                     DoFail()
    28.                 End If
    29.                 StatusStrip1.Text = "Remaining attempts: " + Attempts
    30.                 OutputBox.Text = "Lower!"
    31.             End If
    32.             If Guess < Rand Then
    33.                 Attempts -= 1
    34.                 If Attempts = 0 Then
    35.                     DoFail()
    36.                 End If
    37.                 StatusStrip1.Text = "Remaining attempts: " + Attempts
    38.                 OutputBox.Text = "Higher!"
    39.             End If
    40.             If Guess = Rand Then
    41.                 StatusStrip1.Text = "Winner!"
    42.                 MsgBox("You've got it! The number was: " + Rand, MsgBoxStyle.Information, "Winner!")
    43.                 Me.Close()
    44.             End If
    45.         End If
    46.     End Sub
    47. End Class

    When I attempt to run this, the dialog opens fine. Until I click the "Guess" (Button1) button, which sort of freezes the dialog, returning me to the Visual Basic editor debugger. If the guessed number matches the random number (or if its lower or higher) then it returns the related code (involving the integers 'Rand' and 'Guess'):

    If Guess > Rand:
    vb Code:
    1. StatusStrip1.Text = "Remaining attempts: " + Attempts
    2.  
    3. 'This line is highlighted with this message:
    4. 'Conversion from string "Remaining attempts: " to type 'Double' is not valid.

    If Guess < Rand:
    (same as above)

    If Guess = Rand:
    vb Code:
    1. MsgBox("You've got it! The number was: " + Rand, MsgBoxStyle.Information, "Winner!")
    2.  
    3. 'This line is highlighted with this message:
    4. 'Conversion from string "You've got it! The number was: " to type 'Double' is not valid.


    What am I doing wrong?

    Thanks in advanced.

  2. #2
    Frenzied Member
    Join Date
    Aug 2006
    Location
    India, Punjab, Bhatinda
    Posts
    1,689

    Talking Re: New to Visual Basic, need help with code

    Welcome to the vbforums
    pls specify what version of VB you are working with.
    Happy programming

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: New to Visual Basic, need help with code

    Thread moved from 'VB6 and Earlier' forum to 'VB.Net' (VB2002 and later) forum

    (for the benefit of others, Mattshu's profile says VB2008 Express)

  4. #4
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: New to Visual Basic, need help with code

    Have you stepped through the code? You can place breakpoints at lines of code (F9) and when the line hits, the debugger will bring it up, usually with a yellow highlight. You can then press move your mouse over variables to look at the values, and F10 and F11 to step to the next line to see the flow of execution.

    Welcome to the forums.

  5. #5
    Member
    Join Date
    Nov 2008
    Posts
    34

    Re: New to Visual Basic, need help with code

    Yeh like Mendhak said Place a BP (Breakpoint) on the following line...

    Code:
    Private Sub Button1_Click() Handles Button1.Click
    Not sure if it matters to much but my OnClick Sub begins like this.

    Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    And Hit F5 to run in Debug mode, and then Click the button it should now stop on the BP, then simply hit F8 to step through each line of code.

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

    Re: New to Visual Basic, need help with code

    A couple other points that aren't quite related to the problem directly:

    1) Get rid of Randomize and rnd, look at the Random object. Those other randomizers were used in VB6 and earlier, and are decidedly inferior to the Random object for ease of use. For instance, with the Random object you no longer need the call to Randomize. Also, to get a value between Min and Max using the random object you would do something like this:
    Code:
    Dim rn as New Random
    
    rn.GetNext(Min, Max+1)
    The Max+1 is because GetNext includes the lower bound (Min), but not the upper bound (Max), so Max+1 will include Max.

    2) Turn Option Strict ON. By default, Option Strict is set to Off, a default decision that is truly unfortunate. You will probably get a fair number of errors when you turn Option Strict ON, such as this line:

    Dim Guess As Integer = GuessBox.Text

    Since GuessBox.Text returns a String and you are putting it into an Integer variable. Without Option Strict ON, this works ok, because the compiler does the conversion for you. You would need to change that to either:

    Dim Guess As Integer = CInt(GuessBox.Text)


    or a safer conversion using TryParse. Either way looks like more typing, and it is, but you will avoid some especially subtle bugs, and the code will run faster. Those implicit conversions that you create with Option Strict OFF are not all that fast. Therefore, you get safer, faster, code with Option Strict ON for the cost of slightly more typing. That's a very good trade-off.
    My usual boring signature: Nothing

  7. #7
    Hyperactive Member Runesmith's Avatar
    Join Date
    Oct 2008
    Posts
    399

    Re: New to Visual Basic, need help with code

    Quote Originally Posted by Mattshu

    If Guess > Rand:
    vb Code:
    1. StatusStrip1.Text = "Remaining attempts: " + Attempts
    2.  
    3. 'This line is highlighted with this message:
    4. 'Conversion from string "Remaining attempts: " to type 'Double' is not valid.

    If Guess < Rand:
    (same as above)

    If Guess = Rand:
    vb Code:
    1. MsgBox("You've got it! The number was: " + Rand, MsgBoxStyle.Information, "Winner!")
    2.  
    3. 'This line is highlighted with this message:
    4. 'Conversion from string "You've got it! The number was: " to type 'Double' is not valid.


    What am I doing wrong?

    Thanks in advanced.
    You are using "+" to concatenate strings, which is not valid in VB.NET. Try "&" operator instead. Go to the Visual Studio help, and search "string concatenation" for further information.

    Also, I suggest using .ToString to convert the numeric values to string, instead of doing an implicit conversion. Eg. "The number was " & rand.ToString
    Last edited by Runesmith; Feb 5th, 2009 at 10:22 AM.
    Runesmith

    The key to getting the right answer is asking the right question

    I just realized: good health is merely the slowest possible rate at which one can die

  8. #8
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: New to Visual Basic, need help with code

    CInt vs Int32.Parse, I wonder which is more appropriate. I would lean towards Parse because it is specifically geared towards strings.

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

    Re: New to Visual Basic, need help with code

    The + concatenator works ok in .NET, however, with Option Strict Off, there is a chance that you will not get what you want. That's a rare issue, though.

    CInt and Int32.Parse will both throw exceptions if the string being converted is not a valid integer.
    My usual boring signature: Nothing

  10. #10
    Hyperactive Member Runesmith's Avatar
    Join Date
    Oct 2008
    Posts
    399

    Re: New to Visual Basic, need help with code

    Both errors that Mattshu highlighted in his code were caused by using the "+" operator. The compiler tries to convert the first operand (a string in this case) to Double, and throws the exception.
    Runesmith

    The key to getting the right answer is asking the right question

    I just realized: good health is merely the slowest possible rate at which one can die

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

    Re: New to Visual Basic, need help with code

    That's bizarre. One item is a string, the result is being put into a string, yet it is the string that is being converted to a number. I just checked it in 2005, and it's true.

    The real problem, though, is that Option Strict is OFF. That line wouldn't even compile with Option Strict ON, because the error would have been caught right from the start. The + operator does concatenate strings, but it also adds numbers. Without the implicit conversions required by Option Strict, the compiler didn't know whether to convert the string to a double, or the number to a string, and it guessed wrong. I'm surprised at that, since the string was a literal, rather than a variable, but the result is the same: Option Strict should be ON in all cases except the very rare times when it HAS to be off. Aside from catching problems like this, your code will run faster, too.
    My usual boring signature: Nothing

  12. #12
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: New to Visual Basic, need help with code

    a crude solution
    Code:
    Option Strict On : Option Explicit On
    Public Class Form1
        Dim number2Guess As Integer
        Dim r As New Random
        Const maxGuess As Integer = 5
        Dim guesses As Integer
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Button1.Text = "Guess"
            Me.AcceptButton = Button1
            StartGame()
        End Sub
        Private Sub StartGame()
            ToolStripStatusLabel1.Text = "Type your Guess, then press enter or click Guess"
            number2Guess = r.Next(1, 11) 'a number between 1 and 10 inclusive
            guesses = 0
            ToolStripStatusLabel2.Text = "Guesses Left " & maxGuess.ToString
            TextBox1.Text = ""
            TextBox1.Select()
        End Sub
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim guessed As Integer = -1
            Integer.TryParse(TextBox1.Text, guessed)
            If guessed = number2Guess Then
                'winner
                MessageBox.Show("You Guessed It")
                StartGame()
                Exit Sub
            Else
                guesses += 1
                If guesses >= maxGuess Then
                    MessageBox.Show("The Number was " & number2Guess.ToString()) 'show number
                    StartGame()
                    Exit Sub
                Else
                    ToolStripStatusLabel2.Text = "Guesses Left " & (maxGuess - guesses).ToString
                End If
            End If
            TextBox1.Select()
            TextBox1.SelectAll()
        End Sub
    End Class
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

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