是否可以从java.util.Scanner创建一个lookAheadBuffer?

时间:2015-02-27 17:35:26

标签: java java.util.scanner

我想根据java.util.Scanner的当前状态构建一个预测缓冲区。我的意思是,如果你认为扫描仪作为传送带传送“文字”,扫描仪的“当前状态”将是传送带上剩余的文字。

我以为我可以通过构建另一个保持原始扫描仪当前状态的临时扫描程序来做到这一点。然后,我可以使用getNext()从临时扫描程序填充前瞻缓冲区,而不会影响原始扫描程序的状态。

不幸的是,没有构造函数或方法可以根据需要提供原始扫描程序的当前状态。

是否可以从扫描仪的当前状态创建外观缓冲区?

1 个答案:

答案 0 :(得分:0)

正如大多数回复明确指出的那样,Scanner没有前瞻功能。如果有人对此感兴趣,我是如何做到的。这三种方法都在名为ScannableDocument的类中。

    /**
     * Return the next word in the document.  Just a wrapper for Scanner and look ahead buffer methods.
     * The caller does not have to call hasNext().  
     * The caller does have to catch DocumentExhaustedException.
     * @return next word from scanner
     * @throws DocumentExhaustedException
     */
public String getNextWord() throws DocumentExhaustedException {

        // if the lookAheadBuffer is not empty, return its first element (fifo queue) instead of moving the scanner
        if ( !lookAheadBuffer.isEmpty()) {
            return lookAheadBuffer.removeFirst() ;
        } else {
            if ( scanner.hasNext()) {
                return scanner.next();
            } else {
                throw new DocumentExhaustedException("ScannableDocument.getNextWord()") ;
            }
        }
    }

    /**
     * Move numWords off of the conveyer.  
     * @param numWords
     * @throws DocumentExhaustedException
     */
    public void advanceConveyer ( int numWords ) throws DocumentExhaustedException {
        for ( int word=1; word<=numWords ; word++) {
            getNextWord() ;
        }
    }


    /**
     * The look ahead buffer is used to recognize patterns in the document that start with the 'current' word
     * The patterns come from a dictionary.  The look ahead buffer is loaded
     * with dictionaryEntry.size() words to enable a String comparison.

     * @param numWords
     */
    public void loadLookAheadBuffer ( int numWords )  throws DocumentExhaustedException  {

        if ( lookAheadBuffer.size() >= numWords) return ; // Already have enough words in the buffer

        for ( int i=1; i<=(numWords-lookAheadBuffer.size()) ; i++ ) {
            if ( scanner.hasNext() ) {
                lookAheadBuffer.add ( scanner.next()) ;
            } else {
                throw new DocumentExhaustedException("ScannableDocument.loadLookAheadBuffer()") ;
            }
        }
    }