【问题标题】:Conversion from string "" to type 'Double' is not valid In .NET Fiddle's VB从字符串“”到类型“双”的转换在 .NET Fiddle 的 VB 中无效
【发布时间】:2016-08-09 14:13:17
【问题描述】:

我正在学校编写一个项目(在 .NET Fiddle 的 VB 控制台上)并且遇到错误。

在这项任务中,我们必须: 使用学生姓名输入 10 个测试结果。 在输入时验证所有数据并拒绝不良数据 我们需要打印出平均值(算术平均值)、最高分和谁得到它(假设每次测试最多 1 个)、最低分和谁得到它(假设每次测试 1 分钟)

我的个人代码如下:

Imports System

Public Module Module1
Public Sub Main()
Dim sStudentName As String
Dim iStudentMark As Double
Dim iHighMark As Integer
Dim iLowMark As Integer
Dim iAve As Integer

For List = 1 to 10

    Console.WriteLine("Input A Students Name")
    sStudentName = Console.ReadLine()
    Console.WriteLine("This student's Mark is")
    iStudentMark = Console.ReadLine()


    Do Until 25<= iStudent Or iStudentMark <= 100
        Console.WriteLine("Error. Invalid Percentage. Re-input.")
        iStudentMark = Console.ReadLine()
    Loop

    iAve = iAve + iStudentMark

    If iStudentMark > iHighMark Then
        iHighMark = iStudentMark
        Console.Write("The Highest Percentage has changed. The top score is now " + iStudentMark + " Percent from " + sStudentName)
    End If

    If iStudentMark < iLowMark Then
        iHighMark = iStudentMark
        Console.Write("The Highest Percentage has changed. The top score is now " + iStudentMark + " Percent from " + sStudentName)
    End If

Next 
iAve = iAve/10
Console.WriteLine(iAve)

End Sub
End Module

我得到的错误信息是/是:

运行时异常(第 -1 行):从字符串“最高 Percentage has chang" 键入 'Double' 无效。

堆栈跟踪:

[System.FormatException: 输入字符串格式不正确。]

[System.InvalidCastException:从字符串“最高 Percentage has chang" 输入 'Double' 无效。]

我从来都不是最擅长编码的人,非常感谢那些尝试解决它的人。

【问题讨论】:

  • 在 VB 中使用 & 来连接字符串,而不是 '+'

标签: vb.net string validation double type-conversion


【解决方案1】:

Console.ReadLine() 方法将返回一个您不能直接将其分配给 double 的字符串。您需要将它们转换为双倍。

Console.WriteLine("This student's Mark is")
If Not Integer.TryParse(Console.ReadLine(), iStudentMark) Then
    Console.WriteLine("Invalid input..! failed to convert")
End If
'you can proceed with iStudentMark

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多