我如何创建一个反转给定字符串的迭代器?

时间:2018-06-11 22:04:39

标签: java

我正在尝试在Java中创建一个“Reverse Iterator”,它接受一个字符串并以相反的顺序输出每个字符串。这是我现在的代码:

//a b c d -> d c b a
class ReverseIterator implements Iterator<String> {
  String given;
  int index;
  ReverseIterator(String given) {
    this.given = given;
    this.index = 0;
  }

  // is there a next?
  public boolean hasNext() {
    return this.index <= this.given.length();
  }

  // gets the next item
  // effect: advances the index by one
  public String next() {
    String answer = this.given.substring(given.length() - this.index, given.length() - this.index - 1);
    this.index = index + 1;
    return answer;
  }
}

我收到了String index out of range: -1,但我不确定如何解决我的算法问题。

2 个答案:

答案 0 :(得分:1)

所以有两件事是错的。

当您到达最后一个字符时,第一个return this.index <= this.given.length();会产生错误,因为String为零索引,即0length - 1

第二

this.given.substring(given.length() - this.index, given.length() - this.index - 1);

生成一个索引范围,其中endIndex小于beginIndex(因此错误String index out of range: -1

因此,如果index为5,则您尝试从5开始到4结束的子字符串,这是无效的。你想要转换那些,更像是......

public String next() {
    int from = given.length() - this.index - 1;
    int to = given.length() - this.index;
    String answer = this.given.substring(from, to);
    this.index = index + 1;
    return answer;
}

大部分内容都是通过一系列System.out.println语句进行调试的,当你开始遇到这样的问题时,你需要花时间把变量分解出来(就像我上面做的那样)非常重要并检查实际值,这对于突出我们所犯的愚蠢错误非常有帮助

哦,我也同意String#charAt似乎更有意义

答案 1 :(得分:1)

你在substring方法中的参数混淆了,这导致了异常:

对于长度为5的给定字符串,您希望从索引5到4访问子字符串,这是不可能的。

如果更改参数,则next()方法将最后一个char作为字符串返回。

现在你必须在你的代码中添加hasNext()方法和循环,你应该好好去。

相关问题