注意:請不要說使用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;
}
您應該編寫一個實用程序/測試方法,它將您的參數並將其轉儲爲標準輸出。只要編寫這個方法可能會告訴你錯誤在哪裏。 – jdv
@GiovanniBotta Codereview僅適用於**工作代碼**。破碎的代碼在那裏是無關緊要的。 –
@jdv我已經解釋過,編寫一個測試方法就是後面的話題,只要我找出這個長度問題的變化。 現在的問題是,爲什麼在使用computeSubString方法後,地獄firstSubString長度發生了變化,以及如何防止它發生更改。 –