只有数字,不允许使用字母 - 用户输入
我正在编写一个控制台应用程序,需要用户输入某些值。我想禁止任何字母输入。控制台自动写入“从字符串”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
前端模块
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
前端模块
那么对于初学者,在Try - Catch
应该是里面的输入采集For
循环。由于您的程序是现在编写的,只要输入了一个错误的值,就会跳转到catch并且程序结束!如果您尝试将输入转换为小数,则不需要手动抛出异常,如果输入不是小数,则会自动抛出!尝试将当前控制台输入作为小数转换,然后将该数字添加到列表中。
Dim inputNumber as Decimal = CDec(Console.ReadLine())
Input.Add(inputNumber)
而且n
将相同数量的每一次,所以你是怎么做的,它不会工作(查找列表是如何工作的基本知识,如何元素添加到列表以及如何显示列表元素)
当我把“如果输入= Integer.MaxValue”程序将正确运行,我所需要的是让我的异常消息显示。 – 2011-05-02 21:04:39
'if input = Integer.MaxValue'是无稽之谈。用所有有效的数字尝试你的程序,你会发现你的程序不正确。用你最新的代码更新你的问题,然后按照我给你的建议。 – Michael 2011-05-02 21:43:31
我尝试添加,但我认为我没有做对。 – 2011-05-02 22:54:12
你能显示你的代码吗?这条消息是如何产生的?你只是将例外转储到控制台窗口? – mellamokb 2011-05-02 16:51:42
@mellamokb我发布了我的代码,我不确定消息是如何生成的,但它显示出来。 – 2011-05-02 17:04:19