[RESOLVED] Can't seem to retrieve a specified character from a string of numbers
I'm relatively new to VB, and I'm coding a graphing calculator to familiarize myself with it. I haven't figured out how to to the x^n function yet though.
I made a function to retrieve a certain number from a text box, where the first character is "^", and the second/second and third are numbers.
An example of this not working is: 2^2 = 1.12589990684262E+15 (Where tbNum1 is "2" and tbOpr is "^2"
Here is my code for the entire function:
Code:
'tbopr IS WHERE THE SPECIFIED POWER GOES (x^n)
'tbNum1 IS THE FIRST NUMBER, WHICH IS RAISED TO THE POWER "p"
'tbCalcOut IS THE TEXT BOX THE ANSWER IS OUTPUTTED TO, AND THE NUMBER THAT IS RAISED TO _
'THE POWER "p" IF IT ISN'T EQUAL TO 0.
Private Function Power()
Dim p As Integer = 1
If Len(tbOpr.Text) = 2 Then
p = Convert.ToInt16(GetChar(tbOpr.Text, 2))
ElseIf Len(tbOpr.Text) = 3 Then
p = Convert.ToInt16(GetChar(tbOpr.Text, 2) & GetChar(tbOpr.Text, 3))
Else
MsgBox("Power is too high.", , "Error")
End If
If tbCalcOut.Text <> "" And tbCalcOut.Text <> "0" Then
tbNum1.Text = tbCalcOut.Text
tbCalcOut.Text = tbNum1.Text ^ p
ElseIf tbCalcOut.Text = "0" Or tbCalcOut.Text = "" And tbNum1.Text <> "" And _
tbNum1.Text <> "0" Then
tbCalcOut.Text = tbNum1.Text ^ p
End If
End Function
Thanks guys, this really has stumped me.
Re: Can't seem to retrieve a specified character from a string of numbers
Add this function which return the power part
Code:
Private Function GetPower(strText As String) As Integer
Dim p As Integer = 1
If strText.Contains("^") Then
p = CInt(strText.Substring(strText.IndexOf("^") + 1))
End If
Return p
End Function
Call it from your function like this
Code:
Private Function Power()
Dim p As Integer = GetPower(tbOpr.Text)
If p > 99 Then
MsgBox("Power is too high.", , "Error")
Exit Function ' don't continue
End If
If tbCalcOut.Text <> "" And tbCalcOut.Text <> "0" Then
tbNum1.Text = tbCalcOut.Text
tbCalcOut.Text = tbNum1.Text ^ p
ElseIf tbCalcOut.Text = "0" Or tbCalcOut.Text = "" And tbNum1.Text <> "" And _
tbNum1.Text <> "0" Then
tbCalcOut.Text = tbNum1.Text ^ p
End If
End Function
Re: Can't seem to retrieve a specified character from a string of numbers
Thanks so much!
Why exactly did my code not work, if you don't mind me asking?
Re: [RESOLVED] Can't seem to retrieve a specified character from a string of numbers
Quote:
Why exactly did my code not work,
Because you are not search for "^" inside the tbOpr.Text to know where the power number start, but instead you are picking it from fixed position(s) 2 or 2 & 3 which will never return correct power number from string like "1024^3".
Re: [RESOLVED] Can't seem to retrieve a specified character from a string of numbers
Good to know!
Thanks so much for your help!