好的..所以我正在做一个关于 NLP 的程序。它使用函数 eliminateStopWords()。此函数从二维数组“sentTokens”(检测到的标记)中读取。在下面的代码中,索引 i 是句子编号,j 代表第 i 个句子中的每个标记。
现在,我的 eliminateStopWords() 所做的是:
它从文本文件中读取停用词并将它们存储在 TreeSet 中
从 sentTokens 数组中读取标记并检查它们的停用词。如果它们是搭配,则不应检查停用词,它们只是被转储到 finalTokens 数组中。如果它们不是集合,则会单独检查它们的停用词,并且仅当它们不是停用词时才添加到 finalTokens 数组。
问题出在这第 2 步的循环中。这是它的一些代码:(我在错误实际发生的位置标记了//HERE...它接近尾声)
private void eliminateStopWords() {
try {
// Loading TreeSet for stopwords from the file.
stopWords = new TreeSet<String> ();
fin = new File("stopwords.txt");
fScan = new Scanner(fin);
while (fScan.hasNextLine())
stopWords.add(fScan.nextLine());
fScan.close();
/* Test code to print all read stopwords
iter2 = stopWords.iterator();
while (iter2.hasNext())
System.out.println(iter2.next()); */
int k=0,m=0; // additional indices for finalTokens array
System.out.println(NO_OF_SENTENCES);
newSentence: for(i=0; i < NO_OF_SENTENCES; i++)
{
System.out.println("i = " + i);
for (j=0; j < sentTokens[i].length; j+=2)
{
System.out.println("j = " + j);
// otherwsise, get two successive tokens
String currToken = sentTokens[i][j];
String nextToken = sentTokens[i][j+1];
System.out.println("i = " + i);
System.out.println(currToken + " " + nextToken);
if ( isCollocation(currToken, nextToken) ) {
// if the current and next tokens form a bigram collocation, they are not checked for stop words
// but are directly dumped into finalTokens array
finalTokens[k][m] = currToken; m++;
finalTokens[k][m] = nextToken; m++;
}
if ( !stopWords.contains(currToken) )
{ finalTokens[k][m] = currToken; m++; }
if ( !stopWords.contains(nextToken) )
{ finalTokens[k][m] = nextToken; m++; }
// if current token is the last in the sentence, do not check for collocations, only check for stop words
// this is done to avoid ArrayIndexOutOfBounds Exception in sentences with odd number of tokens
// HERE
System.out.println("i = " + i);
if ( j==sentTokens[i].length - 2) {
String lastToken = sentTokens [i][++j];
if (!stopWords.contains(lastToken))
{ finalTokens[k][m] = lastToken; m++; }
// after analyzing last token, move to analyzing the next sentence
continue newSentence;
}
}
k++; // next sentence in finalTokens array
}
// Test code to print finalTokens array
for(i=0; i < NO_OF_SENTENCES; i++) {
for (j=0; j < finalTokens[i].length; j++)
System.out.print( finalTokens[i][j] + " " );
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
我已经在它们各自的 for 循环的入口处打印了索引 i 和 j ...在循环的第一次迭代中一切正常,但是当循环即将结束时...我已经打印了再次是“我”的值(value)。这次结果是 14。
- 它从 0...开始第一次迭代
- 在循环中的任何地方都不会被操纵...
- 并且就在(仅)第一次迭代结束时,它将值打印为 14
我的意思是,这是我在使用 Java 时遇到的最奇怪的错误。它在最后一个 if block 之前抛出一个 ArrayIndexOutOfBoundsException。就像魔术一样。您对代码中的变量不做任何操作,值仍然发生变化。这怎么会发生?
最佳答案
您从未在代码中声明过 i
或 j
,这让我相信它们是字段。
我很确定您的其他一些方法会重复使用这些变量,从而弄乱您的结果。 isCollocation
看起来很适合它。
for
循环中的计数器应该始终 是局部变量,理想情况下在for
语句本身内声明(用于最小范围)。其他一切都只是自找麻烦(如您所见)。
关于java - 变量自增而不实际改变它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5661767/