2014-09-18 200 views
-1

我不知道是否有人會告訴我爲什麼我的代碼不工作。調試顯示Value可以等於1或2,但VB只會執行第一個while語句,而不會執行第二個語句。爲什麼我的While循環無法正常工作?

Const AnswerA As String = "Copenhagen" 
Const AnswerB As String = "Peter the Great" 
Dim Value As Integer 
Dim Message, Response As String 
Private Sub btnAskMe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAskMe.Click 
    Randomize() 
    ' Generate random value between 1 and 2 to test only. 
    Value = CInt(Int((2 * Rnd()) + 1)) 
    If Value = 1 Then 
     Message = "What's the capital of Denmark?" 
     While Response <> AnswerA 
      Response = InputBox(Message) 
      If String.IsNullOrEmpty(Response) Then Exit Sub 
      If Response <> AnswerA Then Message = "No, no, no! Think boy, think?" 
     End While 
     MsgBox("Correct....What took you so long?") 
    End If 
    If Value = 2 Then 
     Message = "Which Russian Tsar forced his wife to keep her lovers head in a jar?" 
     While Response <> AnswerB 
      Response = InputBox(Message) 
      If String.IsNullOrEmpty(Response) Then Exit Sub 
      If Response <> AnswerB Then Message = "No you twerp! Have another go" 
     End While 
     MsgBox("Correct....What took you so long?") 
    End If 
End Sub 

末級

+4

完成** **任何基本調試,如檢查,如果你的函數實際上是叫什麼名字?檢查'Value'中的值是什麼?而你究竟如何期望你的'Value = 2'代碼運行ince你有一個'Exit Sub'就在它上面? – 2014-09-18 20:39:01

+0

感謝您的回覆。我添加了Exit Sub,因爲我不希望VB在第一個問題得到正確回答後運行腳本的其餘部分。我的希望是,如果發電機產生了2個,那麼第二個問題就會顯示出來。我是VB新手,所以我的調試技巧是有限的,儘管我已經嘗試了Step Into。 – RickTicky 2014-09-18 21:14:24

+0

Step Into顯示Value可以= 1或= 2,但代碼將只運行第一個While響應。即使值爲2,它也不會跳到第二位。我希望您提供任何進一步的建議。 – RickTicky 2014-09-18 21:33:40

回答

1

同一個問題你 「結束時,如果」 位置 這裏

If Value = 1 Then 
     Message = "What's the capital of Denmark?" 
    End If 

這裏

If Value = 2 Then 
     Message = "Which Russian Tsar forced his wife to keep her lovers head in a jar?" 
    End If 

如果需要 來後的第一端「退出子」行 和第二個之後 「結束而」

+0

同意,把結束如果出口後小組似乎是很好的意義。但是,當我嘗試這樣做時,我的第一條Else語句會得到一條虛線,而VB想讓我添加一個End IF。同時,如果我按照建議移動了End IF,也會得到一條擺動線,因爲它需要從一個IF開始。有任何想法嗎? – RickTicky 2014-09-18 21:18:26

+0

我很難檢查你的代碼。它不會在ms access 2003上編譯,它使用一個稍微不同的視覺基本方言。爲了標記一個while循環的結束,它使用「end」而不是「end while」像你的那樣。但我的建議是將這兩個問題放在同一個while循環中,簡化代碼並擺脫end子,然後可以使用「continue while」insead的「exit sub」。「continue while」跳過其餘代碼當前迭代的循環並從新的迭代開始,所以它在這裏會有類似的效果。祝你好運! – 2014-09-18 22:34:16

+0

@RickTicky - 建議你改稱'叫我胡蘿蔔'不應該產生你描述的錯誤。你確定你移動了'End If'語句而不是僅僅複製它?你確定你移動了正確的「End If」語句嗎?你能顯示你的更新代碼嗎? – 2014-09-19 13:52:07

0

它永遠不會正常工作:

While ResponseB <> AnswerB 
        ^----check Response **B** 
     ResponseA = InputBox(Message) 
       ^---- get a response into Response **A** 
+0

啊,很好看。非常感謝馬克!這當然沒有幫助。我只是希望我知道爲什麼代碼在第一時間卡住,並且從未進展到第二個,即使值爲2 – RickTicky 2014-09-18 21:56:16