我为了找到一个程序中的关键字例如"public"等有多少个,写了下面这段代码:
      
      int countItems=1;  
      try  
{
 BufferedReader inputS = new BufferedReader(new FileReader(fileName));
 String line = "";
 line = inputS.readLine();
 StringTokenizer secondWordFinder = 
 new StringTokenizer(line," \t\n");
 while(secondWordFinder.hasMoreTokens())
  {
  if(secondWordFinder.nextToken().equals("public")||
  secondWordFinder.nextToken().equals("private"))
  countItems++;
  }
   
  inputS.close();
} catch(FileNotFoundException e)
 {
 System.out.println("File "+ fileName +" was not found");
 }
 catch(IOException e)
 {
 System.out.println("Erroe reading form file " +fileName );
 }编译通过,也可以执行,但是计数器countItem的值始终是1,望指教

解决方案 »

  1.   

    int countItems=1;  
          try  
    {
     BufferedReader inputS = new BufferedReader(new FileReader(fileName));
     String line = "";
     while(line = inputS.readLine()!=null){
     StringTokenizer secondWordFinder = 
     new StringTokenizer(line," \t\n");
     while(secondWordFinder.hasMoreTokens())
      {
      if(secondWordFinder.nextToken().equals("public")||
      secondWordFinder.nextToken().equals("private"))
      countItems++;
      }
      }
       
      inputS.close();
    } catch(FileNotFoundException e)
     {
     System.out.println("File "+ fileName +" was not found");
     }
     catch(IOException e)
     {
     System.out.println("Erroe reading form file " +fileName );
     }
      

  2.   

    楼上 如果String不相等能用!=表示么?
    我用你的程序编译了,但是编译报错:incompatible types
      

  3.   

    while(line = inputS.readLine()!=null){
    改为
    while((line = inputS.readLine())!=null){
      

  4.   

    package temp;import java.lang.String;
    import java.util.StringTokenizer;
    import java.io.*;public class Test {
    private static int i = 0; public Test() {
    i++;
    } public static int getNum() {
    return i;
    } public static void main(String[] args) {
    int countItems = 0;
    String fileName = "FileTest.java";
    try {
    BufferedReader inputS = new BufferedReader(new FileReader(fileName));
    String line = "";
    while ((line = inputS.readLine()) != null) {
    StringTokenizer secondWordFinder = new StringTokenizer(line,
    " \t\n");
    while (secondWordFinder.hasMoreTokens()) {
    String str=secondWordFinder.nextToken();
    if (str.equals("public")
    || str.equals("private"))
    countItems++;
    }

    }
    System.out.println("结果:" + countItems);
    inputS.close();
    } catch (FileNotFoundException e) {
    System.out.println("File " + fileName + " was not found"+":"+e.getMessage());
    } catch (IOException e) {
    System.out.println("Erroe reading form file " + fileName+":"+e.getMessage());
    } }}
    补上,呵呵