【发布时间】:2015-08-02 11:14:21
【问题描述】:
我必须创建一个自定义类 MyString,它模拟 String 类包含的某些方法,基本上就像一个字符串。唯一的问题是,我不能使用字符串类中的任何东西,只能使用一种方法中的构造函数。
我遇到的问题是让 substring 方法正常工作。我不断收到 arrayoutofbound 异常。我也不确定如何比较两个 MyString 对象。
package hw;
import java.lang.reflect.Array;
import java.util.Scanner;
import java.util.Arrays;
public class MyString {
private final char[] chars;
private final int index;
Scanner sc = new Scanner(System.in);
public MyString(char[] chars) {
this.chars = chars;
this.index = Array.getLength(chars);
}
//this is my trouble method
public MyString substring(int begin, int end) throws Exception{
char[] t = {};
int n = 0;
if(end > index){
throw new Exception();
}
if(begin < 0){
throw new Exception();
}
if(begin > end){
throw new Exception();
}
for(int i=begin-1;i < end;i++){
t[n] = this.chars[i];
n++;
System.out.print(t[n]);
}
System.out.println(t);
MyString myTemp = new MyString(t);
return myTemp;
}
//im not sure how to compare the two
public boolean equals(MyString s){
char [] tempA = this.chars;
char [] tempB = s.chars;
return true;
}
/*
public static MyString valueOf(int i){
Mystring string;
return MyString;
}
*/
}
【问题讨论】:
-
你知道 ArrayIndexOutOfBoundsException 是什么意思吗?
-
请删除解决您的问题不需要的所有代码。这尤其包括除
substring()之外的大多数其他类方法。 -
@TimoSta 好的,删除了一堆,抱歉。
标签: java arrays exception char substring