error catching help in vb - vb.net

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

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.

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

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.

Need to figure out how to use Try, Catch, and Finally in my code?

I am a very beginner programmer, if even that. I have to take a programming course as one of my classes in high school, so I am trying my best to make it through not really understanding much. With that said, please go easy on me.
For a project, I need to go back to two programs I created for a previous assignment, a program for determining an arithmetic sequence, and a program for calculating the volume of a cube or sphere.
The first instructions are to write the program so that it asks the user to define all variables. For example, the program would ask the user to input the value of the length of one side or the radius for the Cube and Sphere program.
I believe I already did this when I wrote the program, but I am struggling with the second set of directions, which states to "include the key words Try, Catch, and Finally, and have them function properly (ie. if the user defines an impossible calculation, there must be an error message shown; if not, there must be some action to indicate there was no error even if it is simply showing the answer)".
I really do not know how to put these statements into my code. If someone could explain or give me an example of them in my code I would very much appreciate it! Here is my code:
Volume of a Cube or Sphere
Sub Main()
Dim Type As String
Dim Size As String
Dim Length_Radius As Double
Dim Output As Double
Dim Value As Double
Console.WriteLine("Would you like to calculate the volume of a (C)ube or a (S)phere? *press either C or S then enter to continue*")
Type = Console.ReadLine
Type = Convert.ToString(Type)
Value = Asc(Type)
If (Value = 67) Or (Value = 99) Then
Console.WriteLine("The equation is x^3 where x is the length of a side. What would you like the value of x to be?")
Size = Console.ReadLine
Length_Radius = Convert.ToDouble(Size)
Output = (Length_Radius * Length_Radius * Length_Radius)
Console.WriteLine("The value of the volume of the Cube is: " & Output & ".")
ElseIf (Value = 83) Or (Value = 115) Then
Console.WriteLine("The equation is 4/3*pi*r^3 where r is the radius. What would you like the value of the radius to be?")
Size = Console.ReadLine
Length_Radius = Convert.ToDouble(Size)
Output = ((4 / 3) * 3.14 * (Length_Radius * Length_Radius * Length_Radius))
Console.WriteLine("The value of the volume of a sphere is: " & Output & ".")
ElseIf (Value <> 83) Or (Value <> 115) Or (Value <> 67) Or (Value <> 99) Then
Console.WriteLine("You have inputted an incorrect value.")
End If
Console.ReadLine()
End Sub
Arithmetic Sequence
Sub Main()
Dim Letters As String
Dim a_n, d, a_one As Double
Dim Output As Double
Console.WriteLine("This program will perform the arithmetic sequence (a(n) = a(1) + d(a(n) - 1)")
Console.WriteLine("What would you like the value of 'a(n)' to be? *The total number of times the sequence will repeat.*")
Letters = Console.ReadLine
a_n = Convert.ToDouble(Letters)
Console.WriteLine("What would you like the value of 'a(1)' to be? *The starting value.*")
Letters = Console.ReadLine
a_one = Convert.ToDouble(Letters)
Console.WriteLine("What would you like the value of 'd' to be? *The number that the equation is multiplied by*")
Letters = Console.ReadLine
d = Convert.ToDouble(Letters)
Output = (a_one + d * (a_n - 1))
Console.WriteLine("The value of the arithmetic sequence is: " & Output & ".")
Console.ReadLine()
End Sub
Computers could encounter a problem when performing an operation. For example if someone asks you to calculate the cube of x but enters x as "abc", the computer can't do that. Good programs validate data before performing calculations and try to provide a gentle handling of errors by warning the user with a friendly message amongst other possible actions. In you code you write:
Size = Console.ReadLine
Length_Radius = Convert.ToDouble(Size)
This code could cause an error if you try a non-numeric value. A better way to write this is to use a method called TryParse, however, for the sake of your question we'll use Try/Catch. Try/Catch allows the program to try to perform one or more commands and if any of them causes an error the control flows to the catch part where the programmer is able to handle the error.
Applying this concept to your code, this is one way to use Try/Catch:
Dim Type As String
Dim Size As String
Dim Length_Radius As Double
Dim Output As Double
Dim Value As Double
Console.WriteLine("Would you like to calculate the volume of a (C)ube or a (S)phere? *press either C or S then enter to continue*")
Type = Console.ReadLine
Type = Convert.ToString(Type)
Value = Asc(Type)
Try
If (Value = 67) Or (Value = 99) Then
Console.WriteLine("The equation is x^3 where x is the length of a side. What would you like the value of x to be?")
Size = Console.ReadLine
Length_Radius = Convert.ToDouble(Size)
Output = (Length_Radius * Length_Radius * Length_Radius)
Console.WriteLine("The value of the volume of the Cube is: " & Output & ".")
ElseIf (Value = 83) Or (Value = 115) Then
Console.WriteLine("The equation is 4/3*pi*r^3 where r is the radius. What would you like the value of the radius to be?")
Size = Console.ReadLine
Length_Radius = Convert.ToDouble(Size)
Output = ((4 / 3) * 3.14 * (Length_Radius * Length_Radius * Length_Radius))
Console.WriteLine("The value of the volume of a sphere is: " & Output & ".")
ElseIf (Value <> 83) Or (Value <> 115) Or (Value <> 67) Or (Value <> 99) Then
Console.WriteLine("You have inputted an incorrect value.")
End If
Catch ex As Exception
'VB.NET will capture the error text in a property called ex.Message.
'Let's show this message to the user as follows:
Console.WriteLine(" A problem occurred:" + Environment.NewLine + ex.Message)
Finally
'Logic will come here eventually after calculation is attempted
Console.WriteLine("I am done with calculations")
End Try
Console.WriteLine("Press enter to exit")
Console.ReadLine()
Try the above code when x is ABC. It is best to do that during debug so you can see the program flow. You should not have 1 big try/catch in your program. Instead, you generally place several such blocks only where you anticipate problems and where your code could prevent damage or provide useful feedback for the user.
Here is another example about this topic.
MSDN-TryCatch1
MSDN-TryCatch2
Note that you should handle the case where the user could enter a negative value for X. This does not require a try/catch, rather an 'if'.

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)