我在一个问题上陷入了很长一段时间,这需要我计算一个项 x 项矩阵。所以,我有两个数组,分别是关键字和句子,如下所示:
String[] Keywords = {"Human", "Machine", "Interface", "Application" };
String[] Sentence = {"Human is Machine", "Interface of Robot", "Application on Human"};
接下来,我必须将它们制成表格,如下图所示。
逻辑:
- 如果行和列具有相同的关键字,我们将输入 0。
- 在人类(行)x 机器(列)空间中,我们放入 1,因为这两个
单词在同一个句子中出现一次(即第一个句子)
在数组中)。
- 在 Human(row) x Interface(column) 中,我们输入 0,因为这两个词
两个句子中都不同时存在。
- 搜索不区分大小写。
- 然后继续下一列,然后是下一行。
这是我尝试过的,但不知何故出了问题。
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));
}
}
感谢任何帮助。谢谢!
最佳答案
您的 for
循环中存在一些逻辑错误。
使用 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;
}
}
这将输出您的示例矩阵。
关于java - 计算项 x 项矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40303172/