【问题标题】:Computing terms x terms matrix计算项 x 项矩阵
【发布时间】:2017-03-11 05:36:25
【问题描述】:

我被一个问题困扰了很长时间,这需要我计算一个术语 x 术语矩阵。所以,我有 2 个数组,分别是 keywordssentences,如下所示:

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

接下来,我必须将它们制成表格,如下图所示。

逻辑:

  1. 如果行和列是相同的关键字,我们就输入 0。
  2. 在 Human(row) x Machine(column) 空间中,我们放 1,因为这两个 单词在同一个句子中出现一次(即第一句 在数组中)。
  3. 在 Human(row) x Interface(column) 中,我们输入 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));




    }
}

感谢任何帮助。谢谢!

【问题讨论】:

    标签: java loops matrix multidimensional-array


    【解决方案1】:

    您的forloop 中有一些逻辑错误。
    使用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;        
        }
    }
    

    这将输出您的示例矩阵。

    【讨论】:

      【解决方案2】:

      你的程序有几个错误:

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

      这个条件检查一个句子是否包含在关键字中。你想检查相反的情况。

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

      你为什么用这个?如果找到匹配项,您希望将单元格的值设置为 1。只需将值设置为 1,而不是使用甚至不起作用的复杂表达式:

      matrix[i][q] = 1;
      

      一般来说:
      无论您使用什么 IDE,都应该提供一个调试器。学会使用它;如果您想编写更大规模的工作代码,无论如何都无法避免这种情况。

      【讨论】:

        猜你喜欢
        • 2019-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多