我正在爲我的計算機科學課進行測驗,基本概念是您有15個關鍵字和15個定義。所有需要隨機顯示,並出現正確的答案。用戶必須將正確的定義與關鍵字匹配兩次,然後該關鍵字和定義纔會再次顯示。當所有人都回答了兩次測驗結束後。在我的代碼中導致這個錯誤的原因是什麼?
我已將我的關鍵字和我的定義存儲在同一個文件中,以免它們不同步。文本文件看起來像這樣:
Keyword1,Definition1
Keyword2,Definition2
Keyword3,Definition3
...
我得到的問題是在我的代碼中有兩行。首先,我將參考所有相關的代碼,使我所要求的儘可能清楚。我創建了一個類Answer
和看起來像這樣:
Public Class Answer
Public Answer As String
Public Answered As Boolean
End Class
我的主要形式form1
看起來是這樣的:
Public Class Form1
Const NUMBER_OF_ANSWERS As Integer = 3
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
kv = New Dictionary(Of String, Answer)
For Each line As String In IO.File.ReadAllLines("C:\Users\Matt\Documents\keywords.txt")
Dim parts() As String = line.Split(",")
kv.Add(parts(0), New Answer With {.Answer = parts(1), .Answered = False})
Next
Dim r As New Random
Dim kvRandom As List(Of KeyValuePair(Of String, String)) =
kv.OrderBy(Function() r.Next).ToList
'questions will appear in random order
For Each line As KeyValuePair(Of String, String) In kvRandom
Dim keyword As String = line.Key
Dim correctDefinition As String = line.Value
Dim keywords As New List(Of String)
keywords.Add(keyword)
keywords.AddRange(kv.Keys.Except({keyword}).
OrderBy(Function() r.Next).Take(NUMBER_OF_ANSWERS - 1))
Dim definitionsRandom As List(Of String) =
keywords.Select(Function(x) kv(x)).OrderBy(Function() r.Next).ToList
LabelKeyword.Text = keyword
RadioButtonDef1.Text = definitionsRandom(0)
RadioButtonDef2.Text = definitionsRandom(1)
RadioButtonDef3.Text = definitionsRandom(2)
Next
End Sub
我的錯誤是在以下兩行:
kv.OrderBy(Function() r.Next).ToList
即:
Error 1 Value of type 'System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of String, flashquiz.Answer))' cannot be converted to 'System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of String, String))'. C:\Users\Matt\Desktop\flashquiz\flashquiz\Form1.vb 62 11 flashquiz
and
keywords.Select(Function(x) kv(x)).OrderBy(Function() r.Next).ToList
是:
Error 2 Value of type 'System.Collections.Generic.List(Of flashquiz.Answer)' cannot be converted to 'System.Collections.Generic.List(Of String)'. C:\Users\Matt\Desktop\flashquiz\flashquiz\Form1.vb 75 15 flashquiz
我不知道什麼是錯的,所以任何幫助將不勝感激。 我知道這是關於Answer類,但不完全是。
謝謝修復該行,但我似乎仍然與另一個問題:'kv.OrderBy(Function()r.Next).ToList'我該如何解決這一問題? –
糟糕。錯過了那部分。我更新了我的答案 –