【问题标题】:Trouble understanding how to emulate String.substring method无法理解如何模拟 String.substring 方法
【发布时间】: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


【解决方案1】:

substring 方法中,t 被创建为长度为 0 (char[] t = {};) 的空数组。只需更改此声明以匹配结果字符串 char[] t = new char[end - begin]; 的大小(如果 end 是独占的)。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2022-01-23
    • 2020-09-11
    • 2019-01-30
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多