Check if a string variable has an integer value - vb.net

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid.
Is there any way to check if they have entered an integer or not? This is the code.
If childAge > 0 And childAge < 150 Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
Thanks,
Kai :)

A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).
Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
' childAge successfully parsed as Integer
Else
' childAge is not an Integer
End If

Complementing Styxxy's response, if you dont need a result just replace it by vbNull:
If Integer.TryParse(childAge, vbNull) Then

You could perform the following two tests to be reasonably certain that the input you're getting is an integer:
If IsNumeric(childAge) AndAlso (InStr(1, childAge, ".") <> 0) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
If childAge < 0 OrElse childAge > 150 Then
fmSecA2 = "I don't believe it's possible to be" & childAge & " years old..."
End If
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
The InStr function returns zero if it doesn't find the string that is being looked for, and so when combining that test with IsNumeric, you also rule out the possibility that some floating point data type was entered.

IsNumeric is built into VB, and will return a true/false
If IsNumeric(childAge) AndAlso (childAge > 0 And childAge < 150) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If

You can use this.
Sub checkInt()
If IsNumeric(Range("A1")) And Not IsEmpty(Range("A1")) Then
If Round(Range("A1"), 0) / 1 = Range("A1") Then
MsgBox "Integer: " & Range("A1")
Else
MsgBox "Not Integer: " & Range("A1")
End If
Else
MsgBox "Not numeric or empty"
End If
End Sub

Working from Styxxy's answer, if you parse as a byte rather than an integer, then it also checks negative ages and maximum age of 255 all in one go.
Dim childAgeAsByte As Byte
If Byte.TryParse(childAge, childAgeAsByte) Then
' childAge successfully parsed as Byte
Else
' childAge is not a Byte
End If
Kristian

Dim Input
Input = TextBox1.Text
If Input > 0 Then
............................
............................
Else
TextBox2.Text = "Please only enter positive integers"
End If

Try
If TextBox1.Text > 0 Then
Label1.Text = "Integer"
End If
Catch ex As Exception
Label1.Text = "String"
End Try
With this you can put anything in TextBox1, if you put text then you get Label1 is string and if you put number then you get it's integer

In .Net you may use GetType() to determine the data type of a variable.
Dim n1 As Integer = 12
Dim n2 As Integer = 82
Dim n3 As Long = 12
Console.WriteLine("n1 and n2 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n2.GetType()))
Console.WriteLine("n1 and n3 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n3.GetType()))
' The example displays the following output:
' n1 and n2 are the same type: True
' n1 and n3 are the same type: False
Based on the above sample you can write a code snippet:
If childAge.GetType() = "Integer" then '-- also use childAge.GetType().Name = "Int32"
' do something
End if
Reference MSDN

Related

Q. Accept two numbers using an InputBox in two different variables and print the sum of two in a message box. (Visual Basic)

I have to answer this in Visual Basic.I actually don't have any idea how to solve this, our teacher barely teaches us practical stuff. I have to submit this assignment by today too.
I have tried to do solve it and searched the internet for it, but I could barely understand it.
Here is some code you can build upon:
Public Sub AddTwoNumbers()
Dim FirstNumber As String = Convert.toInt32(InputBox("Enter the first number.")) 'Get the first number
Dim SecondNumber As String = Convert.toInt32InputBox("Enter the second number.")) 'Get the second number
Dim Result As Integer = 0 'Used to store the result in
'Now perform the calculation.
Result = FirstNumber + SecondNumber
'Then show the result in a MessageBox
MessageBox.Show("The result is: " & Result.ToString())
End Sub
Here's an example using Integer.TryParse():
Dim value1, value2 As Integer
Dim response As String = InputBox("Enter first Integer:")
If Integer.TryParse(response, value1) Then
response = InputBox("Enter second Integer:")
If Integer.TryParse(response, value2) Then
Dim sum As Integer = value1 + value2
MessageBox.Show("The sum of " & value1 & " and " & value2 & " is " & sum)
Else
MessageBox.Show(response & " is not a valid Integer!")
End If
Else
MessageBox.Show(response & " is not a valid Integer!")
End If

Visual Studio - CDbl to Double.TryParse when inputting to array

I'm finishing up a project and needed some clarification on a particular issue I'm running into.
Do While intCount < dblNumbers.Length AndAlso strInput <> String.Empty
dblNumbers(intCount) = CDbl(InputBox("Please enter number " & (intCount + 1) & "."))
intCount += 1
Loop
I'm running into issues changing that a to Double.TryParse for validating as opposed to the CDbl. Any of the ways I've entered it have caused the inputs to not store in the array. Thanks in advance.
TryParse doesn't return the converted value. It returns the validation result. You get the converted value from the parameter.
Dim number As Double
If Double.TryParse(InputBox("Please enter number " & (intCount + 1) & "."), number) Then
dblNumbers(intCount) = number
Else
'Invalid input.
End If

Visual Basic, number range in IF statements

how would i write this line of c# in visual basic. im trying to get a input from the user and provide a result, given the input falls between a number range.
if int(>65 || <=73)
{
}
This is the code i have so far.
Dim Hb As String = txtInput1.Text
If IsNumeric(Hb) Then
Dim HbInt As Integer = Integer.Parse(Hb)
Else
Output("The Hb value needs to be numeric")
End If
For Reference See this.
This Dim Hb As String = txtInput1.Text is not allowed in vba and I assume txtInput1 is a named reference to a cell range.
You have to write it as below
Dim Hb As String: Hb = txtInput1.Text
Also this Dim HbInt As Integer = Integer.Parse(Hb) isn't right as well
The right way would be:
Dim HbInt As Integer: HbInt = CInt(Hb)
So the code for your need would be:
Sub NumRange()
Dim Hb As String: Hb = txtInput1.Text
if IsNumeric(Hb) then
Dim HbInt As Integer: HbInt = CInt(Hb)
if HbInt > 65 And HbInt <=73 then
Do things......
Else
Msgbox "Number Entered is out of Range"
End if
Else
Msgbox "Invalid Input."
End if
End Sub
Just expanding upon the answer provided by #NewGuy I'd rather use the Select Case statement to evaluate the number provided. This will allow for more options:
Option Explicit
Sub tmpTest()
Dim strHB As String
strHB = InputBox("Give me a number between 1 and 100", "Your choice...")
If IsNumeric(strHB) Then
Select Case CLng(strHB)
Case 66 To 73
MsgBox "You picked my range!"
Case 1 To 9
MsgBox "One digit only? Really?"
Case 99
MsgBox "Almost..."
Case Else
MsgBox "You selected the number " & strHB
End Select
Else
MsgBox "I need a number and not this:" & Chr(10) & Chr(10) & " " & strHB & Chr(10) & Chr(10) & "Aborting!"
End If
End Sub
Like this:
If HbInt > 65 And HbInt <= 73 Then
...
End If

My For Loop skips my IF statement

I wonder if anyone can help. I am making a program that will convert Text to ASCII. However, I want my program to ignore spaces. Hence, "IT WAS A" should look like this: 7384 876583 65
When I use the Step Into Feature of VB I can see that my For loop is skipping my IF statement which should be giving me my spaces. I don't understand why. As you can probably tell, I am a beginner so any specific help would be greatly appreciated. My code looks like this:
Dim PlainText, ConvertedLetter As String
Dim LetterToConvert As Char
Dim AscNumber, Counter As Integer
ConvertedLetter = ""
PlainText = txtPlain.Text
For Counter = 1 To Len(PlainText)
LetterToConvert = Mid(PlainText, Counter, 1)
If PlainText = " " Then
ConvertedLetter = " "
Else : AscNumber = Asc(LetterToConvert)
ConvertedLetter = ConvertedLetter & AscNumber
End If
Next
txtAscii.Text = ConvertedLetter
Because you're comparing PlainText, which is the whole string, to " ". It would need to be:
If LetterToConvert = " " Then ....
Try this:
Dim PlainText, ConvertedLetter As String
ConvertedLetter = ""
PlainText = "IT WAS A"
For Each c As Char In PlainText 'iterate through each character in the input
If c <> " " Then ' check whether c is space or not
ConvertedLetter &= Asc(c).ToString()' ascii value is taken if c<>" "
Else
ConvertedLetter &= " " ' c is space means add a space
End If
Next
MsgBox(ConvertedLetter) ' display the result
You will get the output as
7384 876583 65

Only numbers, disallow letters -user input

I am writing a console application which requires user input of certain values. I want to disallow any letter input. The console automatically writes "Conversion from string "b" to type 'Integer' is not valid." but I want the console to display my personal message "Not a valid number, please try again." how can I do that?
I've tried many different keywords and phrases but none work. Maybe I'm doing it wrong (not unlikely) or maybe it's just meant for something else. Either way I need help.
To recap: User input in a console that only allows numbers not letters, and will display my message.
I didn't want to post my code since people always pick on it, but here it is. Please note that there MUST be an exception. It is homework and I NEED an exception and this is one way a user can screw up. Please don't tell me not to use an exception.
Module Module1
Sub Main()
Try
System.Console.WriteLine("Input up to 10 valid numbers to have them mathematically averaged.")
For Index = 0 To 9
Dim Input As IList
Input = Console.ReadLine()
Next Index
If ' here is where I want to add that numbers only Then
Throw New exception("Not a valid number, please try again.")
Else
System.Console.WriteLine("Now averaging numbers...")
Dim average As Double = (n + n + n + n + n + n + n + n + n + n) / 10
Console.WriteLine("The average of " & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & " and " & n & " is " & average & ".", "Calculation")
End If
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
End Module
Dim inputString = Console.ReadLine
If Integer.TryParse(inputString, num) Then
DoSomething(num)
Else
Console.WriteLine("Not a valid number, please try again.")
End If
Here's one way to do it, honoring your requirements:
Module Module1
Sub Main()
System.Console.WriteLine("Input valid numbers seperated by spaces to have them mathematically averaged.")
Dim inputArray As String() = System.Text.RegularExpressions.Regex.Replace(Console.ReadLine().Trim(), "\s{2,}", " ").Split(New Char() {" "})
Dim values As New ArrayList
Dim sum As Integer
For i As Integer = 0 To inputArray.Length - 1
Try
sum = sum + Integer.Parse(inputArray(i), Globalization.NumberStyles.Integer)
values.Add(inputArray(i))
Catch ex As Exception
Console.WriteLine(String.Format("The value ""{0}"" is not a valid number and will be ignored. ExceptionMessage: {1}", inputArray(i), ex.Message))
End Try
Next
Dim average As Decimal = sum / values.Count
Console.WriteLine(vbCrLf)
Console.WriteLine(String.Format("The average of ""{0}"" is {1}", Join(values.ToArray, ", "), average))
Console.WriteLine(vbCrLf)
Main()
End Sub
End Module
Well for starters, the Try - Catch should be inside the input gathering For loop. As your program is written now, as soon as one wrong value is entered execution jumps to the catch and your program ends! If you try casting your input to an decimal you won't need to throw an exception manually, it will be thrown automatically if your input is not an decimal! Try casting the current console input as a decimal and then add that number to your list.
Dim inputNumber as Decimal = CDec(Console.ReadLine())
Input.Add(inputNumber)
Also n will be the same number every time so how you are doing it won't work (look up the basics of how a list works, how to add elements to a list and how to display list elements)