Console Application on VB2008 - Integer.TryParse Method Error - vb.net

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)

Related

Why is Visual Basics Console.ReadLine Buggy and can I fix it?

Hey question about a visual basics program, I am using Console.ReadLine into a string but it seems when I get to that part of the program or any part of my console program the keyboard enter key enters twice or something it completly skips a ReadLine and recieves the input.length 0 before I even have a chance to enter a string.
This isnt runable without my full code I dont think but I cant seem to get ReadLine to prompt for a string when it is initially run, it always returns 0 once and then loops normally. Im wondering if that has something to do with my keyboard or keyboard settings for a visual basics program or command line.
I dont think its a keyboard error because when I am entering code into visual basics it works fine and doesnt send two returns. I couldnt get the full code in code blocks.
...
Shared Sub Main()
Dim s As New Space()
Dim Ship As New Ships()
Dim Run As Boolean = True
Dim ChooseName As Boolean = True
Dim ch As Char
Dim PlayerName As String
While Run = True
s.PrintWelcome()
ch = Convert.ToChar(Console.Read())
If ch = "1" Then
While ChooseName = True
Console.WriteLine("Choose a Name Less then 50 Characters: ")
PlayerName = Console.ReadLine()
If PlayerName.Length > 50 Then
Console.WriteLine("Name is to Long!")
ElseIf PlayerName = "Q" Then
Run = False
Exit While
ElseIf PlayerName.Length <= 0 Then
Console.WriteLine("Please Enter a Player name or Q by itself to quit.")
Else
ChooseName = False
Console.WriteLine("PlayerName: " & PlayerName & " PlayerName.Length: {0}", PlayerName.Length)
End If
End While
If Run = True Then
End If
ElseIf ch = "2" Then
ElseIf ch = "3" Then
Run = False
ElseIf ch = "Q" Then
Run = False
Else
s.PrintWelcome()
End If
End While
End Sub
...
I suspect that you really ought to be structuring your code more like this:
Module Module1
Sub Main()
Do
Console.Write("Please select a menu item from 1, 2, 3 or Q to quit: ")
Dim menuSelection = Console.ReadKey()
Dim input As String = Nothing
Console.WriteLine()
Select Case menuSelection.KeyChar
Case "1"c
Console.WriteLine("What did you want to say about 1?")
input = Console.ReadLine()
Case "2"c
Console.WriteLine("What did you want to say about 2?")
input = Console.ReadLine()
Case "3"c
Console.WriteLine("What did you want to say about 3?")
input = Console.ReadLine()
Case "q"c, "Q"c
Exit Do
Case Else
'Do nothing before repeating the prompt.
End Select
If Not String.IsNullOrEmpty(input) Then
Console.WriteLine("You said: " & input)
End If
Loop
End Sub
End Module
The ReadKey call will immediately read the first key entered by the user. Rather than requiring the user to hit Enter after that key, the application writes the line break itself. It then tests the chararacter represented by that key to see if it is a valid menu item. If it is, it does whatever is appropriate for that item, whether that be reading a line of input or quitting. If the key does not represent a valid menu item then it simply loops back to the prompt. Note also that the Char value entered by the user is actually compared to Char literals, the way it should be done, rather than String literals.

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.

inputBox Excel VBA Integer problems

I am new to VBA and I'm trying to create a macro that from a inputBox accepts a number between 0 and 1000 and converts it to hexadecimal. Well it works, but I am struggling to keep the program accepting that range ( 0 - 1000). This is what happens:
If I input -1 it throws a error;
If I input -1001 it throws a FFFFFFFC17;
If I input any value above 1000 it doesn't throw a MsgBox (I am not familiar with causing error on excel for now).
I've done first like this:
Sub DecToHex()
Dim inputDec As Integer
Dim outputHex As String
inputDec = InputBox("Decimal?")
If inputDec <= 1000 And inputDec >= 0 Then
outputHex = Application.WorksheetFunction.Dec2Hex(inputDec)
MsgBox ("Hex: " + outputHex)
Else
MsgBox ("Error! Please define decimal. It must be larger than zero and less than 1001")
inputDec = InputBox("Decimal?")
outputHex = Application.WorksheetFunction.Dec2Hex(inputDec)
MsgBox ("Hex: " + outputHex)
End If
End Sub
But then I thought well inputBox gives me input as string, so maybe I should accept values as string, so I changed:
Dim inputDec As Integer
'Changed to
Dim inputDec As String
Which still did a poorly control on variables ( ie. it accepts -1200, as also 1200 ). So can you point out what am I doing wrong? Maybe it's the Worksheet Function I'm not reading well. I know it's newbie mistake but it's important for me to understand how to control these input variables from inputBox.
You need to declare the inputDec As Variant
You need to Handle the Cancel Button
You need to put the code in a loop so that when user enters an invalid number, the inputbox can pop up again.
You need to use Application.InputBox with Type:=1 so that only numbers can be accepted.
Try this
Sub DecToHex()
Dim inputDec As Variant
Dim outputHex As String
Do
inputDec = Application.InputBox("Decimal?", Type:=1)
'~~> Handle Cancel
If inputDec = "False" Then Exit Do
If inputDec <= 1000 And inputDec >= 0 Then
outputHex = Application.WorksheetFunction.Dec2Hex(inputDec)
MsgBox ("Hex: " + outputHex)
Exit Do '<~~ Exit the loop
Else
MsgBox ("Error! Please define decimal. It must be larger than zero and less than 1001")
End If
Loop
End Sub

For loop for bowling score array

I am trying to create a bowling program that will display the scores given in a multi-line text box. I've manage to get the program giving an output, but when it runs it skips asking for new inputs and just gives 5 0s on seperate lines and nothing else. I'm completely lost, any help is very much appreciated
EDIT: Sorry should have changed errors to reflect the programs changes, it looks like this now. It gives 0's instead of using the value I gave it, but it does ask for each input now.
For gameNumber As Integer = 1 To 5 Step 1
lblEnterScore.Text = "Enter Score for game #" & gameNumber
Dim Testint As Integer ' define an Integer for testing
Try
Testint = CInt(txtScoreInput.Text) ' try to convert whatever they entered to Int
Catch
MessageBox.Show("Entry is not an Integer") ' If you are here then the CInt failed for some reason, send a message
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End Try
If txtScoreInput.Text.Contains(".") Then
MsgBox("Bowling Score must be a whole number.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
If txtScoreInput.Text > MAXIMUM_SCORE Or txtScoreInput.Text < MINIMUM_SCORE Then
MsgBox("Bowling Score must be between 1 and 300.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
scoreInput(gameNumber) = CInt(txtScoreInput.Text)
' and store it in the array
' and increment the gamecounter for the next time through the loop
Next
'btnEnterScore.Enabled = False
' place the good score into the multi-line textbox
txtScoreOutputs.Text = gameScore & vbCrLf & txtScoreOutputs.Text
End Sub
If it was me, here's what I would do... Just a suggestion; I also cut out over half of your code and stopped it from throwing exceptions as well... You can put this in a click event or where ever you need it as well. You can modify this as well to take as many as you want from user input as well not just limit them from entering score's. Your user also has the option to get out of that loop when they choose to do so as well, not keeping them inside the loop...
Private ScoreLists As New List(Of Integer) 'Hold your inputted values
Private Const MAXIMUM_SCORE As Integer = 300 'Max score
Private Const MINIMUM_SCORE As Integer = 1 'Min score
Private blnStop As Boolean = False
Try
For gameNumber As Integer = 1 To 5
Dim intScore As Integer = 0
Do Until (intScore >= MINIMUM_SCORE And intScore <= MAXIMUM_SCORE) OrElse blnStop
If Not Integer.TryParse(InputBox("Please enter a score for game # " & gameNumber.ToString), intScore) Then
If MsgBox("Bowling Score must be a whole number. Stop getting scores?.", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
blnStop = True
Exit For
End If
End If
Loop
ScoreLists.Add(intScore)
Next
'Display the results...
For i As Integer = 0 To ScoreLists.Count - 1
txtScoreOutputs.Text &= ScoreLists.Item(i.ToString)
Next
ScoreLists.Clear()
Catch ex As Exception
End Try
Construct your logic like this (pseudo):
Loop
{
AskUserForInput()
ProcessUserInput()
}
The loop part will control how many scores the user is prompted to enter. The AskUserForInput() function will prompt the user to type in a new score, and the ProcessUserInput() function will get the value and store it in an array or print it to the screen, etc.
Your current logic is not waiting for any new user input before trying to add to the scores. You are also getting zeros because you're setting the txtScoreOutputs with gameScore, which doesn't look like it's been set to the user's input.