2017-10-15 114 views
0

我對編程非常陌生,目前只是搞亂了控制檯應用程序。我創造了一些東西,例如登錄屏幕和貨幣轉換器,但是這是在老師的幫助下完成的。從來沒有做過任何事情。有沒有更短的寫這段代碼的方法?

我想知道是否有更好/更短的寫作方式? 模塊模塊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(「文本」)不斷。我只是想找到辦法。 我剛剛再次運行了代碼,發現它對用戶輸入區分大小寫,我該如何處理它是Y還是Y和N或n?

+0

我投票結束這個問題作爲題外話,因爲它要求審查。請參閱https://www.codereview.stackexchange.com – Codexer

回答

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

相關問題