-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

感谢您的解答。,问题解决了 –