Visual Basic无效的转换运行时错误

时间:2015-01-24 08:29:17

标签: vb.net

我是Visual Basic的新手,现在正在执行任务。这是我的代码

Sub Main()
    Console.Write("Please let me know your nickname: ")
    Dim name As String = Console.ReadLine()
    Console.WriteLine("Thank you " + name + "!")
    Console.WriteLine()
    Console.Write("How many litres " + name + "<only whole litres please>? ")
    Dim litres As Integer = Console.ReadLine()
    Console.Write("Premium quality? <y/n>: ")
    Dim ans As Char = Console.ReadLine()
    Dim prem As Boolean
    If ans = "y" Then
        prem = True
    ElseIf ans = "n" Then
        prem = False
    End If

    Console.WriteLine()
    Console.WriteLine("WELCOME TO APU'S GAS STATION")
    Console.Write("Quality:     ")
    If prem = True Then
        Console.Write("Premium")
    Else : Console.Write("Regular")
    End If

    Dim price As Double = 12.44
    Console.WriteLine("Quantity <l>:    " + litres)
    Console.WriteLine("Price per l:     " + price)
    Console.WriteLine("Sum to pay: " + litres * price)

    Console.ReadLine()
End Sub

在运行时我可以输入所有数据没有问题,但后来我得到一个错误,我可以粗略地翻译成&#34;字符串的无效演员&#34;数量:&#34;键入&#39; Double&#39;。 我不太确定发生了什么,会很感激指点。

2 个答案:

答案 0 :(得分:2)

要避免此问题,您可以使用

Console.WriteLine("Quantity <l>:    " + litres.ToString)

或者您可以使用

Console.WriteLine("Quantity <l>:    " + CStr(price))

答案 1 :(得分:-1)

我修复了你的代码,这应该可行:

 Sub Main()
    Console.Write("Please let me know your nickname: ")
    Dim name As String = Console.ReadLine()
    Console.WriteLine("Thank you " & name & "!")
    Console.WriteLine()
    Console.Write("How many litres " & name & "<only whole litres please>? ")
    Dim litres As Integer = Console.ReadLine()
    Console.Write("Premium quality? <y/n>: ")
    Dim ans As Char = Console.ReadLine()
    Dim prem As Boolean
    If ans = "y" Then
        prem = True
    ElseIf ans = "n" Then
        prem = False
    End If

    Console.WriteLine()
    Console.WriteLine("WELCOME TO APU'S GAS STATION")
    Console.Write("Quality:     ")
    If prem = True Then
        Console.Write("Premium")
    Else : Console.Write("Regular")
    End If

    Dim price As Double = 12.44
    Console.WriteLine("Quantity <l>:    " & litres)
    Console.WriteLine("Price per l:     " & price)
    Console.WriteLine("Sum to pay: " & (litres * price))
    Console.ReadLine()
End Sub