Validation to ensure value entered is a integer - vb.net

I want a validation method that ensures that value entered is valid, it must be a integer (can include negative) and must not be blank. I have written this code, however not correct, can someone help me please. Thank you
If (b <> Integer Or " ") Then
Console.WriteLine("Value entered must be a number")
End If
new code:
Line98:
Console.WriteLine("Please input the value of, B:")
b = Console.ReadLine()
If Not Integer.TryParse(b, New Integer) Then
Console.WriteLine("Value entered must be a number")
GoTo Line98
End If
so i used a select statement, and if a user enters "abckak" any non numerical data i get an error Unhandled Exception: System.InvalidCastException: Conversion from string "gakjdg" to type 'Integer' is not valid.
how could this be fixed, this is a quick example of my code
Console.WriteLine("..........Main Menu..........")
Console.WriteLine("Please input 1 ")
Console.WriteLine("Please input 2")
Console.WriteLine("Please input 3 ")
Console.WriteLine("Please input 4 ")
Console.WriteLine("Please input 5 for Help")
Console.WriteLine("Please input 6 to Exit")
Console.WriteLine("Please enter your choice: ")
Choice = Console.ReadLine()
Select Case Choice
case1; etc
Case Else
Console.WriteLine("Error: " & Choice & " is not a option, Please try again")

Look into Integer.TryParse, it will try and parse the string into a integer if it can, if it can't it wont throw an exception...
Dim b As Integer
Console.WriteLine("Please input the value of, B:")
If Not Integer.TryParse(Console.ReadLine(), b) Then
Console.WriteLine("Value entered must be a number")
GoTo Line98
End If
If it can parse the input from the user, then b would be the value from the parse, otherwise the value of b is still 0...
Edit Per Comment
Dim b As Integer
Do Until b > 0
Console.WriteLine("Please input the value of, B:")
If Not Integer.TryParse(Console.ReadLine(), b) OrElse b <= 0 Then
Console.WriteLine("Value entered must be a number and not equal 0")
GoTo Line98
End If
Loop

Related

Visual Basic Input Validation

I am new to Visual Basic programming. I'm using a multi-line textbox to accept only numerical inputs from the users.
I need to remove any white space before adding it to my listbox. For example like ( 8) becomes 8 when added into the listbox and I shouldn't let the user proceed if there is no input or only whitespace as an input. Thank you in advance :)
For i As Integer = 0 To Val(TxtInput.Lines.Count) - 1
If TxtInput.Lines(i) = "" Then 'Ignores newline inputs
'Placeholder Comment
ElseIf IsNumeric(TxtInput.Lines(i)) Then 'Tests for Numbers
Temp.LbInput.Items.Add(TxtInput.Lines(i))
Temp.Show()
Else
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
This is the kind of thing linq-to-objects was made for:
Dim result = TxtInput.Lines.
Select(Function(line) line.Trim).
Where(Function(line) Not String.IsNullOrWhitespace(line) AndAlso IsNumeric(line)).
Select(Function(line) Val(line))
You can also do this:
Dim lines = TxtInput.Lines.Select(Function(line) line.Trim)
If lines.Any(Function(line) Not IsNumeric(line)) Then
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Exit Sub
Else
Dim result = lines.Where(Function(line) Not String.IsNullOrWhitespace(line)).
Select(Function(line) Val(line))
'Do more with "result" here
End If
Just store the trimmed line into a variable
For i As Integer = 0 To TxtInput.Lines.Count - 1
Dim line As String = TxtInput.Lines(i).Trim() '<======================
If line = "" Then 'Ignores newline inputs
'Placeholder Comment
ElseIf IsNumeric(line) Then 'Tests for Numbers
Temp.LbInput.Items.Add(line)
Temp.Show()
Else
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
Also, TxtInput.Lines.Count is an Integer already. No need to convert with Val, which, by the way, converts it into a Double.
Note that you can add items of any type to the ListBox, so you could as well convert the line into the desired type. I don't know if you need Integer or Double. Let's assume that you only want integer numbers. then you can change the code to
If TxtInput.Lines.Count = 0 Then
MsgBox("You have not entered anything. Please enter a number!", 1, "Error")
Else
For i As Integer = 0 To TxtInput.Lines.Count - 1
Dim line As String = TxtInput.Lines(i).Trim()
Dim number As Integer
If line = "" Then
MsgBox("Your input is empty. Please enter some numbers!", 1, "Error")
ElseIf Integer.TryParse(line, number) Then 'Tests for Numbers
Temp.LbInput.Items.Add(number)
Temp.Show()
Else
MsgBox("Please enter only valid numbers!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
End If
(Code changed according to your comments.)
If you want doubles, just declare number as Double and convert with Double.TryParse(line, number).

Is there any shorter way of writing this code?

I am extremely new to programming, currently just messing around with console apps. I've created a few things like a login screen and a currency converter but that was with aid from teachers. Never done anything by myself.
I'm wondering if there's any better/shorter way of writing this?
Module Module1
Sub Main()
Dim x As String
Dim Y As String
Dim yes As String
Dim no As String
x = "Please enter your name:"
Y = "Please enter 'Y' or 'N'"
yes = "Y"
no = "N"
Console.WriteLine(x)
Console.ReadLine()
Console.WriteLine("Do you wish to continue?")
yes = Console.ReadLine()
Console.WriteLine(Y)
If yes = "Y" Then
Console.WriteLine("You selected to continue")
Else
If no = "N" Then
Console.WriteLine("You selected to exit")
Environment.Exit(0)
End If
End If
Console.WriteLine("TEXT HERE") 'Text here as I don't know what to put next yet
Console.ReadLine()
Console.ReadLine() 'Just put this here so it doesn't exit straight away
End Sub
I had declared some variables just to try it out rather than just have Console.WriteLine("TEXT") constantly. I'm just trying to find ways of doing things.
I just ran the code again and saw that it's case sensitive to the user input, how would I go about having it be either Y or y and N or n?
You can use the following code:
Sub Main()
Console.WriteLine("Please enter your name:")
Console.ReadLine()
Console.WriteLine("Do you wish to continue?")
Do
Dim selectYN As String = Console.ReadLine()
If selectYN.ToUpper = "Y" Then
Console.WriteLine("You selected to continue")
Exit Do
ElseIf selectYN.ToUpper = "N" Then
Console.WriteLine("You selected to exit")
Environment.Exit(0)
Exit Do
Else
Console.WriteLine("Please enter 'Y' or 'N'")
End If
Loop
Console.WriteLine("TEXT HERE") 'Text here as I don't know what to put next yet
Console.ReadLine()
Console.ReadLine() 'Just put this here so it doesn't exit straight away
End Sub
The code is much more minified than your code. I added also a loop until the user added a valid answer for the yes/no question. The user have to enter one of the following values to break the loop: n, N, y, Y. If the value is not valid the question appears again to give himn a chance to enter a new value again.
How would I go about having it be either Y or y and N or n?
In this case you have the possibility to convert the letter toLower or toUpper. In the example above toUpper is used to check against N and Y.

error catching help in vb

having issues with error catching, I have been trying to fix this but not sure why its not working.
Update: I did not go in to much detail sorry about that.
On line six the user is mean to enter a number but if a user enters a letter the program crashes. I normally use double.tryparse and that works great, but for some reason getting a "Error 1 Overload resolution failed because no accessible 'TryParse' accepts this number of arguments" error message
Private Sub quadraticEquation()
Dim a, b, c, d As Double
Dim x1, x2, stra, strb, strc As String
Console.WriteLine("ax^2 + bx + c = 0")
Console.WriteLine("Please enter a")
stra = Console.ReadLine()
a = Double.Parse(stra)
If IsNumeric(stra) Then
Console.WriteLine("Please enter b")
strb = Console.ReadLine()
b = Double.Parse(strb)
Else
Console.WriteLine("Invalid input")
Call quadraticEquation()
End If
Console.WriteLine("Please enter c")
first you have to check if stra is numeric and only if its numeric parse it to a double type, you try to parse non numeric value to double and its not possible that is why exception is thrown.
If IsNumeric(stra) Then
a = Double.Parse(stra)
Console.WriteLine("Please enter b")
strb = Console.ReadLine()
b = Double.Parse(strb)
Else
Console.Write("Invalid input")
End If

Visual Basic Selection using a case statement task check

Just wondering if what I've done for my visual basic computing homework is correct. Our activity task:
"Activity: Grade Selection using a Case statement
Introduction:
You will use a case statement that will allow a user to enter a grade value as an integer value and return the grade as a letter ranging from A to E.
Selection Logic
If the number entered is between 91-100 the output will be A
If the number entered is between 81 and 90 the output will be B
If the number entered is between 71 and 80 the output will be C
If the number entered is between 61 and 70 the output will be D
If the number entered is between 51 and 60 the output will be E
Anything lower than 50 is a fail
Anything higher than 100 is an incorrect value and they will have to run the program again.
Create the necessary variables
Create necessary outputs telling the user the purpose of the program
Create the code to read in the user's first name
Create the code that reads in the grade as an integer value
Create the code that produces the relevant grade based on the above criteria.
Create the necessary output code to output the user's first name and their grade as a letter of the alphabet"
My code:
Module Module1
Sub Main()
Dim anum As Integer
Dim name As String
Console.WriteLine("This programme converts marks into grades")
Console.WriteLine("Please enter name...")
name = Console.ReadLine
Console.WriteLine("Please enter number of marks...")
anum = Console.ReadLine()
Select Case anum
Case 91 To 100
Console.WriteLine(name & " receives an A.")
Case 81 To 90
Console.WriteLine(name & " receives a B.")
Case 71 To 80
Console.WriteLine(name & " receives a C.")
Case 61 To 70
Console.WriteLine(name & " receives a D.")
Case 51 To 60
Console.WriteLine(name & " receives an E.")
Case Is <= 50
Console.WriteLine(name & ", unfortunately failed.")
Case Is > 100
Console.WriteLine(name & ", this is an incorrect value. Please try again.")
End Select
End Sub
End Module
Would be thankful if someone could just confirm it is correct or tell me if I have done something wrong or need to add something!
Thanks.
Original code seems to be ok Just I've improved it using the correct datatypes, adding basic exception castings, and trying to simplify things:
Module Module1
' Store ranges and chars
ReadOnly TupleList As New List(Of Tuple(Of Short, Short, Char)) From { _
Tuple.Create(51S, 60S, "E"c), _
Tuple.Create(61S, 70S, "D"c), _
Tuple.Create(71S, 80S, "C"c), _
Tuple.Create(81S, 90S, "B"c), _
Tuple.Create(91S, 100S, "A"c) _
}
' Set custom strings formatting
ReadOnly str_OK As String = "{0}, receives an {1}."
ReadOnly str_FAIL As String = "{0}, unfortunately failed."
ReadOnly str_INCORRECT As String = "{0}, this is an incorrect value. Please try again."
Sub Main()
' Initialize user variables with a default value (0)
Dim anum As Short = 0
Dim name As String = 0
Console.WriteLine("This programme converts marks into grades")
Console.WriteLine("Please enter name...")
name = CStr(Console.ReadLine)
Try
Console.WriteLine("Please enter number of marks...")
anum = CShort(Console.ReadLine())
Catch ex As FormatException
Console.WriteLine("Please enter a valid number...")
Environment.Exit(1) ' Exit from application returning an error exitcode
Catch ex As Exception
Console.WriteLine(String.Format("{0}: {1}", _
ex.Message, _
ex.StackTrace))
Environment.Exit(1) ' Exit from application returning an error exitcode
End Try
Select Case anum
Case Is <= 50
Console.WriteLine(String.Format(str_FAIL, name))
Case Is >= 101
Console.WriteLine(String.Format(str_INCORRECT, name))
Case Else ' User value is inside an accepted range
For Each Item As Tuple(Of Short, Short, Char) In TupleList
If (anum >= Item.Item1 AndAlso anum <= Item.Item2) Then
Console.WriteLine(String.Format(str_OK, name, Item.Item3))
Environment.Exit(0) ' Exit from application
' Exit For
End If
Next Item
End Select
Environment.Exit(1) ' Exit from application returning an error exitcode
' ( When Is <= 50 or Is >= 101 )
End Sub
End Module
The only thing I would do different than your original code is:
Use "Case Else" in place of "Case Is > 100" for your final Case statement.
This way it would handle an error if someone entered something other than a number.
Good work and good luck!

Console Application on VB2008 - Integer.TryParse Method Error

I am using Integer.TryParse Method to validate whether user input is a numeric or non-numeric in my program.
1)if the user input is numeric, the program will then proceed and validate that the user input is range from 0 to 9.
2)If the user is enter a non-numeric input, the program will display the message "invalid input" and ask user to start from beginning.
Following is my coding:
Sub Main()
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
Dim index As Integer
Dim number As Integer
Dim reEnter As Boolean = True
Console.WriteLine("Please enter 7 integers: ")
Console.WriteLine("<ATTENTION: FROM 0 TO 9 ONLY>")
Console.WriteLine()
While reEnter
For index = 0 To 6
Console.WriteLine("Please enter the integer no." & "{0}" & " : ", index + 1) 'Prompt user to enter 7 integers.
sevenNumbers(index) = Console.ReadLine() 'The 7 integers are stored in an array.
If Integer.TryParse(sevenNumbers(index), number) Then
While sevenNumbers(index) < 0 Or sevenNumbers(index) > 9
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End While
Else
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End If
reEnter = False
Next
End While
End Sub
However, when a user enter a non-numeric input, the program can't continue and shows an error that forced to close.
i tried this
Sub Main()
Dim num As Integer
Console.Write("enter num:")
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
Console.WriteLine("valid. num = " & num)
Else
Console.WriteLine("invalid")
End If
End Sub
it does works and i am wondering which part of my coding is wrong??
Thank for help!!
Your two samples of code are different. In your second attempt, you do this:
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
The above code reads into a variable called input that will be a String (because Console.ReadLine returns a String). Then, you try to parse the string into a number.
However, in your original code, you do this (some lines omitted for clarity):
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
...
sevenNumbers(index) = Console.ReadLine()
In this case, you are reading into a variable that you have explicitly declared to be an Integer. If the user types "abc" then the conversion will fail at this point - you won't even get to the TryParse because you can't complete the innput.
Instead of reading to an integer, you need to read into a String variable and then parse that value into an Integer (as you did in your second code).
You could have spotted this yourself by taking note of the line that the error actually occurs on when debugging: you should note that the program crashes on the ReadLine, not on the TryParse.
Um. This line:
sevenNumbers(index) = Console.ReadLine()
Is storing whatever text has been read into an array of Integers. If it's compiling, then by the time you reach any later code, you're too late to control the conversion. It's already happened.
Maybe sevenNumbers should be String()?
(You really ought to turn on OPTION STRICT and OPTION EXPLICIT - it should find problems like this for you when it compiles the code)