2016-10-28 139 views
0

我被困在一個很長時間的問題上,這需要我計算一個術語x術語矩陣。所以,我有2個陣列是關鍵字句子如下:計算術語x術語矩陣

String[] Keywords = {"Human", "Machine", "Interface", "Application" }; 
String[] Sentence = {"Human is Machine", "Interface of Robot", "Application on Human"}; 

接下來,我要他們製表如下圖所示的圖。

Result in 2D array

邏輯:

  1. 我們把一個0,如果行和列是相同的關鍵字。
  2. 在人類(行)×機器(列)空間中,我們放1個,因爲這兩個 單詞出現在同一個句子中(即數組中的第一句 )。
  3. 在人類(行)x界面(列)中,我們放0,因爲這兩個詞 不在任何句子中都不存在。
  4. 該搜索不區分大小寫。
  5. 然後進入下一列,然後進入下一行。

這是我試過的,但不知何故有什麼錯誤。

public class Test { 

    public static int [][] matrix; 

    public static void main(String[] args) throws Exception { 

     String[] Keywords = {"Human", "Machine", "Interface", "Application" }; 
     String[] Sentence = {"Human is Machine", "Interface of Robot", "Application on Human"}; 

     int [][] matrix = new int[Keywords.length][Keywords.length]; //initialize matrix 

      System.out.println(Arrays.toString(Keywords)); 
      System.out.println("\n"+ Arrays.toString(Sentence)); 



      for (int i=0;i<Keywords.length;i++) 
      { 
       int count = 0; 
       for (int q=1;q<Sentence.length;q++) 
       { 
        if (Keywords[i].contains(Sentence[q])) 
        { 
         matrix[i][q] = count++; 
        } 
       } 
      } 

      System.out.println(Arrays.deepToString(matrix)); 




    } 
} 

任何幫助表示讚賞。謝謝!

回答

3

您的for循環中有一些邏輯錯誤。
With if (Keywords[i].contains(Sentence[q]))您正在檢查關鍵字是否包含句子,而不是相反是否成立。
另一件事是你的矩陣是基於Keywords,但你正在使用Sentence迭代器來指示線。
正確的代碼將

for (int i=0;i<Keywords.length-1;i++){ 
    for(int j = i+1; j < Keywords.length; j++){ 
     int count = 0; 
     for (int q=0;q<Sentence.length;q++){ 
      if(Sentence[q].contains(Keywords[i]) && Sentence[q].contains(Keywords[j])){ 
       count++; 
      } 
     } 
     matrix[i][j] = count; 
     matrix[j][i] = count;   
    } 
} 

這將輸出你的榜樣矩陣。

0

有幾個錯誤你的程序:

if (Keywords[i].contains(Sentence[q])) 

這個條件檢查句子是否包含在一個關鍵字。你想檢查相反的。

matrix[i][q] = count++; 

你爲什麼用這個?如果您找到匹配項,您希望將單元格的值設置爲1。只需將值設置爲1,而不是使用複雜的表達式甚至不工作:

matrix[i][q] = 1; 

一般:
無論您使用的IDE應該提供一個調試器。學會使用它;無論如何,如果你想在更大規模上編寫工作代碼,就無法避免這種情況。