有没有更短的编写此代码的方法?

时间:2017-10-15 20:35:52

标签: vb.net console-application

我对编程非常陌生,目前只是搞乱控制台应用程序。我创建了一些像登录屏幕和货币转换器这样的东西,但这是在老师的帮助下。我自己从未做过任何事。

我想知道是否有更好/更短的写作方式? 模块模块1

Sub Main()
    Dim x As String
    Dim Y As String
    Dim yes As String
    Dim no As String
    x = "Please enter your name:"
    Y = "Please enter 'Y' or 'N'"
    yes = "Y"
    no = "N"
    Console.WriteLine(x)
    Console.ReadLine()
    Console.WriteLine("Do you wish to continue?")
    yes = Console.ReadLine()
    Console.WriteLine(Y)
    If yes = "Y" Then
        Console.WriteLine("You selected to continue")
    Else
        If no = "N" Then
            Console.WriteLine("You selected to exit")
            Environment.Exit(0)
        End If
    End If
    Console.WriteLine("TEXT HERE") 'Text here as I don't know what to put next yet
    Console.ReadLine()
    Console.ReadLine() 'Just put this here so it doesn't exit straight away
End Sub

我已经宣布了一些变量只是为了尝试它而不仅仅是持有Console.WriteLine(" TEXT")。我只是想找到做事的方法。 我只是再次运行代码,看到它对用户输入敏感,我怎么会让它成为Y或y和N或n?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

Sub Main()
    Console.WriteLine("Please enter your name:")
    Console.ReadLine()
    Console.WriteLine("Do you wish to continue?")

    Do
        Dim selectYN As String = Console.ReadLine()

        If selectYN.ToUpper = "Y" Then
            Console.WriteLine("You selected to continue")
            Exit Do
        ElseIf selectYN.ToUpper = "N" Then
            Console.WriteLine("You selected to exit")
            Environment.Exit(0)
            Exit Do
        Else
            Console.WriteLine("Please enter 'Y' or 'N'")
        End If
    Loop

    Console.WriteLine("TEXT HERE") 'Text here as I don't know what to put next yet
    Console.ReadLine()
    Console.ReadLine() 'Just put this here so it doesn't exit straight away
End Sub

代码比代码简化得多。我添加了一个循环,直到用户为是/否问题添加了有效答案。用户必须输入以下值之一才能打破循环:n, N, y, Y。如果该值无效,则再次出现问题,以便再次输入新值。

  

如何让它成为Y或y和N或n?

在这种情况下,您可以转换字母toLowertoUpper。在上面的示例中,toUpper用于检查NY