Reputation: 1072
I have written the piece of code below to calculate factorials of numbers more than or equal to 1.
Public Class FactorialApp
Private Function FactorialChecker(myNumber As Integer)
myNumber = Val(FactorialTextBox.Text)
If myNumber < 1 Then
FactorialChecker = 1
Else
FactorialChecker = myNumber * FactorialChecker(myNumber - 1)
End If
End Function
Public Sub ResultButton_Click(sender As Object, e As EventArgs) Handles ResultButton.Click
End Sub
End Class
I want to have a message box in a button_click
event that says something like The factorial of 5 is 120 when clicked where 5 is supposed to be myNumber
and 120 the FactorialChecker()
function, but I have no idea how to return values in VB's MsgBox
command, I'm only used to C#'s .
I tried the code snippet
MsgBox("The Factorial of + myNumber "is" + FactorialChecker() "")
But I got stomped by syntax errors in visual studio and also an error that my myNumber
variable wasn't declared in the program. What can I do to fix these errors please?
Upvotes: 0
Views: 97
Reputation: 3112
For a first attempt, move myNumber = Val(FactorialTextBox.Text)
into your button Click handler. If you reload it every time your FactorialChecker function is called, then your recursion won't work the way you want it to.
Also, you're not declaring it or specifying a type, so you may want to change that line to Dim myNumber As Double = Val(FactorialTextBox.Text)
. Then below it, add the MessageBox.Show
call, as others have said.
Val()
may not be a good choice, since it returns a Double, and the factorial function is defined only for non-negative integers. You probably actually want myNumber
to be an Integer (or a Long, or something else, depending on the range you need). You could then replace Val()
with CInt()
, or Integer.Parse
, or Integer.TryParse
, and add error-checking to make sure the value is non-negative.Integer.TryParse, and add error checking to make sure the value is non-negative.
Upvotes: 1
Reputation: 6948
myNumber
is declared inside the FactorialChecker
function. If you try to access it outside that function it won't exist. You might need to make it a property of the class.
Upvotes: 1
Reputation: 48096
Like this:
MsgBox("The Factorial of " + myNumber + " is " + FactorialChecker())
You just didn't close your quotes for the first part of the string so they're unbalanced, thus your compiler errors. Also, I added some spaced because I assume you'll want them.
Note that in VB.NET, using MessageBox.Show
is preferable to the old VB6-style MsgBox
function. Also, in VB, the &
operator is typically recommended over the +
operator for string concatenations, since the +
operator can have some unexpected results when you have Option Strict Off
. So, this would be the better way to do that:
MessageBox.Show("The Factorial of " & myNumber & " is " & FactorialChecker())
Upvotes: 6