|
-
Feb 5th, 2009, 02:11 AM
#1
Thread Starter
New Member
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:
Public Class Form1
Public Rand As Integer = 0
Public Attempts As Integer = 5
Public Function DoFail()
MsgBox("You failed. The number was: " + Rand)
Attempts = 0
Return 1
End Function
Private Sub Button1_Click() Handles Button1.Click
If Rand < 1 Then
Randomize()
Rand = Int(Rnd() * 11)
If Rand = 0 Then
Rand += 1
End If
End If
If GuessBox.Text = 0 Then
MsgBox("You must enter a guess!", MsgBoxStyle.Exclamation, "Guess")
Else
Dim Guess As Integer = GuessBox.Text
If Guess > Rand Then
Attempts -= 1
If Attempts = 0 Then
DoFail()
End If
StatusStrip1.Text = "Remaining attempts: " + Attempts
OutputBox.Text = "Lower!"
End If
If Guess < Rand Then
Attempts -= 1
If Attempts = 0 Then
DoFail()
End If
StatusStrip1.Text = "Remaining attempts: " + Attempts
OutputBox.Text = "Higher!"
End If
If Guess = Rand Then
StatusStrip1.Text = "Winner!"
MsgBox("You've got it! The number was: " + Rand, MsgBoxStyle.Information, "Winner!")
Me.Close()
End If
End If
End Sub
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:
StatusStrip1.Text = "Remaining attempts: " + Attempts
'This line is highlighted with this message:
'Conversion from string "Remaining attempts: " to type 'Double' is not valid.
If Guess < Rand:
(same as above)
If Guess = Rand:
vb Code:
MsgBox("You've got it! The number was: " + Rand, MsgBoxStyle.Information, "Winner!")
'This line is highlighted with this message:
'Conversion from string "You've got it! The number was: " to type 'Double' is not valid.
What am I doing wrong?
Thanks in advanced.
-
Feb 5th, 2009, 04:54 AM
#2
Frenzied Member
-
Feb 5th, 2009, 06:04 AM
#3
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)
-
Feb 5th, 2009, 06:44 AM
#4
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.
-
Feb 5th, 2009, 08:13 AM
#5
Member
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.
-
Feb 5th, 2009, 09:22 AM
#6
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
 
-
Feb 5th, 2009, 10:18 AM
#7
Hyperactive Member
Re: New to Visual Basic, need help with code
 Originally Posted by Mattshu
If Guess > Rand:
vb Code:
StatusStrip1.Text = "Remaining attempts: " + Attempts
'This line is highlighted with this message:
'Conversion from string "Remaining attempts: " to type 'Double' is not valid.
If Guess < Rand:
(same as above)
If Guess = Rand:
vb Code:
MsgBox("You've got it! The number was: " + Rand, MsgBoxStyle.Information, "Winner!")
'This line is highlighted with this message:
'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
-
Feb 5th, 2009, 10:27 AM
#8
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.
-
Feb 5th, 2009, 10:32 AM
#9
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
 
-
Feb 6th, 2009, 06:40 AM
#10
Hyperactive Member
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
-
Feb 6th, 2009, 10:29 AM
#11
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
 
-
Feb 6th, 2009, 12:03 PM
#12
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|