迭代器使用异常

时间:2018-10-01 19:44:09

标签: java exception

您好,即使有可以返回的字符,我的代码也会引发异常。这是我的代码

/** Return true if there is another character for the instance to return. */
    public boolean hasNext() {
        if(cursor<characterSource.length()) {
            return true;
        }
        return false;


    }

    /** Returns the next character in the String. */
    public Character next() throws NoSuchElementException {
        if(hasNext()) {
            int retVal=characterSource.indexOf(cursor);
            return characterSource.charAt(retVal);
        }
        throw new NoSuchElementException();

    }

我在做什么错了?

2 个答案:

答案 0 :(得分:3)

假设characterSourceString或兼容的东西,我认为您应该删除此行:

int retVal=characterSource.indexOf(cursor);

并调整另一个:

return characterSource.charAt(cursor++);

答案 1 :(得分:2)

将您的代码更改为此。

public boolean hasNext() {
    return cursor < characterSource.length();
}

public Character next() throws NoSuchElementException {
    if(hasNext()) {
        return characterSource.charAt(cursor++);
    }
    throw new NoSuchElementException("End of string reached");
}

cursor已经保存了当前字符的索引。没有理由致电characterSource.indexOf(cursor)