我有以下代码:
for(int sentenceCounter = 0; sentenceCounter < sentences.length; sentenceCounter++)
{
double score = 0;
String[] sentence = sentences[sentenceCounter].split(" ");
for (int titleCounter = 0; titleCounter < titles.length; titleCounter++)
{
for (int wordCounter = 0; wordCounter < sentence.length; wordCounter++)
{
if (titles[titleCounter].equals(sentence[wordCounter]))
{
if(titleCounter == 0)
{
score += titleValue * hundred / 100;
sentenceScore.put(sentenceCounter, score);
System.out.println(sentenceCounter + " " + wordCounter + " " + score);
}else
{
score += titleValue - titleSubtract * hundred / 100;
sentenceScore.put(sentenceCounter, score);
System.out.println(sentenceCounter + " " + wordCounter + " " + sentenceScore.get(0));
}
System.out.println(sentenceCounter);
}
}
}
}
我试图在sentenceCounter增加后重置得分计数器,但是当我在sentenceCounter的for循环后右边设置得分= 0时它不会重置自己。那么,我该如何重置呢?
该计划的步骤如下:1。将标题分成单个单词。 2.将句子分成单个单词。 3.查看句子是否包含标题中的单词。如果是,则将句子得分增加X. 4.重复标题中的下一个单词。 5.如果句子包含标题中的另一个单词,则添加到上一个分数6.对下一句重复此操作,但首先将得分计数器设置为零。这就是我被困住的地方。
这是我从上面代码中观察到的输出:
0 0 10.0
0
0 1 19.3
0
1 5 19.3
1
你可以看到第二句从19.3开始,而不是从零开始。
这是完整的程序:
import java.util.HashMap;
import java.util.Map;
公共类MainDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String fullTitle = "Facebook traffic website";
String[] titles = fullTitle.split(" ");
Double titleValue = 10.0;
Double sentenceSubtract = 13.0;
Double titleSubtract = 0.70;
Double hundred = 100.0;
HashMap<Integer, String> titleArray = new HashMap<Integer, String>();
for(int i =0; i < titles.length; i++)
{
String t = titles[i];
titleArray.put(i, t);
}
String article = "Facebook traffic is growing fast. It is the second largest website. ";
HashMap<Integer, Double> sentenceScore = new HashMap<Integer, Double>();
String[] sentences = article.split("\\. ");
String[] str;
for(int sentenceCounter = 0; sentenceCounter < sentences.length; sentenceCounter++)
{
double score = 0;
String[] sentence = sentences[sentenceCounter].split(" ");
for (int titleCounter = 0; titleCounter < titles.length; titleCounter++)
{
for (int wordCounter = 0; wordCounter < sentence.length; wordCounter++)
{
if (titles[titleCounter].equals(sentence[wordCounter]))
{
if(titleCounter == 0)
{
score += titleValue * hundred / 100;
sentenceScore.put(sentenceCounter, score);
System.out.println(sentenceCounter + " " + wordCounter + " " + score);
}else
{
score += titleValue - titleSubtract * hundred / 100;
sentenceScore.put(sentenceCounter, score);
System.out.println(sentenceCounter + " " + wordCounter + " " + sentenceScore.get(0));
}
System.out.println(sentenceCounter);
}
}
}
}
}
}
答案 0 :(得分:5)
您不需要将在循环体中定义的字段重置为零,它将在下一次迭代中重新创建 -
for(int sentenceCounter = 0; sentenceCounter < sentences.length; sentenceCounter++)
{
double score = 0; // <-- create a score variable, set it to 0.
System.out.println("Score is " + score);
答案 1 :(得分:3)
每次迭代都会重置您的分数计数器。问题是如果titleCounter!= 0,则打印一组不同的值。您希望打印得分的打印到控制台实际上已定义为打印sentenceScore.get(0)
。
这是对的。 sentenceScore.get(0)将是重置为0之前的最后一次迭代的得分值。