So i am creating a class for “MiniString” which is just full of instance methods for the object MiniString, every MiniString has an instance variable that is a char[]. When testing my methods, I can’t find where I am going wrong with my substring() method. There are two substring methods where one takes a parameter of int and the other takes two int parameters. I keep getting the error on the one int parameter method. The substring method is supposed to return a new MiniString formed of the characters between the position in the target Ministring specified by the int parameter, and the end of the target MiniString. The error I keep getting in my JUnit Tester is the following:
java.lang.ArrayOutofBoundsException:22
at MiniString.substring(MiniString.java:141)
at MiniString.substring(MiniString.java:159)
Here are my constructors for the object MiniString:
private char[] miniscule;
MiniString(char[] array){
int i = 0;
miniscule = new char[array.length];
while (i < array.length){
miniscule[i] = array[i];
i++;
}
}
MiniString(String string){
int i = 0;
miniscule = new char[string.length()];
while (i < string.length()){
this.miniscule[i] = string.charAt(i);
i++;
}
}
and here is the code for the two substring() methods:
public MiniString substring(int start, int end){
int i = start;
if (end > start){
char[] temp = new char[end - start];
MiniString range = new MiniString(temp);
while (i < end){
range.miniscule[i] = this.miniscule[i];
i++;
}
return range;
}
else{
char[] temp = new char[1];
MiniString range = new MiniString(temp);
range.miniscule[0] = 0;
return range;
}
}
public MiniString substring(int position){
int start = position;
int end = this.miniscule.length;
char[] temp = new char[end - start];
MiniString output = new MiniString(temp);
output = substring(start, end);
return output;
}
Thanks for your help!
In your first
substringmethod, the lineis the most likely suspect. I expect you really want
Stringhas substring methods that do approximately what you’re doing here, but I presume you’re doing this to learn, rather than reinventing string handling for a production use.If you’re using Java 6, you might also want to look at the
Arrays.copyOfRange(T[] ts, int i, int i1)method, which does most of the work you’re doing in yoursubstringmethods.