[英]How to Loop until a variable inputted by the user is an integer in VB.NET?
Here is the code I have so far: 这是我到目前为止的代码:
Module Module1
Sub Main()
Dim A, B, C, D As Integer
Do
Try
System.Console.WriteLine("How high is the cube?")
A = Int32.Parse(Console.ReadLine())
Catch leg As System.FormatException
System.Console.WriteLine(leg.Message)
Finally
End Try
Loop Until A =
System.Console.WriteLine("How wide is the cube?")
B = Int32.Parse(Console.ReadLine())
System.Console.WriteLine("How long is the cube?")
C = Int32.Parse(Console.ReadLine())
D = A * B * C
Console.WriteLine(D)
System.Console.ReadKey()
End Sub
End Module
I want the first try block to loop till A is an Integer in case the user inputs a letter instead of a number. 我希望第一个try块循环播放直到A是一个整数,以防用户输入字母而不是数字。 Does anyone know how I might do that? 有人知道我该怎么做吗?
Use TryParse instead of your try/catch block in conjunction with a do loop. 将TryParse代替try / catch块与do循环结合使用。 It returns True when it succeeds and puts the int32 value into the variable a
. 成功时它将返回True,并将int32值放入变量a
。
Dim a As Integer, tmp As String
Do
System.Console.WriteLine("How high is the cube?")
tmp = Console.ReadLine()
Loop While Int32.TryParse(tmp, a) = False
After the loop, the value stored in a
will be an integer. 在循环之后,将存储在值a
将是一个整数。 Repeat this for each of the other values. 对其他每个值重复此操作。
You can also do like Dai does in his C# sample, and not bother storing into a temporary variable: 您还可以像Dai在C#示例中所做的那样,而不必费心将其存储到临时变量中:
Dim a As Integer
Do
System.Console.WriteLine("How high is the cube?")
Loop While Int32.TryParse(Console.ReadLine(), a) = False
If you MUST do it with Try/Catch for an assignment, you can try this though for practical purposes I would do it as above. 如果您必须使用“尝试/抓住”进行分配,则可以尝试此操作,但出于实际目的,我会如上所述进行操作。
Dim a As Integer, valid As Boolean = True
Do
Try
System.Console.WriteLine("How high is the cube?")
a = Int32.Parse(Console.ReadLine())
Catch ex As Exception
valid = False
End Try
Loop While Not valid
In C# (conversion to VB is an exercise for the reader): 在C#中(转换为VB是读者的练习):
public static Int32 GetInt32() {
Int32 value;
while( !Int32.TryParse( Console.ReadLine(), out value ) ) {
Console.WriteLine("Please enter an integer");
}
Console.WriteLine("You entered {0}", value);
return value;
}
Here's a real world example to further expand on one reason why using Try/Catch to control program flow is bad. 这是一个真实的示例,它进一步说明了使用“尝试/捕获”控制程序流不好的一个原因。 At least in .NET, throwing an error and handling it in a catch takes a lot more execution time than properly handling the error using proper control flow structures. 至少在.NET中,与使用适当的控制流结构正确处理错误相比,抛出错误并在catch中处理错误要花费更多的执行时间。
I picked up a project from a coworker who was using a function to clean input coming in that was supposed to be numeric. 我从一个同事那里接了一个项目,该同事正在使用一个函数来清理传入的数字输入。 He was using something like the following code to do it. 他正在使用类似以下代码的方法来执行此操作。
Public Shared Function SafeDouble(value As Object, Optional DefaultValue As Double = 0.0) As Double
Dim CleanDouble As Double
Try
CleanDouble = CDbl(value) 'try to convert to a double
Catch ex As Exception
CleanDouble = DefaultValue 'if it fails use the default value
End Try
Return CleanDouble
End Function
Which worked fine for the one place he was using it originally to process one row of data. 这对于他最初使用它来处理一行数据的一个地方来说效果很好。 The problem came about when I started using this to process 1000s of rows of data. 当我开始使用它来处理数千行数据时,就会出现问题。 The execution bogged down big time when it hit this section of the import. 当执行到达导入的这一部分时,执行陷入了沉迷。
Using some timers, I determined that it was taking between 50 and 100 milliseconds for each value that it couldn't convert and threw an exception for. 通过使用一些计时器,我确定无法转换的每个值花费50到100毫秒之间的时间,并引发异常。
I changed the code to use a proper control structure and the time dropped to 2 to 5 milliseconds per value it couldn't convert. 我更改了代码以使用适当的控制结构,并且将每个无法转换的值的时间减少到2到5毫秒。 The current code is below. 当前代码如下。 I know that it's possible that some value might come in that isn't numeric. 我知道可能会出现一些非数字值。 If it isn't numeric, I just assign the default value right away. 如果不是数字,则立即分配默认值。
Public Shared Function SafeDouble(value As Object, Optional DefaultValue As Double = 0.0) As Double
Dim CleanDouble As Double
Try
If IsNumeric(value) Then 'test to see if the data is numeric before converting it
CleanDouble = CDbl(value)
Else
CleanDouble = DefaultValue 'if it isn't numeric, use default value
End If
Catch ex As Exception
CleanDouble = DefaultValue 'if something unexpected happens, use default value
End Try
Return CleanDouble
End Function
As you can see, I have handled the expected error of it not converting because it isn't numeric. 如您所见,由于它不是数字,所以我已经处理了它不转换的预期错误。 This should account for the majority of issues that are likely to occur. 这应解决可能发生的大多数问题。 I still leave the try/catch in there in case some other, unexpected error occurs. 我仍然将try / catch保留在那里,以防发生其他意外错误。
I have one more concept to add. 我还有一个概念要补充。 Methods fire exceptions, to let you handle inlikely problems and prevent application crash. 方法会引发异常,以使您处理可能的问题并防止应用程序崩溃。 Readlin and writeline can throw exceptions, and if you dont catch them and they happen, your program will crash. Readlin和writeline可能会引发异常,如果您没有捕获到它们而发生了,则程序将崩溃。 Use the try block to do what its meant for: handle unlikely crashes to increae robustness. 使用try块可以实现其目的:处理不太可能发生的崩溃,以提高鲁棒性。 To do a thorough job you should research the exceptions and write code to prevent the crash. 要彻底完成工作,您应该研究异常并编写代码以防止崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.