(Visual Basic 控制台模式)检查从 1 到 7 的数字并打印某些输出?



问题:请求用户输入从1到7的数字。如果数字为 1 到 5。如果输出"工作日",则输出 6 或 7,则输出"周末"。否则显示错误。

这就是我试图做的。

Imports System
Module Program
Dim num1 As Integer
Sub Main()
Console.WriteLine("Enter a number from 1 to 7")
num1 = Console.ReadLine
If num1 = 1 Or 2 Or 3 Or 4 Or 5 Then
Console.Write("It is a school day")
ElseIf num1 = 6 Or 7 Then
Console.WriteLine("It is the weekend")
Else
Console.WriteLine("Beep! error, enter number from 1 to 7")
End If
Console.ReadKey()
End Sub
End Module

我认为错误在于如果 num1 = 1 或 2 或 3...这句话的正确表达方式是什么? 谢谢

你的怀疑是正确的。 问题出在您的or语法上。 正确的语法是

If num1 = 1 Or num1 = 2 Or num1 = 3 Or num1 = 4 Or num1 = 5 Then
Console.Write("It is a school day")
ElseIf num1 = 6 Or num1 = 7 Then
Console.WriteLine("It is the weekend")
Else
Console.WriteLine("Beep! error, enter number from 1 to 7")
End If

当然,如果您使用Select Case语句,它会更简单。

Select Case num1 
Case 1, 2, 3, 4, 5:
Console.Write("It is a school day")
Case 6, 7:
Console.WriteLine("It is the weekend")
Case Else
Console.WriteLine("Beep! error, enter number from 1 to 7")
End Select

请打开选项严格。这是一个由两部分组成的过程。当前项目的第一个 - 在"解决方案资源管理器"中,双击"我的项目"。选择左侧的"编译"。在"选项严格"下拉列表中,选择"开"。第二个是未来的项目 - 转到工具菜单 ->选项 ->项目和解决方案 -> VB 默认值。在"选项严格"下拉列表中,选择"开"。这将使您在运行时免于错误。

Console.ReadLine 返回一个字符串。因此,它不能直接分配给整数。首先,我们检查是否输入了数字。如果它不是一个数字,我们就无法将其与其他数字进行比较。如果输入是数字,则 Integer.TryParse 返回 True,并用数字填充第二个参数。

Sub Main()
Dim input As String
Dim num1 As Integer
Do
Console.WriteLine("Enter a number from 1 to 7")
input = Console.ReadLine
Loop Until Integer.TryParse(input, num1)
Select Case num1
Case 1, 2, 3, 4, 5
Console.WriteLine("It is a school day")
Case 6, 7
Console.WriteLine("It is the weekend")
Case Else
Beep()
Console.WriteLine("Error, you didn't enter a number from 1 to 7")
End Select
Console.ReadKey()
End Sub

最新更新