StreamTokenizer (流標記) 樣本

來源:互聯網
上載者:User

/*

wordChars( )方法用來指定可以用於字的字元範圍。它的通常形式如下:

void wordChars(int start, int end)這裡,start和end指定了有效字元的範圍。程式中,從33到255範圍內的字元都是有效字元。空格符由 whitespaceChars( )說明。它的一般形式如下:void whitespaceChars(int start, int end)這裡,start和end指定了有效空格符的範圍。下一個標記通過調用nextToken( )從輸入資料流獲得,它返回標記的類型。StreamTokenizer定義個四個int型常量:TT_EOF,TT_EOL,TT_NUMBER和TT_WORD。有三個執行個體變數。nval是一個公開的double 型變數,用來儲存可識別的字數的值。sval是一個public String 型變數,用來儲存可識別的的字的值。ttype是一個int型變數,說明剛剛被nextToken( )方法讀取的標記的類型。如果標記是一個字,ttype等於TT_WORD。如果標記為一個數,ttype等於TT_NUMBER。如果標記是單一字元,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);
  }
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.