我正在编写一个控制台应用程序,需要用户输入某些值。我想不允许任何字母输入。控制台自动写入“从字符串转换”b“到类型'整数'无效。”但我希望控制台显示我的个人信息“不是有效号码,请再试一次。”我怎样才能做到这一点?
我尝试过很多不同的关键词和短语但没有效果。也许我做错了(不是不太可能)或者它只是意味着别的东西。无论哪种方式,我都需要帮助。
回顾一下:控制台中的用户输入只允许数字而不是字母,并会显示我的信息。
我不想发布我的代码,因为人们总是选择它,但现在就是这样。请注意,必须有例外。这是家庭作业,我需要一个例外,这是用户搞砸的一种方式。请不要告诉我不要使用例外。
Module Module1
Sub Main()
Try
System.Console.WriteLine("Input up to 10 valid numbers to have them mathematically averaged.")
For Index = 0 To 9
Dim Input As IList
Input = Console.ReadLine()
Next Index
If ' here is where I want to add that numbers only Then
Throw New exception("Not a valid number, please try again.")
Else
System.Console.WriteLine("Now averaging numbers...")
Dim average As Double = (n + n + n + n + n + n + n + n + n + n) / 10
Console.WriteLine("The average of " & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & " and " & n & " is " & average & ".", "Calculation")
End If
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
结束模块
答案 0 :(得分:1)
Dim inputString = Console.ReadLine
If Integer.TryParse(inputString, num) Then
DoSomething(num)
Else
Console.WriteLine("Not a valid number, please try again.")
End If
这是一种方法,可以满足您的要求:
Module Module1
Sub Main()
System.Console.WriteLine("Input valid numbers seperated by spaces to have them mathematically averaged.")
Dim inputArray As String() = System.Text.RegularExpressions.Regex.Replace(Console.ReadLine().Trim(), "\s{2,}", " ").Split(New Char() {" "})
Dim values As New ArrayList
Dim sum As Integer
For i As Integer = 0 To inputArray.Length - 1
Try
sum = sum + Integer.Parse(inputArray(i), Globalization.NumberStyles.Integer)
values.Add(inputArray(i))
Catch ex As Exception
Console.WriteLine(String.Format("The value ""{0}"" is not a valid number and will be ignored. ExceptionMessage: {1}", inputArray(i), ex.Message))
End Try
Next
Dim average As Decimal = sum / values.Count
Console.WriteLine(vbCrLf)
Console.WriteLine(String.Format("The average of ""{0}"" is {1}", Join(values.ToArray, ", "), average))
Console.WriteLine(vbCrLf)
Main()
End Sub
结束模块
答案 1 :(得分:0)
对于初学者来说,Try - Catch
应该在输入聚集For
循环中。当你的程序现在被编写时,只要输入一个错误的值,执行就会跳转到catch并且程序结束!如果您尝试将输入转换为十进制,则不需要手动抛出异常,如果您的输入不是小数,它将自动抛出!尝试将当前控制台输入转换为十进制,然后将该数字添加到列表中。
Dim inputNumber as Decimal = CDec(Console.ReadLine())
Input.Add(inputNumber)
每次n
都是相同的数字,所以你的工作方式不起作用(查看列表如何工作的基础知识,如何将元素添加到列表以及如何显示列表元素)