You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为VB控制台程序添加非数字输入的错误提示功能?

VB水温程序输入校验完善方案

原程序缺少输入校验,当输入非数字、空值时会报错,以下是添加校验后的完整代码,并附上关键逻辑说明:

完善后的代码

' 变量声明
Dim watertemp As Decimal
Dim fahren As Decimal
Dim userInput As String
Dim continueProgram As Boolean = True

' 主循环,支持多次输入
Do While continueProgram
    ' 获取并校验温度输入
    Do
        Console.ForegroundColor = ConsoleColor.White
        Console.WriteLine("请输入水温(摄氏度,范围-273.15至100):")
        userInput = Console.ReadLine().Trim()
        
        ' 校验输入:空值或非有效数字
        If String.IsNullOrEmpty(userInput) Then
            Console.ForegroundColor = ConsoleColor.Red
            Console.WriteLine("错误:输入不能为空,请重新输入!")
        ElseIf Not Decimal.TryParse(userInput, watertemp) Then
            Console.ForegroundColor = ConsoleColor.Red
            Console.WriteLine("错误:请输入有效的数字!")
        ElseIf watertemp < -273.15 Or watertemp > 100 Then
            Console.ForegroundColor = ConsoleColor.Red
            Console.WriteLine("错误:温度超出范围,请输入-273.15至100之间的数值!")
        Else
            Exit Do ' 输入有效,跳出输入校验循环
        End If
    Loop

    ' 判断水温状态并输出
    Select Case watertemp
        Case <= 0
            Console.ForegroundColor = ConsoleColor.Blue
            Console.WriteLine("水处于结冰状态")
        Case 1 To 25
            Console.ForegroundColor = ConsoleColor.Cyan
            Console.WriteLine("水是温的")
        Case 26 To 60
            Console.ForegroundColor = ConsoleColor.White
            Console.WriteLine("水是热的")
        Case 61 To 99
            Console.ForegroundColor = ConsoleColor.Magenta
            Console.WriteLine("水非常热")
        Case >= 100
            Console.ForegroundColor = ConsoleColor.Red
            Console.WriteLine("水正在沸腾")
    End Select

    ' 转换为华氏度并输出
    fahren = (9 / 5 * watertemp) + 32
    Console.WriteLine($"水温为 {Format(fahren, "0.00")} °F")

    ' 询问是否继续
    Do
        Console.ForegroundColor = ConsoleColor.White
        Console.WriteLine("是否要继续转换其他温度?(yes/no)")
        userInput = Console.ReadLine().Trim().ToLower()
        If userInput <> "yes" And userInput <> "no" Then
            Console.ForegroundColor = ConsoleColor.Red
            Console.WriteLine("错误:请输入yes或no!")
        Else
            Exit Do
        End If
    Loop

    continueProgram = (userInput = "yes")
    If Not continueProgram Then
        Console.WriteLine("程序结束")
    End If
Loop

Console.ReadLine()

关键逻辑说明

  • 输入校验:使用Decimal.TryParse方法判断输入是否能转换为十进制数,同时检查输入是否为空、是否在指定温度范围内,不符合条件则提示错误并要求重新输入。
  • 循环结构:嵌套Do...Loop循环实现「输入错误→重新输入」的逻辑,外层Do While循环支持多次温度转换。
  • 代码优化:用Select Case替代多个独立If语句,让状态判断逻辑更清晰;统一处理文本颜色,避免重复设置。
  • 二次输入校验:对用户是否继续的输入也做了校验,确保只能输入yes/no。

内容的提问来源于stack exchange,提问作者Strring

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 06:55:13