public String nextParagraph ( int totalSentences ) { StringBuilder out = new StringBuilder ( ) ; List < String > lastWords = new ArrayList < String > ( ) ; lastWords . add ( null ) ; lastWords . add ( null ) ; int numSentences = 0 ; boolean inSentence = false ; boolean inQuote = false ; while ( numSentences < totalSentences ) { List < String > words = pairTable . get ( lastWords ) ; if ( words == null ) { // no hit for the digram, try just the last word words = singleWordTable . get ( lastWords . get ( 1 ) ) ; } if ( words == null ) { // hit end of paragraph pair, nothing directly following. start again words = pairTable . get ( Arrays . < String > asList ( null , null ) ) ; } String nextWord = words . get ( random . nextInt ( words . size ( ) ) ) ; if ( nextWord . length ( ) == 1 && sentenceEndChars . indexOf ( nextWord . charAt ( 0 ) ) != - 1 ) { out . append ( nextWord ) ; if ( inQuote ) { out . append ( ' ' ) ; } numSentences ++ ; inSentence = false ; inQuote = false ; lastWords . remove ( 0 ) ; lastWords . add ( null ) ; // look up } else { if ( ! inSentence ) { // start a new sentence if ( out . length ( ) > 0 ) { out . append ( " " ) ; } inSentence = true ; } else { // need a word separator out . append ( " " ) ; } out . append ( nextWord ) ; if ( nextWord . indexOf ( ' ' ) != - 1 ) { inQuote = true ; } } lastWords . remove ( 0 ) ; lastWords . add ( nextWord ) ; } return out . toString ( ) ; }
Returns a paragraph of text with the given number of sentences .