【问题标题】:In Visual Studio 2017 Visual Basic, I get an "End of statement expected" error在 Visual Studio 2017 Visual Basic 中,我收到“预期语句结束”错误
【发布时间】:2020-02-05 21:16:41
【问题描述】:

在以下代码中,我收到“预期语句结束”和“'Text' 不是字符串成员”错误:

Public Class Form1
    Private Sub btnFtoC_Click(sender As Object, e As EventArgs) Handles btnFtoC.Click
        Try
            Dim f As Decimal CDec(txtF.Text)
            Dim c As Decimal
            Dim txtC As String

            c = 5 / 9 * (f - 32)
            txtC.Text = CStr(c)

        Catch ex As Exception

        End Try
    End Sub
End Class

【问题讨论】:

  • Public Class Form1 Private Sub btnFtoC_Click(sender As Object, e As EventArgs) Handles btnFtoC.Click Try Dim f As Decimal CDec(txtF.Text) Dim c As Decimal Dim txtC As String c = 5 / 9 * (f - 32) txtC.Text = CStr(c) Catch ex As Exception End Try End Sub End Class
  • 您正在使用温度,因此请使用Double(科学价值)而不是Decimal(货币价值)。
  • 另外,现在学习不要写Catch ex As Exception。您应该只捕获特定的异常,这些异常是您无法通过编码摆脱的,并且您可以有意义地处理这些异常。您应该很少编写异常处理程序。太多人太频繁地使用它们,他们最终只会创建错误的代码。
  • 试试Dim f As Decimal = CDec(txtF.Text)
  • 另外,请确保在 VB.NET 中编码时拥有 Option Strict OnOption Explicit On。他们会让你成为一个更好的程序员。

标签: basic


【解决方案1】:

您已使用 Dim txtC As String 将 txtC 声明为 String,因此没有 txtC.Text。 (也许您打算填充一个文本框?)

【讨论】:

    【解决方案2】:

    我假设 txtF 和 txtC 是文本框。您需要测试 txtF 中的输入是否为有效的Decimal

    Private Sub btnFtoC_Click(sender As Object, e As EventArgs) Handles btnFtoC.Click
        Dim f As Decimal
        If Not Decimal.TryParse(txtF.Text, f) Then
            MessageBox.Show("Please enter a valid number")
            Return
        End If
        Dim c = CDec(5 / 9 * (f - 32))
        txtC.Text = CStr(c)
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 2015-06-26
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多