StreamTokenizer除法运算符“/”的行为

时间:2015-04-24 12:01:46

标签: java string eof stringreader

查看StreamTokenizer SlidingTabStrip.java的演示代码。当字符串中有/时,它似乎无法正常工作(只需在/中的字符串之间添加StringReader)。这是来自上述链接的代码,

StreamTokenizer tokenizer = new StreamTokenizer(
    new StringReader("Mary had 1 little lamb..."));

    while(tokenizer.nextToken() != StreamTokenizer.TT_EOF){

        if(tokenizer.ttype == StreamTokenizer.TT_WORD) {
            System.out.println(tokenizer.sval);
        } else if(tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
            System.out.println(tokenizer.nval);
        } else if(tokenizer.ttype == StreamTokenizer.TT_EOL) {
            System.out.println();
        }
    }

例如,对于字符串"Mary had 1 little lamb...",输出为

Mary
had
1.0
little
lamb...

对于字符串"Mary had 1 /little lamb...",输出为

Mary
had
1.0
  • /是否可以作为EOF令牌?如果是这样,为什么?
  • 有没有办法将/区分为EOF以外的其他令牌。

2 个答案:

答案 0 :(得分:3)

根据the documentation/StreamTokenizer中的评论字符。在它之后的所有内容,直到EOL或EOF将被忽略,并且不会被标记化。

例如,要继续您给出的示例,如果字符串为"Mary had 1 / 2\n little lamb..."2将被注释掉并且不会被标记化,并且标记化将在{{1}之后恢复}。所以输出将是:

\n

答案 1 :(得分:1)

只是添加到上面的答案 。因为/是StreamTokenizer中的注释字符并一直持续到行尾。因此,您必须在String中添加新行\n\r 所以"Mary had 1 / \n little /\nlamb...""Mary had 1 / \r little/\rlamb..."两者都适合你