2012-05-09 40 views
-3

我的C#程序出現問題:我創建了一個包含10個問題和10個圖像的測驗。 我得到這個Length cannot be less than zero.\r\nParameter name: length在該行c#error:長度不能小於0

int imageIndex = int.Parse(line.Substring(0, delimiter)); 

即使在我的記事本文件,我包括在該圖像索引:

3:What is the foo in the bar? 
10:How can you add a widget? 
4:Why pick a bar over a foo? 

下面是代碼:

if (nr >= questions.Count) 
{ 
    button1.Enabled = false; 
} 
else 
{ 
    Random r = new Random(); 
    int x; 
    do 
    { 
     x = r.Next(questions.Count); 
    } 
    while (questions[x].displayed == true); 

    textBox1.Text = questionText; 
    radioButton1.Text = questions[x].answer1; 
    radioButton2.Text = questions[x].answer2; 
    questions[x].displayed= true; 
    current_question = x; 
} 
+0

調用'Substring'時'delimiter'的值是多少? –

+0

什麼??????????? –

+0

什麼是分隔符? – Tilak

回答

1

子串的參數是初始索引和長度。代碼中的分隔符看起來不像長度。

http://msdn.microsoft.com/en-us/library/aka44szs.aspx

更改以下

int delimiter = line.IndexOf(':'); 
int imageIndex = int.Parse(line.Substring(0, delimiter)); 
string questionText=line.Substring(delimiter + 1); 
pictureBox1.Image = imageList1.Images[imageIndex]; 

textBox1.Text = questionText; 
radioButton1.Text = questions[x].answer1; 
questions[x].displayed= true; 
current_question = x; 

int delimiter = line.IndexOf(':'); 
if(!String.IsNullOrEmpty(line) && delimiter > 0) 
    { 
     int imageIndex = int.Parse(line.Substring(0, delimiter)); 
     string questionText=line.Substring(delimiter + 1); 
     pictureBox1.Image = imageList1.Images[imageIndex]; 

     textBox1.Text = questionText; 
     radioButton1.Text = questions[x].answer1; 
     questions[x].displayed= true; 
     current_question = x; 
    } 
5

你之前已經有這樣一行:

int delimiter = line.IndexOf(':'); 

...但你那麼不是檢查返回值。如果它是-1,那意味着您的分隔符在該特定行中找不到 - 但是您仍然將它傳遞到Substring。在使用它之前請檢查delimiter的值 - 這樣您可以拋出更有用的異常(或跳過該行或您想要執行的任何操作)。

我實際上建議你明顯改變你的代碼 - 而不是保留questions作爲List<string>或其他任何東西,我會創建一個Question類。在閱讀文本時解析文本行,在那個時候拋棄失敗 - 或拋出異常 - 而不是等到碰到壞的問題。然後你可以有一個List<Question>這將使其餘的代碼更簡單。

你可能想保留一個Queue<Question>它最初是一個完整列表的副本,洗牌。當你想顯示一個新問題時,只需從該隊列中取下一個元素。這樣,當你挑選已經顯示的問題時,你不需要循環。 (你要包括Question的類內的IndexQuestionNumber財產,想必......)

請注意,這是可能的,它的工作對所有你真的知道的線,但已在文件末尾有一些空行。你可能只想跳過空行。

0
private string copystring(string instr ,int start ,int length) 
{ 
    return instr.Length >= (start + 1) 
     ? (instr.Length > (start + length) ? instr.Substring(start, length) : instr.Substring(start,instr.Length-start)) 
     : ""; 
} 
相關問題