2013-06-18 40 views
1

我已經做了這段代碼,而試圖拆分一個字符串分成2個部分,我將保存到數據庫後。現在我已經成功地將3個單詞字符串像「單詞字符編號」一樣分成3個字段,但是當我試圖將只有1個單詞的字符串和像「單詞編號」一樣的字符串分成2個字段時,我得到了我無法理解的錯誤消息。嘗試拆分字符串沒有成功

procedure Split 
    (const Delimiter: Char; 
    Input: string; 
    const Strings: TStrings) ; 
begin 
    Assert(Assigned(Strings)) ; 
    Strings.Clear; 
    Strings.Delimiter := Delimiter; 
    Strings.DelimitedText := Input; 
end; 

procedure TForm2.Button64Click(Sender: TObject); 
var 
    A: TStringList; i,c:integer; 
begin 
c:=0; 
//for i:= 0 to ListBox1.Items.Count do 
//begin 
    A := TStringList.Create; 
// try 
    // Split(' ',listbox1.Items.Strings[0], A) ; 
    Split(' ',ListBox1.Items.Strings[ListBox1.ItemIndex], A) ; 
    // finally 
    // A.Free; 
    for i := 48 to 57 do 
if A[1]<>char(i) then 
    c:=1 
else 
if A[1]=char(i) then 
    c:=2; 

if c=1 then 
begin 
    edit81.Text:=(A[0]+' '+A[1]); 
    edit82.Text:=A[2]; 
end 
else 
if c=2 then 
begin 
    edit81.Text:=A[0]; 
    edit82.Text:=A[1]; 
end; 
end; 

的錯誤信息是:

First chance exception at $7C812FD3. Exception class EStringListError with message 'List index out of bounds (2)'. Process paligs.exe (732) 

林試圖從字符串中的所有單詞edit81領域和數字編輯82場。

我的形象從形式:http://i.stack.imgur.com/7vnS8.jpg

+1

現在是時候開始給您的控件比'edit82'更好的名字了。和時間開始縮進你的代碼。 –

回答

9

讓你在這裏學習的是如何解釋,編譯器產生的錯誤信息的最重要的事情。有時他們沒有那麼多幫助,但在這種情況下,這些信息告訴你所有你需要知道的信息。

的錯誤信息是:

List index out of bounds (2) 

這意味着要訪問的列表中的元件2和元件2不存在。這意味着該列表有一個0或1的可能性。當您編寫A[2]時,該列表引發異常,因爲A[2]不存在。

這完全是可以預料的。如果拆分'word number'那麼結果是:

A[0] = 'word' 
A[1] = 'number' 

並沒有元素索引2.

,你的代碼訪問A[2]可以在這裏找到了原因:

對於i:= 48如果A [1] = char(i),則 c:= 2;如果A [1] <> char(i)then c:= 1 else

顯然'number'是從未等於char(i)用於i任何值等設定c1。然後導致這個代碼執行:

if c=1 then 
begin 
    edit81.Text:=(A[0]+' '+A[1]); 
    edit82.Text:=A[2]; // BOOM! 
end 
+0

@Rolands你讀過這個答案了嗎?它有幫助嗎? –