How to effectively error check and evaluate a user input? - input

I am a very beginner programmer that is taking a class in school. We have a project where we are required to check if a user input is an integer, if it is not, we have to return an error message. Would anybody know how to do such a thing?

Check input value is integer:
REM check if user input is integer
PRINT "Input";
INPUT X$
IF VAL(X$) THEN
PRINT "Input is numeric value"
END IF

Check if input is integer or fractional
EDIT: 05/07/2018 to include error checking
REM check if user input is integer
ON ERROR GOTO 100
PRINT "Input";
INPUT X$
IF VAL(X$) THEN
IF INSTR(X$, ".") THEN
PRINT "Input is fractional"
ELSE
PRINT "Input is numeric value"
END IF
END IF
END
100 IF ERR = 6 THEN PRINT "Overflow"
END

Related

IndentationError: expected an output

Here I am coding in python for get output of length of any string. If user enter a integer value then print "Integer doesn't have length" else print the length of string.
Here is my code
def string_length(word):
if type(word) == int:
print("Integer doesn't have length")
else:
print("Length:", len(word))
word = input("Enter Word: ")
string_length(word)
print("End of Program!")
Here is my output result
Enter Word: 65
Length: 2
End of Program!
Thanks in Advance!
It's because input in python is taken as a string by default. One of the ways you can do this is checking string is numeric or not.
if word.isnumeric():
print("Integer doesn't have a length")

Validation to ensure value entered is a integer

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

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).

Validating user input excel vba

I have the following user input set up in excel vba. The function when called asks the user to input a single number no greater than 9999, or two numbers in the format XXXX-XXXX where two numbers are separated by a dash. In that case, the numbers cannot be greater than 9999 in either case, or at least shouldn't.
The goal is to return either a single number (IE 50) or a range (IE low value is 50,high value is 75). Currently as set up it should be returning an array, where the first position is the low value, and the second position is high value. Or, if the user only enters one number, it should return that one number in the first position of an array.
Currently it checks that A) user has entered in a number, B) the number is not greater than 4 digits long.
Unfortunately it is not returning an array, it is returning an error. Subscript out of range.
Also, are there any other likely user inputs that should be checked for here? The application is not going to be widely used by people, but I'd like to minimize potential errors as well.
Public Function getUserInput() As Variant
'this function gets a user input from an input box and puts it out into the proper format
Dim inputString As String
Dim numArr() As String
Dim i As Long
' On Error GoTo NotValidInput
inputString = Trim(InputBox("Enter the rows you'd like to print"))
'has the user entered a dash into their user input
If InStr(inputString, "-") > 0 Then
numArr() = Split(inputString, "-")
If UBound(numArr) <> 1 Then
GoTo NotValidNumberFormat
End If
If (IsNumeric(numArr(0)) And Len(numArr(0)) <= 4) And (IsNumeric(numArr(1)) And Len(numArr(1)) <= 4) Then
getUserInput = numArr
Exit Function
Else
GoTo NotValidNumberFormat
End If
'no dash
'60
Else
If (IsNumeric(CInt(inputString))) And Len(inputString) <= 4 Then
getUserInput = numArr
Exit Function
Else
GoTo NotValidNumberFormat
End If
End If
Exit Function
NotValidNumberFormat:
'if the conversion failed, return error
MsgBox ("Please enter the number in a valid format - either a single number no larger than 9999 or two numbers no larger than 9999 separated by only one dash (IE XX-XX)")
getUserInput = -1
End Function
this should do:
Public Function getUserInput() As Variant
'this function gets a user input from an input box and puts it out into the proper format
Dim numArr As Variant
Dim goOn As Boolean
Do
numArr = Split(WorksheetFunction.Trim(InputBox("Enter the rows you'd like to print in the format 'nnnn' or 'nnnn-mmmm'")), "-")
Select Case UBound(numArr)
Case 0
goOn = Format(numArr(0), "0000") Like "####"
Case 1
goOn = Format(numArr(0), "0000") Like "####" And Format(numArr(1), "0000") Like "####"
End Select
If Not goOn Then MsgBox "Please enter the number in a valid format - either a single number no larger than 9999 or two numbers no larger than 9999 separated by only one dash (ex: XX-XX)"
Loop While Not goOn
getUserInput = numArr
End Function

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)