-2

注意:請不要說使用String類方法,因爲我在這裏創建了所有的String方法。Java:創建一個String類:ArrayIndexOutOfBoundsException

目標:考慮兩個字符串王子和soni。我想要computeConcate方法請求位置(說4進入),然後從名字開始到第4個位置獲取字符串,並將其與姓氏即soniz連接起來。因此我prinsoni

錯誤:在線路ArrayIndexOutOfBondsException內computeConcate標有作爲錯誤()方法

原因的錯誤的:如此獲得(姓氏和名字的即級聯的字符串可以是第一+的atmost長度的姓)

所以我創建的String

char []firstSubString; 
    firstSubString = new char[so.computeLength(firstName) + so.computeLength(lastName)]; 

其現在的長度,因爲我雖然姓和名的總和,但這種方法computeSubstring()後,它改變名字的長度。

我想要什麼?

您能否提供一種方法讓computeSubstring不會最終改變firstSubString的長度 。

/** 
* Take two strings 
* Run a loop pause when counter is encountered 
* Now use + to concatenate them 
**/ 
@Override 
public char[] computeConcatenation(char[] firstName, char[] lastName, int pos) { 
    StringClass so = new StringClass(); 
    Boolean flag = false; 
    char []firstSubString; 
    firstSubString = new char[so.computeLength(firstName) + so.computeLength(lastName)]; 

    System.out.println(firstSubString.length); // O/p is 10 (length of           //             first name + last name 

    firstSubString = so.computeSubstring(firstName, pos); 

    System.out.println(firstSubString.length); // o/p is 6. length of       //             first name 

    int len = so.computeLength(firstSubString); 

    // To find pos 
    for(int i = 0; i < so.computeLength(lastName); i++){ 

     // ArrayIndexOfOfBondsException on this line 
Error : firstSubString[len + i] = lastName[i]; 
    } 
    return firstSubString; 
} 



Here is the code for substring method 

/** 
* Traverse the string till pos. Store this string into a new string 
*/ 
@Override 
public char[] computeSubstring(char[] name, int pos) { 
    StringClass so = new StringClass(); 
    char []newName; 
    newName = new char[so.computeLength(name)]; 



     for(int i = 0; i < so.computeLength(name); i++){ 
     if(i == pos) break; 
     newName[i] = name[i]; 
    } 
    return newName; 
} 
+1

您應該編寫一個實用程序/測試方法,它將您的參數並將其轉儲爲標準輸出。只要編寫這個方法可能會告訴你錯誤在哪裏。 – jdv

+0

@GiovanniBotta Codereview僅適用於**工作代碼**。破碎的代碼在那裏是無關緊要的。 –

+0

@jdv我已經解釋過,編寫一個測試方法就是後面的話題,只要我找出這個長度問題的變化。 現在的問題是,爲什麼在使用computeSubString方法後,地獄firstSubString長度發生了變化,以及如何防止它發生更改。 –

回答

1

那麼,它的變化,因爲你在這裏覆蓋firstSubString

firstSubString = so.computeSubstring(firstName, pos); 

你想要做什麼;然而,將computeString的結果複製到的第一部分firstSubString。你可以用System.arraycopy()

char[] result = so.computeSubstring(firstName, pos); 
System.arraycopy(result, 0, firstSubstring, 0, result.length); 

這做到這一點,而只是將結果複製到firstSubstring的前面。這根本不會改變它的長度。

+0

感謝您的解答。,問題解決了 –