StreamTokenizer (流標記) 示例
阿新 • • 發佈:2019-02-09
字元,ttype包含該字元的值。如果遇到一個行結束情況,ttype等於TT_EOL(這假定了引數為true呼叫eolIsSignificant())。如果遇到流的結尾,ttype 等於TT_EOF。
*///Enhanced word count program that uses a StreamTokenizer.
import java.io.*;
class STWordCount{
public static int intWords = 0;
public static int intLines = 0;
public static int intChars = 0;
public static void wc(Reader r) throws IOException{
StreamTokenizer tok = new StreamTokenizer(r);
tok.resetSyntax();
tok.wordChars(33,255);
tok.whitespaceChars(0,' ');
tok.eolIsSignificant(true);
while(tok.nextToken() != tok.TT_EOF){
switch(tok.ttype){
case tok.TT_EOL: //不知道為什麼會報錯
intLines++;
intChars++;
break;
case tok.TT_WORD: //不知道為什麼會報錯
intWords++;
default:
intChars += tok.sval.length();
}
}
}
public static void main(String[] args)
{
if(args.length == 0){
try{
wc(new InputStreamReader(System.in));
System.out.println(intLines + " " + intWords + " " + intChars);
}catch(IOException e){
}
}else{
int tWords = 0,tLines = 0,tChars = 0;
for(int i =0;i<args.length;i++){
try{
intWords = intLines = intChars = 0;
wc(new FileReader(args[i]));
tWords += intWords;
tLines += intLines;
tChars += intChars;
System.out.println(args[i] + ": " +intLines+ " " + intWords + " " + intChars);
}catch(IOException e){
System.out.println(args[i] +":error.");
}
}
System.out.println("Total :" +tLines+ " " + tWords + " " + tChars);
}
}
}