2011-03-11 172 views
1
// Calculating term frequency 
    System.out.println("Please enter the required word :"); 
    Scanner scan = new Scanner(System.in); 
    String word = scan.nextLine(); 

    String[] array = word.split(" "); 
    int filename = 11; 
    String[] fileName = new String[filename]; 
    int a = 0; 



    for (a = 0; a < filename; a++) { 

     try { 
      System.out.println("The word inputted is " + word); 
      File file = new File(
        "C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a 
          + ".txt"); 
      System.out.println(" _________________"); 

      System.out.print("| File = abc" + a + ".txt | \t\t \n"); 

      for (int i = 0; i < array.length; i++) { 

       int totalCount = 0; 
       int wordCount = 0; 

       Scanner s = new Scanner(file); 
       { 
        while (s.hasNext()) { 
         totalCount++; 
         if (s.next().equals(array[i])) 
          wordCount++; 

        } 

        System.out.print(array[i] + " ---> Word count = " 
          + "\t\t " + "|" + wordCount + "|"); 
        System.out.print(" Total count = " + "\t\t " + "|" 
          + totalCount + "|"); 
        System.out.printf(" Term Frequency = | %8.4f |", 
          (double) wordCount/totalCount); 

        System.out.println("\t "); 

       } 
      } 
     } catch (FileNotFoundException e) { 
      System.out.println("File is not found"); 

     } 

    } 

這是我的代碼,用於計算包含文本的文本文件的字數,總詞數和詞頻。問題是我需要訪問for循環之外的變量wordcount和totalcount。但改變地方聲明變量wordcount和totalcount也會改變結果,使其不準確。有人可以幫我處理變量,這樣我可以得到準確的結果,並且還可以訪問for循環之外的變量嗎?變量範圍問題

回答

1

簡單地將它們聲明外循環,但要賦予它們以0內環路:

  int totalCount; 
      int wordCount; 
      for (...) {     
       totalCount = 0; 
       wordCount = 0; 
       ... 
      } 
      // some code which uses totalCount and wordCount